From 45e3ff972c7562bca5634aa7fe80d9e4c8f5a89d Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Wed, 28 Apr 2010 20:30:48 +0000 Subject: Fixed bug in Iterator.iterate which would lead ... Fixed bug in Iterator.iterate which would lead to a runtime exception under some circumstances due to inadequate laziness in calculating the next element. No review. --- src/library/scala/collection/Iterator.scala | 8 +++++++- test/files/run/iterator-iterate-lazy.scala | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 test/files/run/iterator-iterate-lazy.scala diff --git a/src/library/scala/collection/Iterator.scala b/src/library/scala/collection/Iterator.scala index cbbaf0058c..5eca806933 100644 --- a/src/library/scala/collection/Iterator.scala +++ b/src/library/scala/collection/Iterator.scala @@ -109,9 +109,15 @@ object Iterator { * @return the iterator producing the infinite sequence of values `start, f(start), f(f(start)), ...` */ def iterate[T](start: T)(f: T => T): Iterator[T] = new Iterator[T] { + private[this] var first = true private[this] var acc = start def hasNext: Boolean = true - def next(): T = { val res = acc ; acc = f(acc) ; res } + def next(): T = { + if (first) first = false + else acc = f(acc) + + acc + } } /** Creates an infinite-length iterator which returns successive values from some start value. diff --git a/test/files/run/iterator-iterate-lazy.scala b/test/files/run/iterator-iterate-lazy.scala new file mode 100644 index 0000000000..73886f192b --- /dev/null +++ b/test/files/run/iterator-iterate-lazy.scala @@ -0,0 +1,5 @@ +object Test { + def main(args: Array[String]): Unit = { + Iterator.iterate(1 to 5 toList)(_.tail).takeWhile(_.nonEmpty).map(_.head).toList + } +} -- cgit v1.2.3