Created
July 8, 2012 02:45
-
-
Save thebusby/3069091 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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