Using Transducers in Clojure

I’ve been trying to internalize clojure transducers better of late and I saw this post from Eric Normand. He talks about two ways to “Name your callbacks”.

Option 1: Name the steps

(->> customers
  select-best-customers
  get-biggest-purchases)

Option 2: Name the callbacks

(->> customers
  (filter good-customer?)
  (map biggest-purchase))

Like Eric, I prefer the second option but there is another reason to prefer #2. The two statements inside the thread macro ->> can live outside it as transducers. So I can do something like:

(def xf-good-customers (filter good-customer?))
(def xf-biggest-purchases (map biggest-purchase))
(into [] (comp xf-good-customers xf-biggest-purchases) customers)

That will return the same thing and now customers can be anything that transducers will work on (a collection, a async channel, etc.) and I believe it is more efficient.

I suppose you could also rewrite his select-best-customers and get-biggest-purchases function as transducers and get the same thing.