合并地图列表并将值组合到Clojure中的集合

时间:2010-02-04 21:05:37

标签: functional-programming clojure

我可以将 FOO 放在哪里以最终产生真实效果?我玩哈希集(只对前2个值正确),conj和concat,但我知道我没有正确处理单元素与设置条件中的任何一个。

(defn mergeMatches [propertyMapList]
    "Take a list of maps and merges them combining values into a set"
    (reduce #(merge-with FOO %1 %2) {} propertyMapList))

(def in 
    (list
        {:a 1}
        {:a 2}
        {:a 3}
        {:b 4}
        {:b 5}
        {:b 6} ))

(def out
    { :a #{ 1 2 3}
      :b #{ 4 5 6} })

; this should return true
(= (mergeMatches in) out)

最常用的处理方式是什么?

6 个答案:

答案 0 :(得分:12)

这样做:

(let [set #(if (set? %) % #{%})]
  #(clojure.set/union (set %) (set %2)))

更直接地重写示例(Alex):

(defn to-set [s]
    (if (set? s) s #{s}))
(defn set-union [s1 s2] 
    (clojure.set/union (to-set s1) (to-set s2)))
(defn mergeMatches [propertyMapList]
    (reduce #(merge-with set-union %1 %2) {} propertyMapList))

答案 1 :(得分:5)

我没有写这个,但是contributed @amitrathore Twitter上的{{3}}:

(defn kv [bag [k v]] 
  (update-in bag [k] conj v))
(defn mergeMatches [propertyMapList]
  (reduce #(reduce kv %1 %2) {} propertyMapList))

答案 2 :(得分:4)

我不会使用merge-with,

(defn fnil [f not-found]
  (fn [x y] (f (if (nil? x) not-found x) y)))
(defn conj-in [m map-entry]
  (update-in m [(key map-entry)] (fnil conj #{}) (val map-entry)))
(defn merge-matches [property-map-list]
  (reduce conj-in {} (apply concat property-map-list)))

user=> (merge-matches in)
{:b #{4 5 6}, :a #{1 2 3}}

fnil将很快成为核心的一部分,因此您可以忽略实现......但它只是创建了另一个可以处理nil参数的函数的版本。在这种情况下,conj会将#{}替换为nil。

因此,对于提供的地图列表中的每个键/值,减少连接到一个集合。

答案 3 :(得分:3)

@wmacgyver根据Twittermultimaps提供的另一个解决方案:

(defn add
  "Adds key-value pairs the multimap."
  ([mm k v]
     (assoc mm k (conj (get mm k #{}) v)))
  ([mm k v & kvs]
     (apply add (add mm k v) kvs)))
(defn mm-merge
  "Merges the multimaps, taking the union of values."
  [& mms]
  (apply (partial merge-with union) mms))   

(defn mergeMatches [property-map-list]
  (reduce mm-merge (map #(add {} (key (first %)) (val (first %))) property-map-list)))      

答案 4 :(得分:2)

不是很漂亮,但它确实有效。

(defn mergeMatches [propertyMapList]
    (for [k (set (for [pp propertyMapList] (key (first pp))))]
         {k (set (remove nil? (for [pp propertyMapList] (k pp))))}))

答案 5 :(得分:2)

这似乎有效:

(defn FOO [v1 v2]
      (if (set? v1)
          (apply hash-set v2 v1)
          (hash-set v1 v2)))