Annotated map

From OO to Clojure Workshop!
Watch my free workshop to help you learn Clojure faster and shift your paradigm to functional.
Summary: map
is one of the staples of functional programming. It's
totally useful and also surprisingly simple. Let's look at some
examples and annotated code.
About a week ago I showed some examples of using
reduce
, a very
commonly used function. This time, I'm going to give some examples of
map
, which is probably even more common.
map
is one of those things that's so useful and so straightforward
that it finds its way into every language. Javascript has a map
in the
newer versions, but people couldn't live without it so it's in a lot
of Javascript libraries (for example, in
Underscore).
Let's imagine you're walking down a list [0 1 2 3 4 5]
. Your job is
to increment each one. As you pass each each number on your right you
pick it up, add one to it, and put it down on your left. Boom, a new
list on your left.
(map inc [0 1 2 3 4 5])
=> (1 2 3 4 5 6)
add 1
to each of these
it returns a new list with the numbers incremented
Ok, next one. Let's say you're walking down a list . . . of lists. Your job? Write down the sizes of those lists. Let's do it! Walk down the list, pick up each list as you go, and drop the size to your left. You just made a new list!
(map count
[[]
[1]
[1 1]
[1 1 1]
[1 1 1 1]
[1 1 1 1 1]])
=> (0 1 2 3 4 5)
get the size
of each of these
a list of the sizes
Alright, let's get fun with this one. You walk down a list of maps.
Your job? figure out what's under the :a
key. Drop the answers on the
left. Remember, if the map doesn't have the list, it gives you nil
.
(map :a
[{:a 1}
{:a 2}
{:a 3}
{:b 4}])
=> (1 2 3 nil)
keywords are functions, too
look at these little maps, just waiting there!
look, the last one was nil
Ok, here's a good one. Someone wrote a bunch of sentences, but you want to make them angry. ALL CAPS!! Walk down the list, apply this epic function to each, and make a new list!
(map (fn [x] (str (.toUpperCase x) "!!"))
["I am angry"
"don't yell at me"
"stop yelling"])
=> ("I AM ANGRY!!"
"DON'T YELL AT ME!!"
"STOP YELLING!!")
our epic function
make these angry!!!
LOOK AT THEM!!
Conclusions
Yep, map
is useful. It's one of the staples of functional
programming. Once you start using it, you'll use it everywhere.
If you liked the code with annotations, the physical metaphors, the focus on the basics, you will love Lispcast Introduction to Clojure. Visuals, metaphors, exercises, annotated code, and lots of code in a repo. You learn the basics of Clojure down to your fingertips, writing code right away.