Database Reference
In-Depth Information
Combining function calls with reducers
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 inal 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.
Getting ready
The primary dependency that we'll need for this is the
reducers
library, but we'll also use
the
clojure.string
library:
(require '[clojure.string :as str]
'[clojure.core.reducers :as r])
How to do it…
To illustrate this feature of reducers, we'll take a sequence of words and run them through
a series of transformations. We'll take a look at how Clojure handles these both with and
without the
reducers
library.