ClojureDocs

Nav

Namespaces

lazy-cat

clojure.core

Available since 1.0 (source)
  • (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))
7 Examples
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
;; Prefer lazy-cat to build a lazy seq out of 
;; non-lazy collections with different creation costs

(time (first (concat (sort > (range 10)) (sort > (range 1e7)))))
;; "Elapsed time: 17442.084309 msecs"
(time (first (lazy-cat (sort > (range 10)) (sort > (range 1e7)))))
;; "Elapsed time: 0.458283 msecs"
;; Be aware that lazy-cat can be slower on smaller collections

(time (first (concat (sort > (range 100)) (sort > (range 100)))))
;; "Elapsed time: 0.058254 msecs"
(time (first (lazy-cat (sort > (range 100)) (sort > (range 100)))))
;; "Elapsed time: 0.182578 msecs"

(time (first (concat (sort > (range 10)) (sort > (range 100)))))
;; "Elapsed time: 0.051935 msecs"
(time (first (lazy-cat (sort > (range 10)) (sort > (range 100)))))
;; "Elapsed time: 0.149794 msecs"
See Also

Takes a body of expressions that returns an ISeq or nil, and yields a Seqable object that will inv...

Added by haplo

Returns a lazy seq representing the concatenation of the elements in the supplied colls.

Added by haplo

conj[oin]. Returns a new collection with the xs 'added'. (conj nil item) returns (item). (co...

Added by cloojure

Returns the result of applying concat to the result of applying map to f and colls. Thus function...

Added by MicahElliott
1 Note
    By , created 10.3 years ago

    It looks like lazy-cat is on deprecation path in favor of lazy-seq.