如何在Haskell中实现生成字符串的safeReadFile函数

如何在Haskell中实现生成字符串的safeReadFile函数,haskell,types,exception-handling,io,monads,Haskell,Types,Exception Handling,Io,Monads,我试图在Haskell中实现一个安全的loadFile函数,它捕获任何异常并生成一个Maybe字符串,但是下面的实现没有编译 import System.IO (readFile) import Control.Exception (catch, IOException) -- readFile :: FilePath -> IO String -- this compiles good safeReadFile :: FilePath -> IO (E

我试图在Haskell中实现一个安全的
loadFile
函数,它捕获任何异常并生成一个
Maybe字符串
,但是下面的实现没有编译

 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)

如何在
e
变量上应用必要的类型注释?Haskell文档没有给出任何线索:-(

您必须指定要捕获的异常类型。
safeLoadFile
明确提到了
IOException
,而
safeLoadFile'
没有

请尝试以下方法:

safeLoadFile' :: FilePath -> IO (Maybe String)
safeLoadFile' p =
    (Just <$> loadFile p) `catch` 
    ((\e -> pure Nothing) :: IOException -> IO (Maybe String))
我通常使用
(\e->pure$const Nothing(e::IOException))
。我发现它比其他选项稍微简单一些。
safeLoadFile' :: FilePath -> IO (Maybe String)
safeLoadFile' p =
    (Just <$> loadFile p) `catch` 
    ((\e -> pure Nothing) :: IOException -> IO (Maybe String))
safeLoadFile' :: FilePath -> IO (Maybe String)
safeLoadFile' p = (Just <$> loadFile p) `catch` handler
   where
   handler :: IOException -> IO (Maybe String)
   handler _ = pure Nothing