Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a Maybe value into MaybeT

Say I have some foo :: Maybe Int and I want to bind it for example with bar :: Int -> MaybeT (Writer String) Int, what would be the idiomatic way to do that?

I could define my own liftMaybe function, and then use that, like:

let liftMaybe = maybe (fail "Nothing") return in liftMaybe foo >>= bar 

But is there a more idiomatic (or at least concise) way to do that?

like image 845
user1078763 Avatar asked Dec 30 '11 21:12

user1078763


1 Answers

MaybeT . return :: (Monad m) => Maybe a -> MaybeT m a 

I think it's a shame it doesn't have a standard name, however doing a hoogle search, we see that the relude packages uses hoistMaybe:

hoistMaybe :: Applicative m => Maybe a -> MaybeT m a 

A more general form is

liftMaybe :: (MonadPlus m) => Maybe a -> m a liftMaybe = maybe mzero return 

which is preferable to the use of fail. I'd just put it in a convenient module somewhere.

like image 173
ehird Avatar answered Sep 20 '22 13:09

ehird