Skip to content

Instantly share code, notes, and snippets.

@balinterdi
Created December 7, 2012 09:15
Show Gist options
  • Save balinterdi/4232044 to your computer and use it in GitHub Desktop.
Save balinterdi/4232044 to your computer and use it in GitHub Desktop.
Implement group-by with reducers
(ns group-by-reducers.core
(:require [clojure.core.reducers :as r :only [fold reduce map]])
(:require [criterium.core :as c]))
(defn group-by-naive [f coll]
(reduce
(fn [groups a]
(assoc groups (f a) (conj (get groups a []) a)))
{}
coll))
(defn group-by-red [f coll]
(letfn [(reduce-groups
([] {})
([g1 g2]
(merge-with concat g1 g2)))]
(r/fold reduce-groups (r/map #(hash-map (f %) [%]) coll))))
(defn -main
[& args]
(c/quick-bench (group-by #(mod % 29) (range 10000)))
(c/quick-bench (group-by-naive #(mod % 29) (range 10000)))
(c/quick-bench (group-by-red #(mod % 29) (range 10000))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment