Skip to content

Instantly share code, notes, and snippets.

@thebusby
Created July 8, 2012 02:45
Show Gist options
  • Save thebusby/3069091 to your computer and use it in GitHub Desktop.
Save thebusby/3069091 to your computer and use it in GitHub Desktop.
(defn rindex-by-fn
"Uses core.reducers/fold to return a map indexed by the value of key-fn
applied to each element in coll.
Note: key-fn can return a collection of multiple keys."
([key-fn coll ] (rindex-by-fn key-fn identity coll))
([key-fn value-fn coll] (doall (clojure.core.reducers/fold
;; combinef
(clojure.core.reducers/monoid (partial merge-with into)
hash-map)
;; reducef
(fn [ndx elem] (let [key (key-fn elem)]
(if (coll? key)
(reduce (fn [sndx selem] (assoc sndx selem (conj (get sndx selem [])
(value-fn elem))))
ndx key)
(assoc ndx key (conj (get ndx key [])
(value-fn elem))))))
coll))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment