Skip to content

Instantly share code, notes, and snippets.

@wilkes
Created February 21, 2009 17:05
Show Gist options
  • Save wilkes/68097 to your computer and use it in GitHub Desktop.
Save wilkes/68097 to your computer and use it in GitHub Desktop.
;; reduce is the key here
(def s [{:pk 1 :data "a"} {:pk 2 :data "b"} {:pk 3 :data "c"}])
(def h (reduce (fn [result item] (merge result {(:pk item) item})) {} s))
;; anonymous function version
(def h2 (reduce #(merge %1 {(:pk %2) %2}) {} s))
;; h is {3 {:pk 3, :data "c"}, 2 {:pk 2, :data "b"}, 1 {:pk 1, :data "a"}}
;; general form
(defn m-of-ms
"given a key and seq of maps create a map of maps index by key"
[k s]
(reduce #(merge %1 {(k %2) %2}) {} s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment