Sunday, July 19, 2015

Clojure for macro keywords

These docs weren't incredibly helpful in figuring out the difference between :when and :while.
The examples
(for [x [1 2 3]
  y [1 2 3]
  :while (<= x y)
  z [1 2 3]]
  [x y z])
and

(for [x [1 2 3]
  y [1 2 3]
  z [1 2 3]
  :while (<= x y)]
  [x y z])

come close to exposing the difference, but what should really be stated explicitly somewhere is that :while stops attempting to evaluate at the first false result whereas (almost said while there >.> ) :when continues to try to evaluate after the false.

(for [x [1 2 3]
  y [1 2 3]
  :while (= x y)
  z [1 2 3]]
  [x y z])
;;([1 1 1] [1 1 2] [1 1 3])
(for [x [1 2 3]
  y [1 2 3]
  :when (= x y)
  z [1 2 3]]
  [x y z])
;;([1 1 1] [1 1 2] [1 1 3] [2 2 1] [2 2 2] [2 2 3] [3 3 1] [3 3 2] [3 3 3])

Perhaps I'm dense but this wasn't immediately obvious to me.

Edit: Or perhaps I should have actually read. Example 8 is pretty explicit. >.<

No comments: