Skip to content

Instantly share code, notes, and snippets.

@jeroenvandijk
Forked from fxposter/group_by.clj
Last active October 1, 2015 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeroenvandijk/a65b4938fc297a335b20 to your computer and use it in GitHub Desktop.
Save jeroenvandijk/a65b4938fc297a335b20 to your computer and use it in GitHub Desktop.
group-by as a transducer
(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