{:check ["true"]}

Index

Sequence iteration with side-effects

Doseq

Recall the for iteration over sequences.

(for [binding...]
    expr)

The for form evaluates to the resulting sequence.

Sometimes, we just want to perform some side-effects during the iteration, and not accumulate any resulting sequence.

In [7]:
;
; Print the solutions of x^2 + 4y = x * y
; for x in 0 .. 100 and y in 0 .. 100
;
(for [x (range 100)
      y (range 100)
      :when (= (+ (* x x) (* 4 y)) (* x y))]
    (println "x" x "y" y))
Out[7]:
(x 0 y 0
x 5 y 25
nil x 6 y 18
nil x 8 y 16
nil x 12 y 18
nil x 20 y 25
nil nil)

doseq: sequence iteration with side-effects

Clojure provides a near-identical form:

(doseq [binding*]
    expr*)
In [4]:
;
; Print the solutions of x^2 + 4y = x * y
; for x in 0 .. 100 and y in 0 .. 100
;
(doseq [x (range 100)
        y (range 100)
      :when (= (+ (* x x) (* 4 y)) (* x y))]
    (println "x" x "\ty" y))
x 0 	y 0
x 5 	y 25
x 6 	y 18
x 8 	y 16
x 12 	y 18
x 20 	y 25
Out[4]:
nil

dotimes: repeated iteration with side-effects

(dotimes [<symbol> <number>]
    expr*)
In [9]:
(dotimes [n 10]
    (println "Hello world" n))
Hello world 0
Hello world 1
Hello world 2
Hello world 3
Hello world 4
Hello world 5
Hello world 6
Hello world 7
Hello world 8
Hello world 9
Out[9]:
nil
In [ ]: