Threading Expressions

As you might suspect by now, expressions can become difficult to read if they’re deeply nested. Luckily for us, Clojure provides a couple of helper forms to address this problem. Let’s say we have a range of ten numbers, and we want to increment each number, interpose the number 5 between them, then sum the result. We could write the following:

 
(​reduce​ ​+​ (​interpose​ 5 (​map​ ​inc​ (​range​ 10))))

It’s a little difficult to tell what’s happening in that expression at first glance. If each step were even a little more complex, we’d be really lost. On top of that, if we wanted to rearrange any of the steps, such as interposing 5 before incrementing, then we’d have to renest all our expressions.

An alternative way ...

Get Web Development with 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.