Transducers
Clojure 1.7 introduced a new abstraction called transducers for "composable algorithmic transformations", commonly used to apply a series of transformations over collections. The idea of transducers follows from the reducing function, which accepts arguments of the form (result, input
) and returns result
. A reducing function is what we typically use with reduce. A transducer
accepts a reducing function, wraps/composes over its functionality to provide something extra, and returns another reducing function.
The functions in clojure.core
that deal with collections have acquired an arity-1
variant, which returns a transducer, namely map
, cat
, mapcat
, filter
, remove
, take
, take-while
, take-nth
, drop
, drop-while
, replace
, partition-by
, partition-all
, keep
, keep-indexed
, dedupe
and random-sample
.
Consider the following few examples, all of which do the same thing:
user=> (reduce ((filter odd?) +) [1 2 3 4 5]) 9 user=> (transduce (filter odd?) + [1 2 3 4 5]) 9 user=>...