Skip to content

Instantly share code, notes, and snippets.

@bnyeggen
Created February 27, 2012 18:04
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 bnyeggen/1925891 to your computer and use it in GitHub Desktop.
Save bnyeggen/1925891 to your computer and use it in GitHub Desktop.
More flexible group-by
(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