Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of :let modifier in Clojure

Tags:

clojure

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

like image 345
Horace Avatar asked Jan 04 '13 12:01

Horace


2 Answers

: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)
like image 136
Michiel Borkent Avatar answered Nov 01 '22 23:11

Michiel Borkent


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))
like image 25
sloth Avatar answered Nov 01 '22 22:11

sloth