I have the following (extremely large) lazy-seq:
(def lazy-list (partition-all 100000 (take 10000000000000000000 (repeat 1))))
I want to count the number of elements in it, for which I am doing the following:
(time
(loop [ll lazy-list
c 0]
(if-not (seq (take 1 ll))
c
(recur (drop 1 ll)
(inc c)))))
If I run this I get the following error:
Execution error (OutOfMemoryError) at user/eval2043$fn (REPL:1).
Java heap space
But if I am not holding the head anywhere, why am I seeing this OOM issue?
I tried a slightly different version and it worked:
with result
Going back to your example, I tried:
with result
But note that
take-itemis holding on to the head of the 10 million long list of ones. I suspect that is your problem.The moral of the story is that lazy sequences are sometimes useful, but are tricky and easy to get wrong. Then are not a miracle, can often cause unexpected bugs, and I prefer to always use concrete vectors whenever possible.
I'd recommend to only use a lazy sequence if there is no other choice possible.