In 2.8, there is a protected method called tailDefined that will return false when you go to a point in a stream that has not yet been evaluated.
This is not very useful (unless you want to write your own Stream class), except that Cons makes this method publicly available. I am not sure why it is protected in Stream and not in Cons - I think that one or the other may be a mistake. But at the moment, at least you can write such a method (writing the functional equivalent is left as an exercise for the reader):
def streamEvalLen[T](s: Stream[T]) = { if (s.isEmpty) 0 else { var i = 1 var t = s while (t match { case c: Stream.Cons[_] => c.tailDefined case _ => false }) { i += 1 t = t.tail } i } }
Here you can see it in action:
scala> val s = Stream.iterate(0)(_+1) s: scala.collection.immutable.Stream[Int] = Stream(0, ?) scala> streamEvalLen(s) res0: Int = 1 scala> s.take(3).toList res1: List[Int] = List(0, 1, 2) scala> s res2: scala.collection.immutable.Stream[Int] = Stream(0, 1, 2, ?) scala> streamEvalLen(s) res3: Int = 3
Rex kerr
source share