Why doesn't Option have a fold method?

后端 未结 4 2236
甜味超标
甜味超标 2020-12-14 00:56

I wonder why scala.Option doesn\'t have a method fold like this defined:

fold(ifSome: A => B , ifNone: => B)
<
4条回答
  •  抹茶落季
    2020-12-14 01:18

    As mentioned by Debilski, you can use Scalaz's OptionW.cata or fold. As Jason commented, named parameters make this look nice:

    opt.fold { ifSome = _ + 1, ifNone = 0 }
    

    Now, if the value you want in the None case is mzero for some Monoid[M] and you have a function f: A => M for the Some case, you can do this:

    opt foldMap f
    

    So,

    opt map (_ + 1) getOrElse 0
    

    becomes

    opt foldMap (_ + 1)
    

    Personally, I think Option should have an apply method which would be the catamorphism. That way you could just do this:

    opt { _ + 1, 0 }
    

    or

    opt { some = _ + 1, none = 0 }
    

    In fact, this would be nice to have for all algebraic data structures.

提交回复
热议问题