How to simplify nested map calls?

前端 未结 3 2070
独厮守ぢ
独厮守ぢ 2021-01-11 17:33

Suppose I have a few nested functors, e.g. List[Option[Int]] and need to call the map of the most inner one.

Now I am using nested m

3条回答
  •  情书的邮戳
    2021-01-11 18:01

    If you have a lot of nested functors and you don't want to flatten them (i.e. they're not monads or you don't want to use them as monads) - then lenses may help. There is quicklens implementation, which supports traversable lenses : http://www.warski.org/blog/2015/03/quicklens-traversing-options-and-lists/.

    Example (sorry didn't try to compile it):

    modify(opts)(_.each.each).using(_ + 1)
    

    Anyway, you have to specify nesting level, but you don't have to nest functions here. And it's enough to specify it once, like (conceptual example, didn't check):

    def md2[T]: (l: List[Option[T]]) => modify(l)(_.each.each)
    
    md2[Int](opts).using(_ + 1)     
    

提交回复
热议问题