From 48cc8408cfd0b57f46746162b8d4c184f7a3ed5c Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Wed, 26 Aug 2009 04:53:25 +0000 Subject: Tail recursive foldLeft for Stream. --- src/library/scala/collection/immutable/Stream.scala | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/library/scala/collection/immutable/Stream.scala b/src/library/scala/collection/immutable/Stream.scala index 2841beea14..e6f3d3c47c 100644 --- a/src/library/scala/collection/immutable/Stream.scala +++ b/src/library/scala/collection/immutable/Stream.scala @@ -13,6 +13,7 @@ package scala.collection.immutable import scala.collection.mutable.ListBuffer import scala.collection.generic._ +import scala.annotation.tailrec /** *

The class Stream implements lazy lists where elements @@ -180,6 +181,7 @@ self => * for allowing the GC to collect the underlying stream as elements are * consumed. */ + @tailrec override final def foreach[B](f: A => B) { if (!this.isEmpty) { f(head) @@ -187,6 +189,15 @@ self => } } + /** Stream specialization of foldLeft which allows GC to collect + * along the way. + */ + @tailrec + override final def foldLeft[B](z: B)(op: (B, A) => B): B = { + if (this.isEmpty) z + else tail.foldLeft(op(z, head))(op) + } + /** Returns all the elements of this stream that satisfy the * predicate p. The order of the elements is preserved. * -- cgit v1.2.3