5

在这段代码中:

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))

这是怎么回事???我希望处理程序处理任何异常。

4

2 回答 2

4

Ambiguous type variable意味着编译器无法推断类型。因为它可以是许多具有异常类型类实例的数据类型。您可以使用SomeException来处理任何异常。例如:

safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path = handle errorHandler $ fmap Just $ getFileStatus path
  where
    errorHandler :: SomeException -> IO (Maybe FileStatus)
    errorHandler _ = return Nothing
于 2012-08-20T02:23:23.347 回答
4

您可以SomeException在 lambda 函数的模式匹配中使用值:

import System.Posix.Files
import Control.Exception

safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path =
  handle (\(SomeException _) -> return Nothing) (getFileStatus path >>= (return . Just))
于 2012-08-20T09:54:24.430 回答