Ivan
Ivan

Reputation: 64227

How to map 2 maps with a function in Scala?

When c map equals a function of a map I can calculate it as

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

but what if c map equals a function of both a and b as arguments? For example if a, b and c are Map[String, Int] and a c values are to equal corresponding a values raised to powers specified by corresponding b values?

Upvotes: 0

Views: 709

Answers (2)

Alex Cruise
Alex Cruise

Reputation: 7979

Something like this?

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)    

Upvotes: 2

dhg
dhg

Reputation: 52691

Is this what you're after?

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)

Upvotes: 1

Related Questions