murtaza52
murtaza52

Reputation: 47441

practical use of lazy sequences

Usually the sequence operations I perform, I always realzie them using a doall. Thus I am wondering what is the practical use of having lazy sequences ?

All examples I have seen online where lazy sequences are used are for seq building - (take 5 (range)) - this code could have been rewritten as - (range 5) too - my point being is that all seq generation can be done even without lazy seq, so what is their practical need ?

I have only seen examples of lazy seq for generating numeric seqs, is there any other application ?

Upvotes: 2

Views: 188

Answers (2)

Juraj Martinka
Juraj Martinka

Reputation: 4358

One of the lazy seq examples (although I'm not sure if it's a great one) can be found in the tentacles library.

Eric Normand also shows an example of reading pages of data from a database while leveraging lazy sequences so the client only fetches pages which they really need.

As a side note: the Programming Clojure book (3rd ed., p. 85) mentions the following guidelines for using lazy sequences:

  • Be lazy when producing large or variable-sized sequences.
  • Don't realize more of a lazy seq than you need
  • Use recursion [i.e. eager evaluation] when producing scalar values or small, fixed sequences.

Upvotes: 2

Jochen Bedersdorfer
Jochen Bedersdorfer

Reputation: 4122

They produce their results on-demand and can stop producing whenever necessary. That enables things like infinite seqs, parallelization of processing, combining operations and avoiding temporary storage (which can be further optimized by using transducers)

Lastly laziness makes it easy to turn recursive algorithms into sequences (using lazy-seq)

Upvotes: 3

Related Questions