lazy-cat

added
1.0

ns
clojure.core

type
macro

(lazy-cat & colls)

Expands to code which yields a lazy sequence of the concatenation
of the supplied colls.  Each coll expr is not evaluated until it is
needed. 

(lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))

                user=> (lazy-cat [1 2 3] [4 5 6])
(1 2 3 4 5 6)

            
                ;; N.B. this example holds onto the head of a lazy seq which should generally be avoided
(def fib-seq
     (lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))

(take 10 fib-seq)
            
                ;; When the producer function produces a collection, not an element,
;; lazy-cat is usable.
user=> (defn n-repeat [n] (lazy-cat (repeat n n) (n-repeat (inc n))))
#'user/n-repeat

user=> (take 6 (n-repeat 1))
(1 2 2 3 3 3)

user=> (take 12 (n-repeat 1))
(1 2 2 3 3 3 4 4 4 4 5 5)

            
                (lazy-cat (seq ["lazy-cat" "is" "my" "favorite" "function"]))
            
                user=> (defn loop-endlessly
         "Block thread with endless loop when evaluated"
         []
         (while true))
#'user/loop-endlessly

user=> (take 3 (lazy-cat ["will" "it" "return?"] (loop-endlessly)))
("will" "it" "return?")

user=> (take 4 (lazy-cat ["will" "it" "return?"] (loop-endlessly)))
;; This gets stuck on loop-endlessly and never returns