Threading Expressions

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (72 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Closures | TOC | Being Lazy 👉

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 expression is to use the ->> form:

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

Here, we use ->> to thread the operations from one to the next. This means that we implicitly pass the result of each expression as the last argument of the next one. To pass it as the first argument, we’d use the -> form instead.

👈 Closures | TOC | Being Lazy 👉

Web Development with Clojure, Third Edition by Dmitri Sotnikov, Scot Brown can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.