in Clojure, you can iterate over a sequence using the for function or similarly with doseq for side effects and get zero as the return value:
(doseq [x (range 3)] (prn x)) ; 0 ; 1 ; 2
for the case when the sequence is infinite, there is a way to introduce a break condition:
(doseq [x (range) :while (< x 3)] (prn x))
This will lead to the same conclusion as above.
As a specialty, there is a very interesting behavior when you use more than one sequence. As the documentation calls it: "Collections repeat in nested order, most quickly faster."
(doseq [x (range 3) y (range 3)] (prn xy)) ; 0 0 ; 0 1 ; 0 2 ; 1 0 ; 1 1 ; 1 2 ; 2 0 ; 2 1 ; 2 2
What happens if the sequences are endless again. When the latter is infinite, it works very well. this will work equally as an example until:
(doseq [x (range 3) y (range) :while (< y 3)] (prn xy))
If the first one is infinite, the resulting output will be as expected, but for some reason the loop does not stop after printing the last line. In other words: repl continues to work.
(doseq [x (range) y (range 3) :while (< x 3)] (prn xy))
Can anyone explain this behavior?
source share