{:check ["true"]}
box
Section 2.6 - 2.7
The general form is:
(loop [<symbol> <initial-value>
<symbol> <initial-value>
...]
exprs*)
This evaluates to the last evaluated expression when the loop terminates.
The loop can contain:
(recur <value> <value> ...)
This starts the next iteration with new values for the <symbol>
in the loop-binding.
;
; Print messages
;
(loop [n 0]
(when (< n 10)
(do (println "Hello" n)
(recur (inc n)))))
;
; Construct a sequence backwards
;
(loop [result []
x 10]
(if (zero? x)
result
(recur (conj result x) (dec x))))
;
; x^2 + 4*y = x * y
;
(defn solution? [x y] (= (+ (* x x) (* 4 y)) (* x y)))
(loop [x 0
y 0
result []]
(let [result' (if (solution? x y)
(conj result [x, y])
result)]
(cond
(< y 100) (recur x (inc y) result')
(< x 100) (recur (inc x) 0 result')
:else result)))
;
; The equivalent form in (for...)
;
(for [x (range 100)
y (range 100)
:when (solution? x y)]
[x y])