gpt4 book ai didi

exception - 捕获的 Haskell 类型错误

转载 作者:行者123 更新时间:2023-12-04 21:14:35 25 4
gpt4 key购买 nike

我正在玩一些在线示例,其中有一个短语:

   do ... contents <- getDirectoryContents path `catch` const (return []) 

但它不会为我编译,并给出错误:
No instance for (Exception e0) arising from a use of `catch'
The type variable `e0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
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 a stmt of a 'do' block:
contents <- getDirectoryContents path `catch` const (return [])
In the expression:
do { contents <- getDirectoryContents path
`catch` const (return []);

我不得不改变它来为处理程序提供一个类型,现在可以了,但有点困惑:
contents <- getDirectoryContents path `catch` (\(SomeException e) -> const (return []) e)

所以我想知道为什么我需要进行这种更改,以及这是否是最简洁的方法。
(是的,我知道我可以使用 try、handle、...的替代形式)

最佳答案

catch有类型 Exception e => IO a -> (e -> IO a) -> IO a所以(e -> IO a)是您经过 const 的地方函数结果,但 const在这种情况下返回类型是 (e0 -> IO []) .如您所见,此类型具有 e0它不像 catch 那样受到限制,即 e应该有 Exception实例,这就是错误所说的。

因此,从概念上讲,您将“约束较少”的东西传递到需要“约束较多”的地方。

关于exception - 捕获的 Haskell 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20301634/

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