小编Pao*_*tti的帖子

如何在Haskell中实现safeReadFile函数以产生Maybe String

我正在尝试loadFile在Haskell中实现一个安全功能,该功能可以捕获任何异常并产生a,Maybe String但以下实现无法编译

 import System.IO         (readFile)
 import Control.Exception (catch, IOException)

 -- readFile :: FilePath -> IO String

 -- this compiles good
 safeReadFile :: FilePath -> IO (Either IOException String)
 safeReadFile p =
    (Right <$> readFile p) `catch`
    (\e -> pure $ Left e)

 -- this does not!
 safeReadFile' :: FilePath -> IO (Maybe String)
 safeReadFile' p =
    (Just <$> readFile p) `catch` 
    (\e -> pure Nothing)
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么GCH提出以下问题吗?

  Ambiguous type variable ‘e0’ arising from a use of ‘catch’ …
Run Code Online (Sandbox Code Playgroud)

io monads haskell types exception-handling

3
推荐指数
1
解决办法
179
查看次数

标签 统计

exception-handling ×1

haskell ×1

io ×1

monads ×1

types ×1