Home > Software design >  How to multiply the values of a map by the values of another map functionally in scala
How to multiply the values of a map by the values of another map functionally in scala

Time:12-14

I have two maps quantity,price of type Map[String, Int].

Price has many items and their prices and quantity have the items that I have and their quantity. I'm trying to have a function that will return the total value of the Items that I have, I did it like this but I feel there's an improvement that can be done so it can be more functional.

def value (quantity: Map[String,Int], price: Map[String,Int]): Int = {
    var value = 0
    quantity.foreach { case (item,qunatity) =>
      value = price(item) * qunatity
    }
    value
  }

CodePudding user response:

What if you do mapping and .sum rather than mutating?

quantity.map { case item -> quantity =>
  price(item) * quantity
}.sum

Please notice that this throws if a key from quantity is absent in price.

You can consider

(quantity.keySet intersect price.keySet)
  .map(item => quantity(item) * price(item))
  .sum

Although maybe throwing is a desirable semantics, otherwise items with unknown price are for free.

CodePudding user response:

Alternatively, foldLeft may be a bit more concise than map sum in this case.

   quantity.foldLeft(0) { case (p, (i, q)) => p   price.getOrElse(i, 0)*q }
  • Related