Skip to content

clojure.core/lazy-seq

View this page on ClojureDocs

Type: macro Added: Clojure 1.0 Examples: 9 Runnable: 6
([& body])

Takes a body of expressions that returns an ISeq or nil, and yields a Seqable object that will invoke the body only the first time seq is called, and will cache the result and return it on all subsequent seq calls. See also - realized?

Examples

by gstamp on . May have evaluation errors.
by jakubholynet on
by jakubholynet on
by esumitra on . May have evaluation errors.
by Dimagog on
by esumitra on . May have evaluation errors.
by cloojure on
by ibercode on
by bdevel on

Note by hgijeon

I think every form of (cons a (lazy-seq (f b))) in examples should be changed to (lazy-seq (cons a (f b))) to be fully lazy.

Think about
(def one-over ((fn helper [n] (cons (/ 1 n) (lazy-seq (helper (inc n))))) 0))
and
(def one-over ((fn helper [n] (lazy-seq (cons (/ 1 n) (helper (inc n))))) 0))

First one throws an exception right after hitting enter key, while second code postpones the calculation(and that's the point of lazyness!).
Therefore, cons should be inside of lazy-seq.

See also


Content from the matching ClojureDocs page, with authors credited on each contribution.