clojure equivalent of python defaultdict



假设我们有一个函数f,它返回一个可以用作字典键的值:

d = defaultdict(set)
for x in xs:
    d[f(x)].add(x)

结构可能看起来像这样,但我不知道如何a)提供一个默认值和b)与现有值

合并
(defn build-maps [xs]
  (let [inverse-map {}]
    (reduce (fn [im x]
              (let [y (f x)
                    im' (assoc im y x)] ; want to add x to a set
                im')) inverse-map xs)))

更新,下面似乎可以工作

(defn build-maps [xs]
  (let [inverse-map {}]
    (reduce (fn [im x]
              (let [y (f x)
                    new-im (assoc im y (set/union (im y) #{x}))]
                new-im)) inverse-map xs)))

我的写法是:

(apply merge-with into
       (for [x xs]
         {(f x) #{x}}))

但是如果你想要更接近于基于reduce的计划,你可以这样写:

(reduce (fn [m x]
          (update m (f x) (fnil conj #{}) x))
        {}, xs)

最新更新