Last active
January 1, 2016 09:59
-
-
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.
This file contains hidden or 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
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