简体   繁体   English

在scala中划分一个元组序列

[英]Partition a sequence of tuple in scala

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: Scalaz foldMap更清晰,尽管可能效率较低:

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 . 由于Scalaz仅提供诸如ListVector类的具体类型的类型类实例,因此您只能使用这些实例,而不能使用Seq If you want a generic version you can use the typeclass explicitly: 如果需要通用版本,可以显式使用typeclass:

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. 这将适用于ListVector或通常的任何S[_]: Foldable -但在您不知道具体类型的情况下仍不能使用Seq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM