Я переписывал этот же метод дважды сейчас, на последующих работах.:) Кто-то действительно Oughta сделать это более общим.Также удобно иметь полную версию.
/**
* Like {@link scala.collection.Traversable#groupBy} but lets you return both the key and the value for the resulting
* Map-of-Lists, rather than just the key.
*
* @param in the input list
* @param f the function that maps elements in the input list to a tuple for the output map.
* @tparam A the type of elements in the source list
* @tparam B the type of the first element of the tuple returned by the function; will be used as keys for the result
* @tparam C the type of the second element of the tuple returned by the function; will be used as values for the result
* @return a Map-of-Lists
*/
def groupBy2[A,B,C](in: List[A])(f: PartialFunction[A,(B,C)]): Map[B,List[C]] = {
def _groupBy2[A, B, C](in: List[A],
got: Map[B, List[C]],
f: PartialFunction[A, (B, C)]): Map[B, List[C]] =
in match {
case Nil =>
got.map {case (k, vs) => (k, vs.reverse)}
case x :: xs if f.isDefinedAt(x) =>
val (b, c) = f(x)
val appendTo = got.getOrElse(b, Nil)
_groupBy2(xs, got.updated(b, c :: appendTo), f)
case x :: xs =>
_groupBy2(xs, got, f)
}
_groupBy2(in, Map.empty, f)
}
И вы используете это так:
val xs = (1 to 10).toList
groupBy2(xs) {
case i => (i%2 == 0, i.toDouble)
}
res3: Map[Boolean,List[Double]] = Map(false -> List(1.0, 3.0, 5.0, 7.0, 9.0),
true -> List(2.0, 4.0, 6.0, 8.0, 10.0))