由try产生的歧义类型

我试图在打开文件时做一些错误处理,以确保文件存在/可读。这是我的尝试:

init struct = do
    str <- try $ readFile (filePath struct)
    case str of
        Left exception -> print exception
        Right content -> execute content struct

(Struct 是一种数据结构,我在其中保留文件路径和其他变量)。我收到此错误:

使用 'try' 引起的不明确的类型变量 'a0' 阻止了约束 '(Exception a0)' 的解决。可能的解决方法:使用类型注释来指定 'a0' 应该是什么。

但我只是不明白如何解决它。

回答

这是因为 of 的结果try :: ... -> IO (Either e a)具有异常的类型参数,e而您只需将其放入print可以处理所有类型的东西(只要e位于 中Show) - 所以编译器不清楚中间e需要什么类型。

这非常类似于show . read- 那应该有类型String -> Stringread应该做什么?阅读 a Int, a Float- 不同的东西?


解决此问题的最简单方法是使用类型应用程序的 IMO:

{-# LANGUAGE TypeApplications #-}

init struct = do
    str <- try @IOException $ readFile (filePath struct)
    case str of
        Left exception -> print exception
        Right content -> execute content struct

当然,您可以在任何地方添加类型注释

str <- try $ readFile (filePath struct) :: IO (Either IOException MyStruct)

等等。


以上是由try产生的歧义类型的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>