[英]In Scala, is there an equivalent of Haskell's “fromListWith” for Map?
In Haskell, there is a function called fromListWith which can generate a Map from a function (used to merge values with the same key) and a list: 在Haskell中,有一个名为fromListWith的函数,它可以从函数生成Map(用于合并具有相同键的值)和列表:
fromListWith :: Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
The following expression will be evaluated to true
: 以下表达式将被评估为true
:
fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
In Scala, there is a similar function called toMap
on List
objects , which can also convert a list to a Map, but it can't have a parameter of function to deal with duplicated keys. 在Scala中,在List
对象上有一个名为toMap
的类似函数,它也可以将列表转换为Map,但是它不能具有处理重复键的函数参数。
Does anyone have ideas about this? 有没有人有这个想法?
Apart from using scalaz
you could also define one yourself: 除了使用scalaz
之外,您还可以自己定义一个:
implicit class ListToMapWith[K, V](list: List[(K, V)]) {
def toMapWith(op: (V, V) => V) =
list groupBy (_._1) mapValues (_ map (_._2) reduce op)
}
Here is a usage example: 这是一个用法示例:
scala> val testList = List((5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a"))
scala> testList toMapWith (_ + _)
res1: scala.collection.immutable.Map[Int,String] = Map(5 -> aba, 3 -> ba)
该STDLIB不具备这样的功能,但是,没有一个端口Data.Map
可用scalaz
这确实有提供此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.