underscoreio/essential-scala

Code mistake (C.5.40)

Closed this issue · 2 comments

C.5.40 Solution to: Union of Maps

def union[A](map1: Map[A, Int], map2: Map[A, Int]): Map[A, Int] = {
   map1.foldLeft(map2){(map, elt) =>
      val (k, v) = elt
      val newV = map.getOrElse(k, v) //Mistake
      map + (k -> newV)
   }
}

This code returns Map(a -> 2, b -> 4) instead of desired Map(a -> 3, b -> 6)

val newV = v + map.getOrElse(k, 0) - that will fix the problem

This issue has been fixed in c38e368.

Yes -- @daniashers fixed this when she migrated everything to Tut. Thanks all!