Difference between Dose and Clojure

What is the difference between dose and Clojure? What are some examples of when you decided to use one over the other?

+92
clojure
Jan 18 2018-11-18T00:
source share
2 answers

The difference is that for creates a lazy sequence and returns it, and doseq - for performing side effects and returns zero.

 user=> (for [x [1 2 3]] (+ x 5)) (6 7 8) user=> (doseq [x [1 2 3]] (+ x 5)) nil user=> (doseq [x [1 2 3]] (println x)) 1 2 3 nil 

If you want to create a new sequence based on other sequences, use for. If you want to do side effects (printing, writing to a database, launching a nuclear warhead, etc.) Based on elements from some sequences, use the dose.

+147
Jan 18 2018-11-18T00:
source share

Note that doseq impatient and doseq is lazy. In an example missing from Rayne's answer,

 (for [x [1 2 3]] (println x)) 

In REPL, this will usually do what you want, but this is basically a coincidence: REPL forces the lazy sequence created by for , causing printlns to appear. In a non-interactive environment, nothing will ever be printed. You can see it in action by comparing the results.

 user> (def lazy (for [x [1 2 3]] (println 'lazy x))) #'user/lazy user> (def eager (doseq [x [1 2 3]] (println 'eager x))) eager 1 eager 2 eager 3 #'user/eager 

Since the def form returns the newly created var, and not the value that is bound to it, nothing exists to print the REPL, and lazy will refer to the unrealized lazy-seq: none of its elements were calculated at all. eager will refer to nil , and all its printing will be executed.

+53
Mar 13 '11 at 4:30
source share



All Articles