-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))

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
  • What have you read about lazy sequences that you don't understand? – jmargolisvt Jan 31 '16 at 22:18
  • 3
    Possible duplicate of [How Are Lazy Sequences Implemented in Clojure?](http://stackoverflow.com/questions/3247045/how-are-lazy-sequences-implemented-in-clojure) – jmargolisvt Jan 31 '16 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. – Thumbnail Jan 31 '16 at 22:46

1 Answers1

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.

Seth Paulson
  • 800
  • 6
  • 15
  • 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 ? – CrazySynthax Feb 01 '16 at 22:16
  • 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. – Seth Paulson Feb 01 '16 at 23:57