2

The following code sums the values of the two maps into a single map.

val merged = (map1 /: map2) { case (map, (k,v)) =>
    map + ( k -> (v + map.getOrElse(k, 0)) )
}

However I am unsuccessful in converting it using the foldLeft()() function. Here's what I tried , but not able to meaningfully progress.

val merged2 =  map2 foldLeft (map1) ((acc:Map[Int,Int], (k:Int,v:Int)) =>   acc + ( k -> (v + acc.getOrElse(k, 0)) ))

Whats the correct way to rewrite using the foldLeft function?

SCouto
  • 7,808
  • 5
  • 32
  • 49
Dev A
  • 171
  • 2
  • 8

1 Answers1

2

You almost had it:

val merged2 = map2.foldLeft(map1) { case (acc, (k,v)) =>  acc + (k -> (v + acc.getOrElse(k, 0))) }
sachav
  • 1,316
  • 8
  • 11
  • Can you break down your answer as to what my version was missing? Why did you use "case" ? Also in general how should you approach a foldLeft use case where using pattern match , i.e. the case syntax becomes necessary ? – Dev A Apr 20 '19 at 17:12
  • How this is different from OP’s version? Other then {} brace – Raman Mishra Apr 20 '19 at 17:22
  • @RamanMishra op's version has a compilation error, sachav added a case too along with {}, but I am not sure why my version is wrong even tho I have provided the right function as per the foldLeft specs – Dev A Apr 20 '19 at 17:58
  • 4
    @DevA The problem is that `(a: Int, b: Int) => ???` is a function that takes two `Int` arguments, not a function that takes a tuple `(Int, Int)`. Using `{}` and `case` turns the argument into a partial function with a single argument, and the `case` statement then de-structures the tuple using pattern matching. – Tim Apr 20 '19 at 19:25