1mwy7g
Last Updated: February 25, 2016
·
4.919K
· runexec
81609937c20aeab3598aea56f1f4f022

doseq vs for in Clojure

doseq is almost interchangable with for, so why have both doseq and for? The for loop will always return a value and doseq will never return a value.

user=> (for [x (range 10) :when (even? x)] x)
(0 2 4 6 8)
user=> (doseq [x (range 10) :when (even? x)] x)
nil
user=>

2 Responses
Add your response

2
Bf4e0e4e4f0b1f703b1372a8dd7b0735

For returns a lazy sequence, while doseq performs side-effects immediately. So, if you're doing side-effects in a for, they won't occur until you try to use the values from the for (printing at the REPL counts as using the values. Here's an illustration (done on TryClj):


Clojure> (do (for i (range 3)) nil)
nil

Clojure> (do (doseq i (range 3)) nil)
0
1
2
nil
</pre>
Since, with the for, we didn't attempt to use any of the values, it never bothered executing the body, so the prn doesn't get called.

over 1 year ago ·
3
Bf4e0e4e4f0b1f703b1372a8dd7b0735