From d7f5a8824a94d01cb76f459454932d71b9e6f5cf Mon Sep 17 00:00:00 2001 From: Iulian Dragos Date: Tue, 25 Aug 2009 10:00:50 +0000 Subject: Added 'foreach' method in Stream that is tail-c... Added 'foreach' method in Stream that is tail-call optimized, and which does not hold references to stream elements (fix for #692). --- src/library/scala/collection/immutable/Stream.scala | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/library/scala/collection/immutable/Stream.scala b/src/library/scala/collection/immutable/Stream.scala index badeb31bbc..2841beea14 100644 --- a/src/library/scala/collection/immutable/Stream.scala +++ b/src/library/scala/collection/immutable/Stream.scala @@ -171,6 +171,22 @@ self => else new Stream.Cons(rest.head, rest.tail filter p) } + /** Apply the given function f to each element of this linear sequence + * (while respecting the order of the elements). + * + * @param f the treatment to apply to each element. + * @note Overridden here as final to trigger tail-call optimization, which replaces + * 'this' with 'tail' at each iteration. This is absolutely necessary + * for allowing the GC to collect the underlying stream as elements are + * consumed. + */ + override final def foreach[B](f: A => B) { + if (!this.isEmpty) { + f(head) + tail.foreach(f) + } + } + /** Returns all the elements of this stream that satisfy the * predicate p. The order of the elements is preserved. * -- cgit v1.2.3