Reduce

Sometimes you don’t need to transform each item of a collection the way that map or for does. Sometimes what you need is to combine all the elements of a collection into a single value. For this we have reduce. Like map, reduce takes a function and a sequence and calls the function for each item in the sequence. Unlike map, reduce passes two arguments to the function—along with the element from the collection, your function gets called with the current result. Each time reduce calls your function, it updates the current result with the return value from that call. When reduce runs out of elements, it returns the last result.

Although there are a lot of variations on how you can use reduce, the easiest to grasp is where you pass in three ...

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.