O'Reilly logo

Web Development with Clojure by Dmitri Sotnikov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required