Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
Hanfei Sun Avatar asked May 15 '15 15:05

Hanfei Sun


2 Answers

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)
like image 98
Kolmar Avatar answered Oct 01 '22 17:10

Kolmar


The stdlib doesn't have such a feature, however, there is a port of Data.Map available in scalaz that does have this function available.

like image 42
gpampara Avatar answered Oct 01 '22 18:10

gpampara