Haskell 什么是GHCi';MonadError的默认实现是什么?
考虑以下测试功能:Haskell 什么是GHCi';MonadError的默认实现是什么?,haskell,error-handling,ghci,Haskell,Error Handling,Ghci,考虑以下测试功能: 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> tes
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 ()
因为我已经声明了任意字符串作为表达式的类型,所以它使用MonadError的任意字符串实现。我假设如果我没有自己指定MonadError的实现,或者从另一个函数调用这个函数,允许类型推断,我会得到一个错误。相反:
*Main> testError True
*Main> testError False
*** Exception: user error (hello world)
看来GHCi提供了某种“默认”错误monad。有人能解释一下这里发生了什么吗?在GHCi的提示下键入的表达式会被检查两次:首先包装在
打印中,如果由于任何原因失败,则作为IO操作。在您的情况下,第一次尝试将由于歧义而失败,但第二次尝试使用MonadError
的IO
实例进行类型检查