5

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.

duplode
  • 33,731
  • 7
  • 79
  • 150
ErikR
  • 51,541
  • 9
  • 73
  • 124

1 Answers1

8

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.

dfeuer
  • 48,079
  • 5
  • 63
  • 167
  • 2
    I was wondering if the community has come around to a consensus as to what it should be called. Seems like a candidate for inclusion in `base` somewhere. – ErikR May 17 '16 at 02:24
  • @ErikR, I don't know about that. Sorry. – dfeuer May 17 '16 at 02:29
  • @dfeuer Perhaps `foldAlt = asum . fmap pure` makes it more clear exactly how it is similar to `asum`. – Daniel Wagner May 17 '16 at 02:35
  • @DanielWagner, that has a rather more restrictive type. Can that be fixed? There's also an operational difference; I imagine the `asum` way is often (usually?) better, but I don't know if it always is. One option is `foldAlt = foldr (\x r -> pure x <|> r) empty`. – dfeuer May 17 '16 at 02:42