Reputation: 1208
I wonder what is the sense of a :let
modifier when using the for
loop in Clojure?
Upvotes: 7
Views: 810
Reputation: 34820
:let
lets you define named values, in the same sense that the let special form lets you do it:
(for [i (range 10)
:let [x (* i 2)]]
x) ;;=> (0 2 4 6 8 10 12 14 16 18)
is equivalent to:
(for [i (range 10)]
(let [x (* i 2)]
x)) ;;=> (0 2 4 6 8 10 12 14 16 18)
except when used in combination with :when
(or :while
):
(for [i (range 10)
:let [x (* i 2)]
:when (> i 5)]
x) ;;=> (12 14 16 18)
(for [i (range 10)]
(let [x (* i 2)]
(when (> i 5) x))) ;;=> (nil nil nil nil nil nil 12 14 16 18)
Upvotes: 10
Reputation: 101072
You can use :let
to create bindings inside a list comprehension like let
.
To quote an example of the clojure documentation:
user=> (for [x [0 1 2 3 4 5]
:let [y (* x 3)]
:when (even? y)]
y)
(0 6 12)
The trick is that you can now use y
in the :while
and :when
modifiers, instead of writing something like
user=> (for [x [0 1 2 3 4 5]
:when (even? (* x 3))]
(* x 3))
Upvotes: 1