Monday, September 16, 2019

Unify two maps in Scala using a function arg


def unify[K, V](a: Map[K, V], b: Map[K, V])(f: (V, V) => V): Map[K, V] =
    b.foldLeft(a) { case (acc, (k, v)) =>
      acc + (k -> acc.get(k).map(f(_, v)).getOrElse(v))
    }

val m = Map[String, Int](("a", 1),("b", 2),("c", 3),("d", 4),("e", 5),("f", 6))

val n = Map[String, Int](("a", 11),("b", 12),("c", 13),("d", 14),("e", 15),("f", 16))


def f(i: Int, j: Int): Int = Math.max(i,j)

unify(m,n)(f)

No comments:

Post a Comment