concept dorun in category clojure

appears as: dorun
Clojure: The Essential Reference MEAP V30

This is an excerpt from Manning's book Clojure: The Essential Reference MEAP V30.

  • dorun are similar to doall but they return nil without holding the head of the sequence. Prefer dorun when the input is a sequence containing side-effecting items once realized.
  • doseq, dorun and run! for instance, are designed exclusively for side effects. They walk a lazy sequence throwing away the results and returning nil:

    (defn unchunked [n] ; #1
      (map #(do (print ".") %)
        (subvec (vec (range n)) 0 n)))
    
    (doseq [x (unchunked 10) :while (< x 5)] x) ; #2
    ;; ......nil
    
    (dorun 5 (unchunked 10)) ; #3
    ;; ......nil
    
    (run! #(do (print "!") %) (unchunked 10)) ; #4
    ;; .!.!.!.!.!.!.!.!.!.!nil

    As we can see from examples, doseq, dorun and run! always return nil, independently from the input, so if anything interesting happens while iterating, it must necessarily be a side effect. As a consequence, doseq, dorun and run! are all O(1) memory allocation as they don’t retain the head (or any other item) of the sequence.

    doall is similar in behavior to dorun but it returns the output forcing any side effects in the process. doall is often used to fully realize a lazy sequence before leaving a state that is necessary for the sequence to work properly. A typical example is with-open:

    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest