问题
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
回答1:
_.flatMap(f).flatMap(g).map(h)
because:
_- receive anOption[A]flatMap(f)- peek inside, returnOption[B](flatMap()won't re-wrap it)flatMap(g)- peek inside, returnOption[C](flatMap()won't re-wrap it)map(h)- peek inside, return D (map()will re-wrap it)
来源:https://stackoverflow.com/questions/60901041/composing-functions-via-map-and-flatmap