Skip to content

Instantly share code, notes, and snippets.

@wfaler
Created November 12, 2014 15:40
Show Gist options
  • Save wfaler/70f20f9f27f9fc66bf61 to your computer and use it in GitHub Desktop.
Save wfaler/70f20f9f27f9fc66bf61 to your computer and use it in GitHub Desktop.
Must be a better way? some configuration of MaybeT?
ioMaybe :: Maybe a -> (a -> IO (Maybe b)) -> IO (Maybe b)
ioMaybe (Just a) fn = fn a
ioMaybe Nothing _ = return Nothing
@ijuma
Copy link

ijuma commented Nov 12, 2014

@aloiscochard came up with the following:

traverseM f m = fmap join $ traverse f m

@aloiscochard
Copy link

@wfaler actually, I think such code is a smell that you should use a transformer (in this case MaybeT).

At TO we use traverseM a lot, but I think it's just because we don't use transformer when we should.

I don't think I ever used that function in Haskell, that's why I would highly recommend try to put transformers in the mix.

@nlim
Copy link

nlim commented Nov 12, 2014

I'm not sure if this is any more concise but it works:

import Control.Monad.Trans.Maybe

ioMaybe :: Maybe a -> (a -> IO (Maybe b)) -> IO (Maybe b)
ioMaybe ma f = runMaybeT $ mta >>= f'
  where mta = MaybeT . return $ ma
        f'  = MaybeT . f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment