summaryrefslogtreecommitdiff
path: root/src/library
diff options
context:
space:
mode:
authorDonna Malayeri <lindydonna@gmail.com>2009-11-27 11:05:04 +0000
committerDonna Malayeri <lindydonna@gmail.com>2009-11-27 11:05:04 +0000
commit252ebb328144c843266264ad40b59634685cb4cf (patch)
tree60ba37348ba8b20e2a6a76d1af8b4e0967d31fc5 /src/library
parent5be23003fd06ec551c30c4692bce0e91eed00725 (diff)
downloadscala-252ebb328144c843266264ad40b59634685cb4cf.tar.gz
scala-252ebb328144c843266264ad40b59634685cb4cf.tar.bz2
scala-252ebb328144c843266264ad40b59634685cb4cf.zip
Closes #2540 and closes #2593.
Diffstat (limited to 'src/library')
-rw-r--r--src/library/scala/collection/Iterator.scala49
1 files changed, 45 insertions, 4 deletions
diff --git a/src/library/scala/collection/Iterator.scala b/src/library/scala/collection/Iterator.scala
index 8f49bbd0e4..b507426fb8 100644
--- a/src/library/scala/collection/Iterator.scala
+++ b/src/library/scala/collection/Iterator.scala
@@ -367,11 +367,52 @@ trait Iterator[+A] { self =>
def next() = if (hasNext) { hdDefined = false; hd } else empty.next()
}
+ def withFilter(p: A => Boolean): WithFilter = new WithFilter(p)
- /** !!! Temporary, awaiting more general implementation.
- * ... better wait longer, this fails once flatMap gets in the mix.
- */
- // def withFilter(p: A => Boolean) = this.toStream withFilter p
+ final class WithFilter private[Iterator] (p: A => Boolean) {
+
+ def map[B](f: A => B): Iterator[B] = new Iterator[B] {
+ private var hd: A = _
+ private var hdDefined: Boolean = false
+
+ def hasNext: Boolean = hdDefined || {
+ do {
+ if (!self.hasNext) return false
+ hd = self.next()
+ } while (!p(hd))
+ hdDefined = true
+ true
+ }
+
+ def next() = if (hasNext) { hdDefined = false; f(hd) } else empty.next()
+ }
+
+ def flatMap[B](f: A => Iterator[B]): Iterator[B] = new Iterator[B] {
+ private var cur: Iterator[B] = empty
+
+ @tailrec
+ def hasNext: Boolean = cur.hasNext || {
+ var x = null.asInstanceOf[A]
+ do {
+ if (!self.hasNext) return false
+ x = self.next()
+ } while (!p(x))
+ cur = f(x)
+ hasNext
+ }
+
+ def next(): B = (if (hasNext) cur else empty).next()
+ }
+
+ def foreach[U](f: A => U) {
+ while (self.hasNext) {
+ val x = self.next()
+ if (p(x)) f(x)
+ }
+ }
+
+ def withFilter(q: A => Boolean): WithFilter = new WithFilter(x => p(x) && q(x))
+ }
/** Returns an iterator over all the elements of this iterator which
* do not satisfy the predicate <code>p</code>.