5

我正在尝试使用 clojure 惯用地将多个地图合并到一个地图中。

输入

{:a 1 :b "a"}
{:a 2 :b "b"}
{:a 3 :b "c"}
{:a 4 :b "a"}

预期的

{:a #{1,2,3,4}, :b #{"a" "b" "c"}} 

每个键的值都转换为原始映射中的一组值。

4

7 回答 7

5

我会使用merge-with,使用包含空集的预构建结构:

(def data [{:a 1 :b "a"}
           {:a 2 :b "b"}
           {:a 3 :b "c"}
           {:a 4 :b "a"}])

(let [base {:a #{} :b #{}}]
  (apply merge-with conj base data))

=> {:a #{1 2 3 4}, :b #{"a" "b" "c"}}

在基本地图中使用空集的技巧是conj有一个具体的对象可以处理,因此可以正常工作。

于 2012-06-27T14:48:52.203 回答
4

merge-with可以用于这样的:

(def d [{:a 1 :b "a"}
        {:a 2 :b "b"}
        {:a 3 :b "c"}
        {:a 4 :b "a"}])

(def initial (into {} (map #(vector  %1 [])  (keys (apply merge d)))))

(into {} (map (fn [[a b]] [a (set b)]) 
           (apply merge-with (fn [a b] (conj a b)) initial  d)))
于 2012-06-27T12:18:24.640 回答
2
(defn value-sets [& maps]
  (reduce (fn [acc map]
            (reduce (fn [m [k v]]
                      (update-in m [k] (fnil conj #{}) v))
                    acc
                    map))
          {} maps))

编辑或也许

(defn value-sets [& maps]
  (reduce (fn [acc [k v]]
            (update-in acc [k] (fnil conj #{}) v))
          {}
          (apply concat maps)))

多年后的进一步编辑:我现在会以不同的方式写这个:

(defn value-sets [maps]
  (apply merge-with into (for [m maps, [k v] m] 
                           {k #{v}})))
于 2012-06-27T18:44:00.353 回答
1

看到 amalloy 的解决方案reduce向我建议了这个:

(def maps [{:a 1 :b 2}
           {:a 11 :b 22 :c 5}
           {:c 6 :a 7}])

(defn my-merge-maps
  [maps]
  (reduce (fn [accum [k v]]
            (if (accum k)
              (assoc accum k (conj (accum k) v))
              (assoc accum k #{v})))
          {}
          (apply concat maps)))

(defn -main
  []
  (println (my-merge-maps maps)))

结果是:{:c #{5 6}, :b #{2 22}, :a #{1 7 11}}

(感谢 gfredericks 指出我不小心使用了可变参数。:))

编辑:这是另一种方式,使用merge-with

(def maps [{:a 1 :b 2}
           {:a 11 :b 22 :c 5}
           {:c 6 :a 7}])

(defn build-up-set
  [curr-val new-val]
  (if (set? curr-val)
    (conj curr-val new-val)
    #{curr-val new-val}))

(defn my-merge-maps
  [maps]
  (apply merge-with build-up-set maps))

(defn -main
  []
  (println (my-merge-maps maps)))
于 2012-06-28T19:24:58.633 回答
0

这是一个流水线方法:

(defn my-merge-maps [stuff]
  (->> stuff
       (apply concat)
       (group-by first)
       (map (fn [[k vs]] [k (set (map second vs))]))
       (into {})))

如果我们有正确的核心函数来操作它们,这可以在地图中完成吗?

于 2014-03-17T16:00:00.813 回答
0
(def data [{:a 1 :b "a"}
           {:a 2 :b "b"}
           {:a 3 :b "c"}
           {:a 4 :b "a"}])

(apply
  merge-with
  clojure.set/union
  (map #(zipmap (keys %) (map hash-set (vals %))) data))
;{:b #{"a" "b" "c"}, :a #{1 2 3 4}}
于 2014-07-19T08:47:33.570 回答
0

Amalloy 昨天在 IRC 上针对同一问题放弃了以下解决方案:

(defn value-sets [& maps]                                                      
  (apply merge-with into (for [m maps, [k v] m] {k #{v}})))
于 2017-05-30T08:37:55.857 回答