GHCi 对 MonadError 的默认实现是什么?

发布于 2024-09-08 22:57:23 字数 663 浏览 2 评论 0原文

考虑以下测试函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别再吹冷风 2024-09-15 22:57:23

在 GHCi 提示符下键入的表达式会进行两次类型检查:首先用 print 包装,如果由于任何原因失败,则作为 IO 操作。在您的情况下,第一次尝试将由于不明确而失败,但第二次尝试使用 MonadErrorIO 实例进行类型检查。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文