[英]Haskell type error with catch
我正在玩一些在線示例,其中一個有這樣的短語:
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)
所以我想知道為什么我需要做出這個改變,如果這是最簡潔的方法。 (是的,我知道我可以使用替代形式的嘗試,處理,...)
catch
有類型Exception e => IO a -> (e -> IO a) -> IO a
so (e -> IO a)
是你傳遞const
函數結果的地方但是在這種情況下const
返回類型是(e0 -> IO [])
。 正如你所看到的那樣,這個類型的e0
,就像catch中所要求的那樣,即e
應該有Exception
實例,這就是錯誤所說的內容。
因此,從概念上講,您正在將“受限制較少”的內容傳遞到需要“更多約束”的地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.