macro | since v0.0-927 | imported clojure.core/->> | Edit |
(->> x & forms)
The thread-last macro "threads" an expression through several forms as the last item in a list.
Inserts x
as the last item in the first form, making a list of it if it is not
a list already. If there are more forms, inserts the first form as the last item
in second form, etc.
Code | Expands To |
---|---|
(->> x (a b c) d (x y z)) |
(x y z (d (a b c x))) |
Sequence transformation functions often take a sequence as the last argument, thus the thread-last macro is commonly used with them. Here we compute the sum of the first 10 even squares:
(->> (range)
(map #(* % %))
(filter even?)
(take 10)
(reduce +))
;;=> 1140
This expands to:
(reduce +
(take 10
(filter even?
(map #(* % %)
(range)))))
;;=> 1140
Threads the expr through the forms. Inserts x as the last item in the first form, making a list of it if it is not a list already. If there are more forms, inserts the first form as the last item in second form, etc.
(defmacro ->>
{:added "1.1"}
[x & forms]
(loop [x x, forms forms]
(if forms
(let [form (first forms)
threaded (if (seq? form)
(with-meta `(~(first form) ~@(next form) ~x) (meta form))
(list form x))]
(recur threaded (next forms)))
x)))