cgrand / xforms

Extra transducers and reducing fns for Clojure(script)
573 stars 32 forks source link

x/by-key with multiple transducers? #53

Open imrekoszo opened 9 months ago

imrekoszo commented 9 months ago

Hey Christophe,

I ran into situations a few times when I wanted to use x/by-key but run different transducers on values belonging to different keys.

Example:

(x/into {} (x/by-key odd? (x/reduce +)) (range 1 10))

but imagine we want the sum of odd numbers but the product of evens.

Something like this for example:

(x/into {}
  (x/by-key odd?
    {true (x/reduce +)
     false (x/reduce *)})
  (range 1 10))
; {true 25, false 384}

The last arg could be a function of key->xform in this example.

Not sure if there is already an idiomatic way to do this using the library? If not, would you consider including this functionality in some way? Or, alternatively, would you consider situations like this a code smell?

cgrand commented 9 months ago

what about (x/transjuxt {true (comp (filter odd?) (x/reduce +)) false (comp (remove odd?) (x/reduce * ))}?

imrekoszo commented 9 months ago

Yeah, that's an option for sure, but what bug me are:

(x/by-key
  (fn [k]
    (cond
      (< k 5) (x/reduce +)
      (odd? k) (x/reduce *)
      :else (x/into []))))