Clinton
Clinton

Reputation: 23135

Either [Char] a -> IO a function

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

Answers (1)

Dietrich Epp
Dietrich Epp

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

Related Questions