Where developers come to connect, share, build and be inspired.


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=>


  • Bf4e0e4e4f0b1f703b1372a8dd7b0735
  • 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)

    Clojure> (do (doseq i (range 3)) nil) 0 1 2 nil

    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.

Add a comment