gpt4 book ai didi

haskell - 异常类型错误

转载 作者:行者123 更新时间:2023-12-02 15:00:20 24 4
gpt4 key购买 nike

我正在学习 Haskell 中的异常如何工作。
当尝试复制this时Prelude 中的简单示例我得到:

GHCi, version 7.10.2: http://www.haskell.org/ghc/  :? for help
Prelude> :m Control.Exception
Prelude Control.Exception> let x = 5 `div` 0
Prelude Control.Exception> let y = 5 `div` 1
Prelude Control.Exception> print x
*** Exception: divide by zero
Prelude Control.Exception> print y
5
Prelude Control.Exception> try (print x)

<interactive>:16:1:
No instance for (Show (IO (Either e0 ())))
arising from a use of `print'
In a stmt of an interactive GHCi command: print it
Prelude Control.Exception>

为什么我在 try(print x) 上收到无实例错误,而之前我遇到了异常?

最佳答案

问题是 Haskell/GHCi 不知道 e0 的类型,因此您必须对其进行注释:

try (print x) :: IO (Either ArithException ()) 

原因是在编译时有很多可能的实例(对于不同的异常):see here for a description - 且GHCi无法选择

如果您更深入地研究表达式,您可以让 GHCi 告诉您(或多或少不会直接强制GHCi显示它):

Prelude Control.Exception> e <- try (print x)

<interactive>:5:6:
No instance for (Exception e0) arising from a use of `try'
The type variable `e0' is ambiguous
Note: there are several potential instances:
instance Exception NestedAtomically
-- Defined in `Control.Exception.Base'
instance Exception NoMethodError
-- Defined in `Control.Exception.Base'
instance Exception NonTermination
-- Defined in `Control.Exception.Base'
...plus 7 others
In the first argument of `GHC.GHCi.ghciStepIO ::
IO a_a18N -> IO a_a18N', namely
`try (print x)'
In a stmt of an interactive GHCi command:
e <- GHC.GHCi.ghciStepIO :: IO a_a18N -> IO a_a18N (try (print x))
<小时/>

当然,您不必猜测正确的异常(就像IArithException所做的那样) - 相反,您可以使用SomeException捕获:

Prelude Control.Exception> try (print x) :: IO (Either SomeException ())
Left divide by zero

关于haskell - 异常类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com