Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top