简体   繁体   中英

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:

fromListWith :: Ord k => (a -> a -> a) -> [(k, a)] -> Map k a

The following expression will be evaluated to 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.

Does anyone have ideas about this?

Apart from using scalaz you could also define one yourself:

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确实有提供此功能。

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.

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