views:

81

answers:

1

Consider the following test function:

testError :: (Error e, MonadError e m) => Bool -> m ()
testError True  = return ()
testError False = throwError $ strMsg "hello world"

At the GHCi prompt, I can do the following:

*Main> testError False :: Either String ()
Left "hello world"
*Main> testError True :: Either String ()
Right ()

Because I have stated Either String _ as the expression's type, it uses the Either String implementation of MonadError. I was assuming that if I didn't specify an implementation of MonadError myself, or call this function from another function, allowing for type inference, I would get an error. Instead:

*Main> testError True
*Main> testError False
*** Exception: user error (hello world)

It would appear that GHCi is providing some kind of "default" error monad. Can someone explain what is going on here?

+11  A: 

Expressions typed at the prompt in GHCi are typechecked twice: first wrapped in print, and if that fails for any reason, then as an IO operation. In your case the first attempt would fail due to ambiguity, but the second attempt typechecks using the IO instance of MonadError.

Simon Marlow