Is there a name for "maybe mzero return"?

221 views Asked by At

Is there an established name for maybe mzero return?

It has the type:

MonadPlus m => Maybe a -> m a

and converts Nothing to failure and Just a to return a.

1

There are 1 answers

4
dfeuer On

All of the above are the same.

An obvious variant would be

maybeAlt :: Alternative f => Maybe a -> f a
maybeAlt = maybe empty pure

And this is a special case of the following, similar to asum.

import Data.Monoid
import Control.Applicative

foldAlt :: (Foldable f, Alternative m) => f a -> m a
foldAlt = getAlt . foldMap (Alt . pure)

The reason you won't find this anywhere is that pure a <|> x === pure a. So it's good for this and not much else. It could be improved to

foldAltMap f = getAlt . foldMap (Alt . f)

or

foldrAltMap f = foldr (\x r -> f x <|> r) empty

but it's probably clearer just to write it out.