I often write the same code to partition a sequence of tuples:
def groupBy[A, B](s: Seq[(A, B)]) : Map[A, Seq[B]] = s.groupBy (_._1) map { case (k, values) => (k, values.map(_._2))}
Is there a better way ?
Scalaz foldMap
is clearer, although possibly less efficient:
import scalaz._, Scalaz._
def groupBy[A, B](l: List[(A,B)]) = l foldMap {t => Map(t._1 → List(t._2))}
Since Scalaz only offers typeclass instances for concrete types like List
or Vector
you can only use those, not Seq
. If you want a generic version you can use the typeclass explicitly:
def groupBy[S[_]: Foldable, A, B](s: S[(A, B)]) =
s foldMap {t => Map(t._1 → List(t._2))}
This will work for List
, Vector
, or generally any S[_]: Foldable
- but still not Seq
where you don't know the concrete type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.