Created
July 22, 2011 23:23
-
-
Save mpilquist/1100665 to your computer and use it in GitHub Desktop.
Grouping an iterator by a predicate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class IteratorW[A](itr: Iterator[A]) { | |
def groupWhen(fn: A => Boolean): Iterator[Seq[A]] = new Iterator[Seq[A]] { | |
private val bitr = itr.buffered | |
override def hasNext = bitr.hasNext | |
override def next = { | |
val xs = collection.mutable.ListBuffer(bitr.next) | |
while (bitr.hasNext && !fn(bitr.head)) xs += bitr.next | |
xs.toSeq | |
} | |
} | |
} | |
implicit def ToIteratorW[A](itr: Iterator[A]): IteratorW[A] = new IteratorW(itr) | |
val everyTen = (1 to 100).iterator groupWhen { _ % 10 == 1 } | |
everyTen foreach println |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See http://stackoverflow.com/questions/6800737/how-to-group-a-variable-length-repeating-sequence-in-scala for other implementations.