如何使用Scala中的函数映射2个映射?

时间:2012-03-15 04:43:48

标签: scala mapping

c地图等于a地图的函数时,我可以将其计算为

val a: Map[T, U] = ...
def f(aValue: U): V = ...
val c: Map[T, V] = a.map(f)

但是如果c map等于ab的函数作为参数怎么办?例如,如果abcMap[String, Int]c值等于相应的a值,则相应的b值?

2 个答案:

答案 0 :(得分:2)

这样的东西?

val a: Map[String, Int] = Map("a" -> 10, "b" -> 20)
val b: Map[String, Int] = Map("a" -> 2,  "b" -> 3)
def f(a: Int, b: Int): Int = math.pow(a,b).toInt // math.pow returns a Double

val c = for {
  (ak, av) <- a        // for all key-value pairs from a
  bv <- b.get(ak)      // for any matching value from b
} yield (ak, f(av,bv)) // yield a new key-value pair that results from applying f

// c: scala.collection.immutable.Map[String,Int] = Map(a -> 100, b -> 8000)    

答案 1 :(得分:1)

这就是你要追求的吗?

val a = Map('a -> 2, 'b -> 3)
val b = Map('a -> 4, 'b -> 5)
a.map{ case (k, aVal) => (k, aVal + b(k)) } // Map('a -> 6, 'b -> 8)