Created
July 10, 2012 00:29
-
-
Save luigip/3080119 to your computer and use it in GitHub Desktop.
multiPartion for non-Array collections
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
def multiPartition[T, C[X] <: Traversable[X]](xs: C[T])(fs: T => Boolean *)(implicit cbf: CanBuildFrom[C[_],T,C[_]]) = { | |
val builders = Vector.fill(fs.length)(cbf()) | |
for (e <- xs) { | |
val i = fs.indexWhere(f => f(e)) | |
if (i >= 0) builders(i) += e | |
} | |
builders.map(_.result) | |
} | |
// ----------TEST--------------- | |
case class Person(val name: String, val age: Int) | |
val people = Seq(Person("Doris", 100), Person("Barry", 60), Person("Mary", 45), Person("Justin", 16)) | |
val Seq(minors, adults, seniors) = multiPartition(people)(_.age < 18, p => 18 < p.age && p.age < 65, _.age > 65) | |
println(minors mkString " ") | |
println(adults mkString " ") | |
println(seniors mkString " ") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment