9

Let's say I have a LazySeq

(def s (take 10 (iterate + 0)))

Does (count s) realize the sequence?

al3x
  • 93
  • 4

3 Answers3

6

If you are asking about lazy sequences, Yes.

user> (def s (map #(do (println "doing work") %) (range 4)))
#'user/s
user> (count s)
doing work
doing work
doing work                       
doing work
4  

Some of the data structures can give you answers in constant time, though lazy sequences do not have a stored count, and counting always realizes them.

Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
4

For a LazySeq yes, you can see its count method here. It walks every element from head to tail.

Michiel Borkent
  • 34,228
  • 15
  • 86
  • 149
1

Depends on the definition of lazy sequence. It's possible to implement ones that know their length without realizing their elements. See this question for an example, but in 99% of the cases they're just LazySeqs so Michiel's answer should cover that.

In your example case it's easy to test, as:

(realized? s) 

returns true after calling (count s), so s isn't 'clever' enough to know it's length without realizing it's content.

Community
  • 1
  • 1
soulcheck
  • 36,297
  • 6
  • 91
  • 90