-1

In Clojure, what is the difference between an "ordinary" sequence and a lazy-sequence ?

Please look at this link: https://clojuredocs.org/clojure.core/partition#partition-by

It says that function "partition" returns a lazy-sequence. How makes the following sequence "lazy" ?

((0 1 2 3) (4 5 6 7) (8 9 10 11) (12 13 14 15) (16 17 18 19))

3
  • What have you read about lazy sequences that you don't understand? Commented Jan 31, 2016 at 22:18
  • 3
    Possible duplicate of How Are Lazy Sequences Implemented in Clojure? Commented Jan 31, 2016 at 22:19
  • The REPL will usually realise small lazy sequences such as yours, and any use will realise at least as much as you look at. Consider (partition 4 (range)) - an endless lazy sequence of which you have the first five elements. In LightTable, you can scroll through as much of it as you wish. Commented Jan 31, 2016 at 22:46

1 Answer 1

0

user> (time (def lazy-partition (partition 3 (range 1000000)))) "Elapsed time: 0.165415 msecs"

user> (time (def eager-partition (doall (partition 3 (range 1000000))))) "Elapsed time: 2181.272597 msecs"

Normally sequences in clojure are lazy. That means they don't actually evaluate the sequence until the data is needed notice how the partitioning returns instantly. The second one uses doall to force the evaluation, notice how it takes over two seconds to run.

Sign up to request clarification or add additional context in comments.

2 Comments

OK. But what makes the first function so fast? What does it matten WHEN the data is evaluated. In both cases the same data is evaluated. No ?
No. The first one has not been evaluated. That is the reason I used a def instead of just typing in the code in the REPL because otherwise the REPL would automatically realize the seq in order to display it to you. If after typing the first command you then just typed lazy-partition into the REPL then the REPL would be forced to evaluate it to display it to you and would then take the full 2 seconds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.