John Wang
John Wang

Reputation: 4692

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 ?

Upvotes: 17

Views: 2715

Answers (3)

Gert
Gert

Reputation: 3859

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

Upvotes: 29

Dimagog
Dimagog

Reputation: 1925

Look at the last example here: http://clojuredocs.org/clojure_core/clojure.core/for#example_913

Upvotes: 1

Chouser
Chouser

Reputation: 5208

:when prevents any inner 'for' bindings or its body expression from being evaluated for that one iteration, acting like the 'filter' function.

:while halts this binding from proceeding any more, acting more like 'take-while'

Upvotes: 8

Related Questions