Annotated map

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            ;; add 1
     [0 1 2 3 4 5]) ;; to each of these

  => (1 2 3 4 5 6)  ;; 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           ;; get the size
     [[]             ;; of each of these
      [1]
      [1 1]
      [1 1 1]
      [1 1 1 1]
      [1 1 1 1 1]])

  => (0 1 2 3 4 5)  ;; 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          ;; keywords are functions, too
     [{:a 1}     ;; look at these little maps, just waiting there!
      {:a 2}
      {:a 3}
      {:b 4}])

  => (1 2 3 nil) ;; 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) "!!")) ;; our epic function
     ["I am angry"                        ;; make these angry!!!
      "don't yell at me"
      "stop yelling"])

  => ("I AM ANGRY!!"                      ;; LOOK AT THEM!!
      "DON'T YELL AT ME!!"
      "STOP YELLING!!")

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 Beginning 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.