merge-with

clojure.core

  • (merge-with f & maps)
Returns a map that consists of the rest of the maps conj-ed onto
the first. If a key occurs in more than one map, the mapping(s)
from the latter (left-to-right) will be combined with the mapping in
the result by calling (f val-in-result val-in-latter).

4 Examples top

  • user=> (merge-with concat
    		  {"Lisp" ["Common Lisp" "Clojure"]
    		   "ML" ["Caml" "Objective Caml"]}
    		  {"Lisp" ["Scheme"]
    		   "ML" ["Standard ML"]})
    {"Lisp" ("Common Lisp" "Clojure" "Scheme"), "ML" ("Caml" "Objective Caml" "Standard ML")}
    
    user=> (clojure.pprint/pp)
    {"Lisp" ("Common Lisp" "Clojure" "Scheme"), "ML" ("Caml" "Objective Caml" "Standard ML")}
    nil
    
  • ;; merge two maps using the addition function
    
    user=> (merge-with + 
                       {:a 1  :b 2}
                       {:a 9  :b 98 :c 0})
        
    {:c 0, :a 10, :b 100}
  • ;; 'merge-with' works with an arbitrary number of maps:
    
    user=> (merge-with + 
                       {:a 1  :b 2}
                       {:a 9  :b 98  :c 0}
                       {:a 10 :b 100 :c 10}
                       {:a 5}
                       {:c 5  :d 42})
        
    {:d 42, :c 15, :a 25, :b 200}
  • ;; Use union to merge sets of elements
    user=> (use 'clojure.set)
    user=> (merge-with union
                       {:a #{1 2 3},   :b #{4 5 6}}
                       {:a #{2 3 7 8}, :c #{1 2 3}})
    
    {:c #{1 2 3}, :a #{1 2 3 7 8}, :b #{4 5 6}}
Log in to add / edit an example.

See Also top

  • 1
    clojure.core/merge

    Returns a map that consists of the rest of the maps conj-ed onto th

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:2631 top

(defn merge-with
  "Returns a map that consists of the rest of the maps conj-ed onto
  the first.  If a key occurs in more than one map, the mapping(s)
  from the latter (left-to-right) will be combined with the mapping in
  the result by calling (f val-in-result val-in-latter)."
  {:added "1.0"
   :static true}
  [f & maps]
  (when (some identity maps)
    (let [merge-entry (fn [m e]
			(let [k (key e) v (val e)]
			  (if (contains? m k)
			    (assoc m k (f (get m k) v))
			    (assoc m k v))))
          merge2 (fn [m1 m2]
		   (reduce1 merge-entry (or m1 {}) (seq m2)))]
      (reduce1 merge2 maps))))
Vars in clojure.core/merge-with:
Used in 0 other vars

Comments top

No comments for merge-with. Log in to add a comment.