Threading Expressions

By this point you’ve probably noticed that nested expressions can be difficult to read. Fortunately, Clojure provides a couple of helper forms to deal with this problem. Let’s say we have a range of numbers, and we want to increment each number, interpose the number 5 between them, and then sum the result. We could write the following code to do that:

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

It’s a little difficult to tell what’s happening in the preceding example at a glance. With a few more steps in the chain, 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 re-nest all our expressions. An alternative way to write this ...

Get Web Development with Clojure, 2nd Edition 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.