M. Tong
M. Tong

Reputation: 579

Why applying seq on a LazySeq returns ChunkedCons?

(class (range 10))
;=> clojure.lang.LazySeq

(class (seq (range 10))
;=> clojure.lang.ChunkedCons

From my understanding, LazySeq is already an sequence, since:

(seq? (range 10))
;=> true

Upvotes: 5

Views: 478

Answers (2)

noahlz
noahlz

Reputation: 10311

To expand upon your answer (and because comments don't support new lines):

user=> (def r (range 10))
#'user/r
user=> (realized? r)
false
user=> (class r)
clojure.lang.LazySeq
user=> (def r2 (rest r))
#'user/r2
user=> (realized? r2)
ClassCastException clojure.lang.ChunkedCons cannot be cast to clojure.lang.IPending  clojure.core/realized? (core.clj:6607)
user=> (class r2)
clojure.lang.ChunkedCons
user=> (realized? r)
true

Upvotes: 1

M. Tong
M. Tong

Reputation: 579

I guess I have an answer.

That's because using seq enforces the evaluation of the first element of LazySeq. Because seq returns nil when the collection & sequence is empty, it has to eval the element to decide that.

That's the exactly reason why rest is lazier than next, because (next s) is just (seq (rest s)).

Upvotes: 2

Related Questions