Skip to content

Instantly share code, notes, and snippets.

@luigip
Created July 10, 2012 00:29
Show Gist options
  • Save luigip/3080119 to your computer and use it in GitHub Desktop.
Save luigip/3080119 to your computer and use it in GitHub Desktop.
multiPartion for non-Array collections
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