Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between :while and :when in clojure?

I'm studying clojure but not quite clear on the difference between the :while and :when test:

=> (for [x [1 2 3] y [1 2 3] :while (= (mod x y) 0)] [x y])
([1 1] [2 1] [2 2] [3 1])
=> (for [x [1 2 3] y [1 2 3] :when (= (mod x y) 0)] [x y])
([1 1] [2 1] [2 2] [3 1] [3 3])

Can anybody help by elaborating on them ?

like image 342
John Wang Avatar asked Jun 10 '12 03:06

John Wang


People also ask

Do while loops Clojure?

Following is the syntax of the 'while' statement. The while statement is executed by first evaluating the condition expression (a Boolean value), and if the result is true, then the statements in the while loop are executed. The process is repeated starting from the evaluation of the condition in the while statement.

How do you define a list in Clojure?

List is a structure used to store a collection of data items. In Clojure, the List implements the ISeq interface. Lists are created in Clojure by using the list function.


1 Answers

:when iterates over the bindings, but only evaluates the body of the loop when the condition is true. :while iterates over the bindings and evaluates the body until the condition is false:

(for [x (range 20) :when (not= x 10)] x)
; =>(0 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19)

(for [x (range 20) :while (not= x 10)] x)
; => (0 1 2 3 4 5 6 7 8 9)
like image 73
Gert Avatar answered Oct 17 '22 05:10

Gert