Eri*_*ikR 5 haskell exception-handling
在这段代码中:
import System.Posix.Files
import Control.Exception
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path =
handle (\_ -> return Nothing) (getFileStatus path >>= (return . Just))
Run Code Online (Sandbox Code Playgroud)
我收到此错误(在 ghci 中):
Ambiguous type variable `e0' in the constraint:
(Exception e0) arising from a use of `handle'
...
Run Code Online (Sandbox Code Playgroud)
我可以通过执行以下操作来消除错误:
nothing :: IOException -> Maybe a
nothing _ = Nothing
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path =
handle (return . nothing) (getFileStatus path >>= (return . Just))
Run Code Online (Sandbox Code Playgroud)
这是怎么回事???我希望处理程序处理任何异常。
SomeException您可以在 lambda 函数的模式匹配中使用值:
import System.Posix.Files
import Control.Exception
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path =
handle (\(SomeException _) -> return Nothing) (getFileStatus path >>= (return . Just))
Run Code Online (Sandbox Code Playgroud)
Ambiguous type variable意味着编译器无法推断类型。因为它可以是许多具有Exception类型类实例的数据类型。您可以使用SomeException来处理任何异常。例如:
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path = handle errorHandler $ fmap Just $ getFileStatus path
where
errorHandler :: SomeException -> IO (Maybe FileStatus)
errorHandler _ = return Nothing
Run Code Online (Sandbox Code Playgroud)