Skip to content

Instantly share code, notes, and snippets.

@mlimotte
Created April 24, 2012 15:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mlimotte/2480454 to your computer and use it in GitHub Desktop.
Save mlimotte/2480454 to your computer and use it in GitHub Desktop.
Clojure merge-with-key
(ns mlimotte.util)
; A variation on clojure.core/merge-with
(defn merge-with-key
"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 key val-in-result val-in-latter)."
[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 k (get m k) v))
(assoc m k v))))
merge2 (fn [m1 m2]
(reduce merge-entry (or m1 {}) (seq m2)))]
(reduce merge2 maps))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment