Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the point of lazy-seq in clojure?

I am looking through some example Fibonacci sequence clojure code:

 (def fibs (lazy-cat [1 2] (map + fibs (rest fibs))))

I generally understand what is going on, but don't get the point of lazy-cat. I know that lazy-cat is a macro that is translating to something like this:

(def fibs (concat (lazy-seq [1 2]) (lazy-seq (map + fibs (rest fibs))))) 

What exactly is lazy-seq accomplishing? It would still be evaluated lazily even without lazy-seq? Is this strictly for caching purposes?

EDIT: Thanks for the answers. My confusion was that it worked with a plain concat from the REPL because I had a previous binding to fibs in scope.

like image 764
dbyrne Avatar asked May 31 '10 15:05

dbyrne


People also ask

What is a lazy sequence?

Lazy sequences are regular sequences where each item is computed on demand rather than up front. For example, consider this array of numbers: let numbers = Array(1... 100000) That will hold 100,000 numbers.

Does seq do in Clojure?

The 'doseq' statement is similar to the 'for each' statement which is found in many other programming languages. The doseq statement is basically used to iterate over a sequence.


2 Answers

The lazy-seq on [1 2] is not needed, but doesn't really hurt.

The lazy-seq on (map + fibs (rest fibs)) is essential; without it, the function call will be evaluated before fibs is bound to a value, which will cause an exception. By wrapping it in lazy-seq, the call will be deferred until the value is needed, and fibs will have a value at that point.

like image 142
Brian Avatar answered Sep 28 '22 23:09

Brian


As I understand it (and I admit to still being a relative newcomer to Clojure!), if you try the following:

(def fibs (concat [1 2] (map + fibs (rest fibs))))

Then it won't work because fibs isn't yet bound and therefore the two later references to it fail.

The lazy version you give will however work, because the references to fibs are only actually resolved at a later time when the sequence is consumed - and by which point fibs has already been successfully defined as the lazy sequence.

like image 31
mikera Avatar answered Sep 28 '22 22:09

mikera