-
-
Save jeroenvandijk/a65b4938fc297a335b20 to your computer and use it in GitHub Desktop.
group-by as a transducer
This file contains hidden or 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 group-by | |
([f] | |
(fn [rf] | |
(let [grouped-value (volatile! (transient {}))] | |
(fn | |
([] (rf)) | |
([result] | |
(rf result (persistent! @grouped-value))) | |
([result input] | |
(let [key (f input)] | |
(vswap! grouped-value assoc! key (conj (get @grouped-value key []) input)) | |
result)))))) | |
([f coll] | |
(into {} (group-by f) coll))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment