WarChild
WarChild

Reputation: 3

Composing functions via map and flatmap

I learn scala in university and I cannot understand how to use map, flatmap and Option. Here's couple functions from my lab. I know how to implement first but I have no idea how to deal with second? So, the question: how to implement second function without changing it's signature (using map and flatmap)?

def testCompose[A, B, C, D](f: A => B)
                           (g: B => C)
                           (h: C => D): A => D = h compose g compose f

def testMapFlatMap[A, B, C, D](f: A => Option[B])
                              (g: B => Option[C])
                              (h: C => D): Option[A] => Option[D] = // help

Upvotes: 0

Views: 301

Answers (1)

jwvh
jwvh

Reputation: 51271

_.flatMap(f).flatMap(g).map(h)

because:

  • _ - receive an Option[A]
  • flatMap(f) - peek inside, return Option[B] (flatMap() won't re-wrap it)
  • flatMap(g) - peek inside, return Option[C] (flatMap() won't re-wrap it)
  • map(h) - peek inside, return D (map() will re-wrap it)

Upvotes: 3

Related Questions