[Haskell-beginners] Good way of combining functions of type IO (Maybe a)

Yitzchak Gale gale at sefer.org
Tue Mar 4 07:13:54 UTC 2014


Nathan Hüsken wrote:
>> I want to write a function, which is basically a concatenation of
>> functions of type "IO (Maybe a)".

David McBride wrote:
> cabal install maybet

I would recommend using the standard MaybeT
type, from the transformers library that is
part of the Haskell Platform, unless you have
a special reason to use a different library
from Hackage.

David's code works fine with the transformers library,
after a slight modification of the import:

import Control.Monad.Trans.Maybe

Also - using the MaybeT monad is not the only
way to do this. Maybe comes with a whole
collection of very convenient combinators like
"maybe", "fromMaybe", etc. So you can also do
the calculation entirely in just IO without
very much extra noice. Choose the approach
that works out nicest for your particular
application.

Here is David's code, modified to do the
calculations directly in the IO monad:

f1 :: IO (Maybe Int)
f1 = return . Just $ 1

d2 :: Int -> IO (Maybe String)
d2 = return . Just . show

blah :: IO (Maybe (Int, String))
blah = do
  a <- f1
  b <- maybe (return Nothing) d2 a
  return (a,b)

If you end up using things like
"maybe (return Nothing)" and
"fromMaybe (return Nothing)" a lot,
you can define aliases for them.
Perhaps there ought to be aliases like
that in the standard libraries somewhere...

Regards,
Yitz


More information about the Beginners mailing list