Nested calls can become hard to manage. Threading macros help us take control. In this chapter, we'll learn about the concept of threading macros and study three commonly-used versions.
thread has got nothing to do with parallel programming. Thread is an expression for a linear series of operations, like pearls on a thread.
As your functions grow in complexity, the readability of your code is affected. Suppose you have a list of books with various attributes, and you want to find the number of books related to each unrestricted book:
The complexity of that
map operation can easily grow beyond control. What happens if we want the publishing year of all related books?:
We performed the following operations:
filtered all books that are restricted
publish-year-by-idfunction on each element of
Threading macros help decomplect nested function calls.
thread-last macro (
thread-last macro makes nested function calls easier to express. A function call:
can be expressed as:
In thread-last macro expansion, the result of a form is passed as the last argument to the next form. Let's rewrite our
publish-year-by-id with the thread-last macro:
Notice how we are able to use the
first function and
:publish-year keyword without parentheses. You can add parentheses if you wish to, but Clojure assumes parentheses in cases where a callable form is passed. Most developers find forms using threading macros more readable.
Let's rewrite the other operation using the thread-last macro too: