Skip to content

Instantly share code, notes, and snippets.

@mpilquist
Created July 22, 2011 23:23
Show Gist options
  • Save mpilquist/1100665 to your computer and use it in GitHub Desktop.
Save mpilquist/1100665 to your computer and use it in GitHub Desktop.
Grouping an iterator by a predicate
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
@mpilquist
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment