Created
February 27, 2012 18:04
-
-
Save bnyeggen/1925891 to your computer and use it in GitHub Desktop.
More flexible group-by
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 flexigroup | |
"Like group-by, but allows arbitrary calculation of keys and values from | |
source coll, (for instance, to roll up distinct particular elements of a | |
vector by distinct other parts) and arbitrary combinations of old and new | |
vectors (for instance, to perform an efficient online count). | |
(flexigroup identity identity conj [] coll) == group-by | |
(flexigroup identity identity (fn [a b] (inc a)) 0) == online count | |
(flexigroup #(subvec % 0 1) #(subvec % 1) conj #{} coll) == all the | |
distinct rests of the vectors, grouped by the first element" | |
[key-f val-f combine-f init-v coll] | |
(persistent! | |
(reduce | |
(fn [ret x] | |
(let [k (key-f x)] | |
(assoc! ret k (combine-f (get ret k init-v) (val-f x))))) | |
(transient {}) coll))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment