Composing functions via map and flatmap

若如初见. 提交于 2021-01-29 22:02:12

问题


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 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)


来源:https://stackoverflow.com/questions/60901041/composing-functions-via-map-and-flatmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!