May 2018
Beginner to intermediate
290 pages
6h 43m
English
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 ...
Read now
Unlock full access