Reputation: 23135
How can I write a function so that Left x
to an IO error but Right x
returns its result as usual, i.e. the function has signature Either [Char] a -> IO a
?
Basically I want the Left err
result to become the err
in the IO Monad.
Upvotes: 2
Views: 211
Reputation: 213578
One simple definition is:
f :: Either String a -> IO a
f = either (ioError . userError) return
Note that we can make this generic with fail
, but it's really a historical accident that fail
is in Monad
to begin with, so I wouldn't use this definition:
f :: Monad m => Either String a -> m a
f = either fail return
A better generic version might use the MonadError
class:
import Control.Monad.Error.Class
f :: MonadError e m => Either String a -> m a
f = either (throwError . strMsg) return
Upvotes: 14