In Haskell, is there an abstraction for the <?>-operator?
I think it's a good idea to leave things at (<?>) = flip fromMaybe
.
If you'd like to generalize though, Foldable
seems to be the simplest class with a notion of emptiness:
(<?>) :: Foldable t => t a -> a -> a
ta <?> a = foldr const a ta
This returns a
if ta
is empty or else the first element of ta
. Examples:
Just 0 <?> 10 == 0
Nothing <?> 0 == 0
[] <?> 10 == 10
Actually, I don't like <?>
operator name for what you are looking for.
If you search for Maybe a -> a -> a
type on Stackage or Hayoo you can find ?:
operator from errors
package.
And this operator is so called elvis-operator. It is used in Groovy in that form. And Kotlin also had it. This operator helps to deal with nulls in imperative language. But if you imagine that Maybe a
is some kind of nullable type then ?:
operator makes sense for you as well. You can observe fact that there is some history behind ?:
operator.
Also, <?>
is already used in some packages like megaparsec, attoparsec, optparse-generic and others. And your project may use one of those with high probability. So you may experience some conflicts using your version of elvis-operator.
The only two abstraction of "emptyness" I can think on top of my head are:
First, MonadError
: Maybe
could have instance MonadError () Maybe
. See however https://github.com/ekmett/mtl/issues/27
Second, lens
_Empty
,
which is by default comparison (Eq
) with mempty
(of Monoid
). However Monoid
and Alternative
disagree for Maybe
.
Yet I don't recall any operator directly working on either one above.