在此代码中:
import System.Posix.Files
import Control.Exception
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path =
handle (\_ -> return Nothing) (getFileStatus path >>= (return . Just))
我收到此错误(在ghci中):
Ambiguous type variable `e0' in the constraint:
(Exception e0) arising from a use of `handle'
...
我可以通过以下方式解决错误:
nothing :: IOException -> Maybe a
nothing _ = Nothing
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path =
handle (return . nothing) (getFileStatus path >>= (return . Just))
发生什么事了?我希望汉德处理任何例外。
答案 0 :(得分:3)
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
答案 1 :(得分:3)
您可以在lambda函数的模式匹配中使用SomeException
值:
import System.Posix.Files
import Control.Exception
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path =
handle (\(SomeException _) -> return Nothing) (getFileStatus path >>= (return . Just))