Welcome! Please see the About page for a little more info on how this works.

+11 votes
in Transducers by
retagged by

I often find myself writing a reducing function that does what group-by does. It would be convenient to have group-by return a reducing function (without needing to import Christophe Grand's xforms lib). So instead of writing:

  (->> (range 10)
       (transduce (map inc) (completing (fn [r x] (update r (even? x) (fnil conj []) x))) {}))

I could write:

  (->> (range 10)
       (transduce (map inc) (group-by even?)))

Maybe something like this?

  (defn group-by
       ([] (transient {}))
       ([r] (persistent! r))
       ([r x]
        (let [k (f x)]
          (assoc! r k (conj (get r k []) x))))))
    ([f coll]  
       (fn [ret x]
         (let [k (f x)]
           (assoc! ret k (conj (get ret k []) x))))
       (transient {}) coll))))

1 Answer

+1 vote