Map

Another thing we might want to do with a collection is transform it by evaluating a function on each element. We might, for example, have a collection of numbers and want a collection of all the numbers doubled. Here Clojure provides you with a choice.

Behind door number one is map. The map function takes a function and a collection and gives you back a sequence cooked up by applying the function to each member of the original collection. So if we started with some numbers:

 (​def​ some-numbers [1, 53, 811])

and we wanted to double them, we could write this:

 (​def​ doubled (map #(* 2 %) some-numbers))

Or if we had our collection of book maps and we just wanted the titles, we could do this:

 (map (​fn​ [book] (:title book)) books)

which ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.