Created
December 7, 2012 09:15
-
-
Save balinterdi/4232044 to your computer and use it in GitHub Desktop.
Implement group-by with reducers
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
(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