Skip to content

Instantly share code, notes, and snippets.

@stephenjudkins
Created April 23, 2011 00:52
Show Gist options
  • Save stephenjudkins/938058 to your computer and use it in GitHub Desktop.
Save stephenjudkins/938058 to your computer and use it in GitHub Desktop.
import annotation.tailrec
object SplitList {
def split[A](all: List[A], f: (A, A) => Boolean): List[List[A]] = {
@tailrec def _split(list: List[A], acc: List[List[A]], current: List[A]): List[List[A]] = list match {
case Nil => current match {
case Nil => Nil
case _ => acc ::: current :: Nil
}
case l :: ls => current match {
case Nil => _split(ls, acc, List(l))
case c :: cs => if (f(l, c)) {
_split(ls, acc, current ::: l :: Nil)
} else {
_split(ls, acc ::: current :: Nil, List(l))
}
}
}
_split(all, Nil, Nil)
}
}
implicit def pimpListWithSplit[A](l: List[A]) = new { def split(f: (A, A) => Boolean) = SplitList.split[A](l, f) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment