Clojure 1.5 introduced the clojure.core.reducers
library. This library provides a lot of interesting and exciting features. It allows you to compose multiple calls to map
and other sequence-processing, high-order functions. This also makes it possible to abstract map
and other functions for different types of collections while maintaining the collection type.
Looking at the following chart, initial operations on individual data items such as map
and filter
operate on items of the original dataset. Then, the outputs of the operations on the items are combined using a reduce function. Finally, the outputs of the reduction step are progressively combined until the final result is produced. This might involve a reduce-type operation (such as addition), or an accumulation (such as the into
function).
In this recipe, we'll take a look at how we can use reducers to minimize the number of sequences that Clojure creates and immediately throws away.