[Haskell-cafe] Monad m => m (Maybe a) -> m (Maybe a) -> m (Maybe a)

Evan Laforge qdunkan at gmail.com
Tue Nov 11 16:57:48 UTC 2014


I've been using these functions lately:

try :: Monad m => m (Maybe a) -> m (Maybe a) -> m (Maybe a)
try action alternative = maybe alternative (return . Just) =<< action

tries :: Monad m => [m (Maybe a)] -> m (Maybe a)
tries = foldr try (return Nothing)

It's sort of like (<|>) on Maybe, or MonadPlus, but within a monad.
It seems like the sort of thing that should be already available, but
hoogle shows nothing.  I think 'm' has to be a monad, and I can't
figure out how to generalize the Maybe to MonadPlus or Alternative.
It's sort of a mirror image to another function I use a lot:

justm :: Monad m => m (Maybe a) -> (a -> m (Maybe b)) -> m (Maybe b)
justm op1 op2 = maybe (return Nothing) op2 =<< op1

... which is just MaybeT for when I can't be bothered to put runMaybeT
and lifts and hoists on everything.  So you could say 'try' is like
MaybeT with the exceptional case reversed.

Is 'try' just the instantiation of some standard typeclass, or is it
its own thing?


More information about the Haskell-Cafe mailing list