I wonder why scala.Option
doesn't have a method fold
like this defined:
fold(ifSome: A => B , ifNone: => B)
equivalent to
map(ifSome).getOrElse(ifNone)
Is there no better than using map
+ getOrElse
?
I wonder why scala.Option
doesn't have a method fold
like this defined:
fold(ifSome: A => B , ifNone: => B)
equivalent to
map(ifSome).getOrElse(ifNone)
Is there no better than using map
+ getOrElse
?
I personally find methods like
cata
that take two closures as arguments are often overdoing it. Do you really gain in readability overmap
+getOrElse
? Think of a newcomer to your code: What will they make ofDo you really think this is clearer than
In fact I would argue that neither is preferable over the good old
As always, there's a limit where additional abstraction does not give you benefits and turns counter-productive.
You can do:
or
(Both solutions will evaluate
els
by value, which might not be what you want. Thanks to Rex Kerr for pointing at it.)Edit:
But what you really want is Scalaz’s catamorphism
cata
(basically afold
which not only handles theSome
value but also maps theNone
part, which is what you described)defined as (where
value
is the pimped option value)which is equivalent to
opt.map(some).getOrElse(none)
.Although I should remark that you should only use cata when it is the ‘more natural’ way of expressing it. There are many cases where a simple
map
–getOrElse
suffices, especially when it involves potentially chaining lots ofmap
s. (Though you could also chain thefun
s with function composition, of course – it depends on whether you want to focus on the function composition or the value transformation.)As mentioned by Debilski, you can use Scalaz's
OptionW.cata
orfold
. As Jason commented, named parameters make this look nice:Now, if the value you want in the
None
case ismzero
for someMonoid[M]
and you have a functionf: A => M
for theSome
case, you can do this:So,
becomes
Personally, I think
Option
should have anapply
method which would be the catamorphism. That way you could just do this:or
In fact, this would be nice to have for all algebraic data structures.
It was finally added in Scala 2.10, with the signature
fold[B](ifEmpty: => B)(f: A => B): B
.Unfortunately, this has a common negative consequence:
B
is inferred for calls based only on theifEmpty
argument, which is in practice often more narrow. E.g. (a correct version is already in the standard library, this is just for demonstration)Scala will infer
B
to beNil.type
instead of desiredList[A]
and complain aboutf
not returningNil.type
. Instead, you need one ofThis makes
fold
not quite equivalent to correspondingmatch
.