Hi Troy,
You can do something like this:
def merge[K, V](maps: Seq[Map[K, V]])(f: (K, V, V) => V): Map[K, V] = {
maps.foldLeft(Map.empty[K, V]) { case (merged, m) =>
m.foldLeft(merged) { case (acc, (k, v)) =>
acc.get(k) match {
case Some(existing) => acc.updated(k, f(k, existing, v))
case None => acc.updated(k, v)
}
}
}
}
Then you can use the above merge method with your example like this:
scala> val maps = Seq(Map(1 -> 0.5, 2 -> 0.0), Map(1 -> 0.0, 2 -> 1.0))
maps: Seq[scala.collection.immutable.Map[Int,Double]] = List(Map(1 -> 0.5, 2 -> 0.0), Map(1 -> 0.0, 2 -> 1.0))
scala> merge(maps) { (_, v1, v2) => v1 + v2 }
res2: Map[Int,Double] = Map(1 -> 0.5, 2 -> 1.0)
--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+unsubscribe@googlegroups.com.
Hi Troy,
You can do something like this:
def merge[K, V](maps: Seq[Map[K, V]])(f: (K, V, V) => V): Map[K, V] = { maps.foldLeft(Map.empty[K, V]) { case (merged, m) => m.foldLeft(merged) { case (acc, (k, v)) => acc.get(k) match { case Some(existing) => acc.updated(k, f(k, existing, v)) case None => acc.updated(k, v) } } } }Then you can use the above
mergemethod with your example like this:scala> val maps = Seq(Map(1 -> 0.5, 2 -> 0.0), Map(1 -> 0.0, 2 -> 1.0)) maps: Seq[scala.collection.immutable.Map[Int,Double]] = List(Map(1 -> 0.5, 2 -> 0.0), Map(1 -> 0.0, 2 -> 1.0)) scala> merge(maps) { (_, v1, v2) => v1 + v2 } res2: Map[Int,Double] = Map(1 -> 0.5, 2 -> 1.0)
With val ms = Seq(map1, map2) you could use merge(ms.map(_.mapValues(List(_)))){(_, v1, v2) => v1 ++ v2} or if you are interested in just the sizes: merge(ms.map(_.mapValues(_ => 1))){(_, v1, v2) => v1 + v2} which in turn is the same as: (m1.toSeq ++ m2).groupBy(_._1).mapValues(_.size)