29

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?

user1078763
  • 728
  • 5
  • 15

1 Answers1

27
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.

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187
ehird
  • 40,602
  • 3
  • 180
  • 182
  • Thx, this is already an improvement. But can we do even better? – user1078763 Dec 30 '11 at 21:34
  • Than `maybe mzero return`? I doubt it; that's very short already. I don't suggest inlining this everywhere you use it; putting it into a common module is a much better idea. – ehird Dec 30 '11 at 21:35
  • This can also be seen as a specific use of something like `fmapT :: (Monad m, Monad n, MonadTransformer t) => (forall a. m a -> n a) -> (forall a. t m a -> t n a)`, but only if we pretend that `Maybe` is actually `MaybeT Identity`. I don't think that function is possible in full generality, but could be made into a type class with specific monad transformers as instances. – C. A. McCann Dec 30 '11 at 21:42
  • I think you mean `t n b` there. – ehird Dec 30 '11 at 21:43
  • 1
    `t n a`, actually. Ugh, this is why I need a type checker. – C. A. McCann Dec 30 '11 at 21:45
  • I think it is interesting that the results from Hayoo for `Maybe a -> m a` are more relevant then [those from Hoogle](http://www.haskell.org/hoogle/?hoogle=Maybe+a+-%3E+m+a) (at least it came as a surprise to me). – user1078763 Dec 30 '11 at 21:49
  • Hayoo searches all of Hackage; Hoogle only searches a much smaller set of packages (but it does more fancy unification tricks with the queries). For seeing what names people use to name standard combinators like this, Hayoo is the best bet. (BTW, in case you don't know: You can click the tick-mark next to an answer to accept it.) – ehird Dec 30 '11 at 21:52
  • 2
    The `errors` packages names it `hoistMaybe`: https://hackage.haskell.org/package/errors-1.4.7/docs/Control-Error-Util.html – Emmanuel Touzery Aug 02 '14 at 13:29