summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Phillips <paulp@improving.org>2010-04-28 20:30:48 +0000
committerPaul Phillips <paulp@improving.org>2010-04-28 20:30:48 +0000
commit45e3ff972c7562bca5634aa7fe80d9e4c8f5a89d (patch)
tree1e4ec722ad8c88555c47d75a5552d70dc9de027e
parentb86d72b35eb729be8226b241134bfc76e68b3ae9 (diff)
downloadscala-45e3ff972c7562bca5634aa7fe80d9e4c8f5a89d.tar.gz
scala-45e3ff972c7562bca5634aa7fe80d9e4c8f5a89d.tar.bz2
scala-45e3ff972c7562bca5634aa7fe80d9e4c8f5a89d.zip
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.
-rw-r--r--src/library/scala/collection/Iterator.scala8
-rw-r--r--test/files/run/iterator-iterate-lazy.scala5
2 files changed, 12 insertions, 1 deletions
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
+ }
+}