Skip to content

Instantly share code, notes, and snippets.

@ScalaWilliam
Last active January 1, 2016 09:59
Show Gist options
  • Save ScalaWilliam/8128343 to your computer and use it in GitHub Desktop.
Save ScalaWilliam/8128343 to your computer and use it in GitHub Desktop.
Group consecutive siblings according to truth/falsity. Useful to interpret something like parsing output from the shell to distinguish between Input and Output.
def continuousPartitions[A](l: List[A])(f: A => Boolean): List[(List[A], List[A])] = {
if ( l.isEmpty ) Nil
else {
val (continuousTrue, followingPartition) = l span f
val (continuousFalse, nextGroup) = followingPartition span (!f(_))
(continuousTrue, continuousFalse) :: continuousPartitions(nextGroup)(f)
}
}
val hav = continuousPartitions(List("a", "b", "a", "a", "b", "b", "a"))(_=="a")
val exp = List(
(List("a"),List("b")),
(List("a","a"),List("b","b")),
(List("a"), Nil)
)
println(hav)
println(exp)
assert(hav == exp, "Check that the lists are identical.")
assert(Nil == continuousPartitions(List())(_ => true), "Empty input should return empty result.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment