Some Annotated clojure.core/reduce Examples

Summary: reduce is a very useful function. You can use it for many calculations over a collection. Code annotations are useful, as are physical metaphors.

reduce is used a lot in Clojure. I've heard a lot of people get scared by reduce, like it's something deep and mysterious. It is deep, but it's not mysterious. It's also very loveable for its easy mechanistic application.

I love to watch my toddler doing mechanistic stuff. She picks up a bean and puts it in the cup. She picks up a bean and puts it in the cup. Over. And over. And then I think: that's reduce!

Let's look at a first example. Let's say we want to add up a list of numbers.

(reduce +            ;; let's add
        0            ;; start with zero
        [1 2 3 4 5]) ;; add these numbers to it, one at a time

Imagine holding 0 in your left hand and walking down the list of numbers 1, 2, 3, 4, 5. You approach the number 1. You grab it with your right hand. You have two numbers in your hands. You add them together (+) and hold the answer in your left hand. Now proceed to the next number. Repeat until you're done with the list. At the end, what number are you holding in your left hand? That's the answer.

We can add stuff to a set.

(reduce conj         ;; let's add things to a collection
        #{}          ;; start with an empty set
        [1 2 3 4 5]) ;; add these numbers to it, one at a time

Imagine holding an empty bucket (like the empty set) in your left hand and walking down the list of numbers. When you get to 1, you pick it up in your right hand. Now drop it in the bucket (conj). Proceed to the next number and repeat down the list. What is in your left hand at the end? A bucket with the numbers 1-5. That's the value of this expression.

Alright, we can do something more complicated. This time, let's use an anonymous function. We'll calculate the maximum number from a list.

(reduce (fn [a b]     ;; we can use an anonymous function
          (if (> a b) ;; return the larger of the two
            a
            b))
        0             ;; start with zero
        [1 2 3 4 5])  ;; compare these numbers to it, one at a time

Hold 0 in your left hand and walk down the list. When you get to 1, pick it up. Which is bigger, what's in your left hand or what's in your right hand? Whichever it is, put that in your left hand and proceed to the next number, and so on down the line. The answer is in your left hand.

Hmm. What about averages? We think of averages as the sum of a bunch of numbers divided by the number of numbers. We can keep the sum and the count separate so we can operate on them.

(reduce (fn [[n d] b] ;; `n` is the numerator,
                      ;; `d` is the denominator
          [(+ n b)    ;; add each number to the numerator
           (inc d)])  ;; add 1 to the denominator
        [0 0]         ;; start here
        [1 2 3 4 5])  ;; average these numbers, one at a time

Hold [0 0] in your left hand. Walk down the list. When you get to 1, pick it up in your right hand. Now, add what's in your right hand to the first number in your left hand, and add 1 to the second number in your left hand. Hold the two new numbers in your left hand. Proceed down the line, picking each number up in your right hand, until the end. The answer is in your left hand. UPDATE: I explain this reduce example in more detail here.

Now, one final time, the general pattern:

(reduce (fn [left right] ;; a function of 2 arguments
                         ;; the arguments correspond to your hands
          ;; the return value of this function will be the next
          ;; value in your left hand
          (dosomething left right))
        starting-value ;; what you start with in your left hand
        collection)    ;; the items you grab with your right hand

Conclusions

Well, that was fun. reduce is not hard. You just need a good way of thinking about it. Physical metaphors can help a ton. I wish I could have made this visual with a cartoon, but that would take more time and skill than I have. And I think the code annotations really help add context to what would otherwise be very terse code. Context is so important.

If you liked the code annotations and this style of teaching the basics, you will love Lispcast Introduction to Clojure. It has lots of visuals, lots of metaphors, exercises, and code annotations. It teaches the basics of Clojure and functional programming in a fun way. Check out a preview.