Search code examples
clojurelazy-evaluation

How to convert lazy sequence to non-lazy in Clojure


I tried the following in Clojure, expecting to have the class of a non-lazy sequence returned:

(.getClass (doall (take 3 (repeatedly rand))))

However, this still returns clojure.lang.LazySeq. My guess is that doall does evaluate the entire sequence, but returns the original sequence as it's still useful for memoization.

So what is the idiomatic means of creating a non-lazy sequence from a lazy one?


Solution

  • doall is all you need. Just because the seq has type LazySeq doesn't mean it has pending evaluation. Lazy seqs cache their results, so all you need to do is walk the lazy seq once (as doall does) in order to force it all, and thus render it non-lazy. seq does not force the entire collection to be evaluated.