4.3

Write a generic function map2 that combines two Option values using a binary function. If either Option value is None, then the return value is too. Here is its signature:

def map2[A,B,C](a: Option[A], b: Option[B])(f: (A, B) => C): Option[C]

Solution

object Main extends App {
  override def main(args: Array[String]): Unit = {
    println("map2(Some(10), Some(20))(f:(a:Int, b:Int) => a * b): " + map2(Some(10), Some(20))((a:Int, b:Int) => a*b))
  }

  def map2[A,B,C](a: Option[A], b: Option[B])(f: (A, B) => C): Option[C] =
    a flatMap(a1 => b map(b1 => f(a1, b1)))

}

Output

map2(Some(10), Some(20))(f:(a:Int, b:Int) => a * b): Some(200)