GHCi 对 MonadError 的默认实现是什么?
考虑以下测试函数:
testError :: (Error e, MonadError e m) => Bool -> m ()
testError True = return ()
testError False = throwError $ strMsg "hello world"
在 GHCi 提示符下,我可以执行以下操作:
*Main> testError False :: Either String ()
Left "hello world"
*Main> testError True :: Either String ()
Right ()
因为我已将 Either String _ 声明为表达式的类型,所以它使用 MonadError 的 Either String 实现。我假设如果我自己没有指定 MonadError 的实现,或者从另一个函数调用这个函数,允许类型推断,我会得到一个错误。相反:
*Main> testError True
*Main> testError False
*** Exception: user error (hello world)
GHCi 似乎正在提供某种“默认”错误单子。有人可以解释一下这是怎么回事吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 GHCi 提示符下键入的表达式会进行两次类型检查:首先用
print
包装,如果由于任何原因失败,则作为 IO 操作。在您的情况下,第一次尝试将由于不明确而失败,但第二次尝试使用MonadError
的IO
实例进行类型检查。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 theIO
instance ofMonadError
.