Transformation
Learn about the tools available in Clojure to help develop well-written code.
We'll cover the following
Introduction
Transforming data to achieve what we need is preferable to using a loop iterator. In Clojure, the concept of recursion is favored over iteration in various scenarios because it’s more idiomatic, clean, and to the point.
We’re talking about transforming collections because those are the most widely used data structures in Clojure. In contrast with object-oriented programming languages that rely on the ability to save state and use it to do stuff over time, Clojure focuses on transforming data.
Just to make it clearer, imagine that we need to do a sequence of modifications. Another language would probably use a for loop with some auxiliary variables to get the values during the loop and build the result at the end.
In Clojure, we normally are able to do it with those three main core functions: map
, filter
, and reduce
. They’re used extensively and can probably fix 80% of the problems that we might have. While this percentage is an estimate, through experience, it’s safe to say that they’ll be used a lot.
The map
function
Functions are first-class citizens in Clojure. We can transform our sequence of data by applying a function to each element, and this is what map
does. We can create a function, use symbols, use core functions, or use anything that accesses data or modifies it in place of the predicated. This means we can transform the data we have, but because everything is immutable in Clojure, we create a new sequence with the modifications we’ve made.
The structure of the map
function is (map predicate sequence)
.
Get hands-on with 1400+ tech skills courses.