[Haskell-cafe] How to simplify the code of Maybe within a monad?

Ertugrul Söylemez es at ertes.de
Fri Aug 17 06:22:29 CEST 2012

Magicloud Magiclouds <magicloud.magiclouds at gmail.com> wrote:

>   Since Maybe is a monad, I could write code like 'maybeA >> maybeB >>
> maybeC' to check if all these are not Nothing. Or 'liftM foo maybeD'
> to avoid ugly 'case of'.

Also check out the somewhat cleaner Functor class with its liftM
equivalent called 'fmap', for which you don't need to import
Control.Monad.  For monads fmap = liftM.

>   But how if here maybe[ABC] are like 'IO (Maybe Int)', or foo is type
> of 'Int -> IO Int'?

Well, this is Haskell, so you can always write your own higher order

    (~>>=) :: (Monad m) => m (Maybe a) -> (a -> m (Maybe b)) -> m (Maybe b)
    c ~>>= f = c >>= maybe (return Nothing) f

    (~>>) :: (Monad m) => m (Maybe a) -> m (Maybe b) -> m (Maybe b)
    c ~>> d = c >>= maybe (return Nothing) (const d)

    infixl 1 ~>>=
    infixl 1 ~>>

However in the second case of course there is no Maybe, but then notice
that IO itself acts like Maybe through its exceptions.  In fact Maybe is
a transparent exception monad.


Not to be or to be and (not to be or to be and (not to be or to be and
(not to be or to be and ... that is the list monad.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120817/42c13c18/attachment-0001.pgp>

More information about the Haskell-Cafe mailing list