Usage: let modifier in Clojure

I wonder what is the meaning of the :let modifier when using the for loop in Clojure?

+4
source share
2 answers

:let allows you to define named values ​​in the same sense as the special let form allows you to do this:

 (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) 

unless 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) 
+5
source

You can use :let to create bindings inside a list comprehension, such as let .

To give an example of 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 now you can use y in :while and :when modifiers instead of writing something like

 user=> (for [x [0 1 2 3 4 5] :when (even? (* x 3))] (* x 3)) 
+1
source

All Articles