cgrand / xforms

Extra transducers and reducing fns for Clojure(script)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

x/by-key with multiple transducers?

imrekoszo opened this issue · comments

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?

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

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

  • kfn (odd?) is not only written repeatedly, it will be called on every item for every possible key (twice in this case)
  • no vfn means I cannot simply ignore the key in cases when I don't need it for the transduction
  • xforms-map is static so all the possible keys need to be typed out and I can't provide something like the following:
(x/by-key
  (fn [k]
    (cond
      (< k 5) (x/reduce +)
      (odd? k) (x/reduce *)
      :else (x/into []))))