diff options
-rw-r--r-- | src/library/scala/Iterable.scala | 16 | ||||
-rw-r--r-- | test/files/run/iterables.check | 3 | ||||
-rw-r--r-- | test/files/run/iterables.scala | 18 |
3 files changed, 34 insertions, 3 deletions
diff --git a/src/library/scala/Iterable.scala b/src/library/scala/Iterable.scala index 0acd9b824d..e00d41c7c8 100644 --- a/src/library/scala/Iterable.scala +++ b/src/library/scala/Iterable.scala @@ -187,6 +187,22 @@ trait Iterable[+A] { buf } + /** Partitions this iterable in two iterables according to a predicate. + * + * @param p the predicate on which to partition + * @return a pair of iterables: the iterable that satisfy the predicate + * <code>p</code> and the iterable that do not. + * The relative order of the elements in the resulting iterables + * is the same as in the original iterable. + */ + def partition[T](p: A => Boolean): (Iterable[A], Iterable[A]) = { + val matched = new ArrayBuffer[A] + val failed = new ArrayBuffer[A] + val elems = elements + while (elems.hasNext) { val x = elems.next; if (p(x)) matched += x else failed += x } + (matched, failed) + } + /** Returns the longest prefix of this iterable whose elements satisfy * the predicate <code>p</code>. * diff --git a/test/files/run/iterables.check b/test/files/run/iterables.check index 2660f51aa5..aac90b70a9 100644 --- a/test/files/run/iterables.check +++ b/test/files/run/iterables.check @@ -1,2 +1,5 @@ false 0,1,2,3,4,5,6,7,8,9 +5,6,7,8,9 +0,2,4,6,8 +1,3,5,7,9 diff --git a/test/files/run/iterables.scala b/test/files/run/iterables.scala index 7a29b80e8d..5fb587a323 100644 --- a/test/files/run/iterables.scala +++ b/test/files/run/iterables.scala @@ -8,7 +8,19 @@ object Test extends Application { else throw new IndexOutOfBoundsException("empty iterator") } } - val x = new Test(10) - println(x.isEmpty) - println(x.mkString(",")) + { + val x = new Test(10) + println(x.isEmpty) + println(x.mkString(",")) + } + { + val x = new Test(10) + println(x.filter(_ > 4).mkString(",")) + } + { + val x = new Test(10) + val y = x.partition(_ % 2 == 0) + println(y._1.mkString(",")) + println(y._2.mkString(",")) + } } |