I wonder why scala.Option
doesn\'t have a method fold
like this defined:
fold(ifSome: A => B , ifNone: => B)
<
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.