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

19

doseq vs for in Clojure

2884 views

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

Comments

  • Blank-mugshot
    sgeo
  • Blank-mugshot
    sgeo

    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

    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