我读RWH,我已经来到第9章介绍了下面的一段代码:“手柄”功能和真实世界哈斯克尔
import System.IO
import Control.Exception
saferFileSize :: FilePath -> IO (Maybe Integer)
saferFileSize path = handle (\_ -> return Nothing) $ do
h <- openFile path ReadMode
size <- hFileSize h
hClose h
return (Just size)
它不会然而编译,从而以下错误信息:
test.hs:5:22:
Ambiguous type variable `e0' in the constraint:
(Exception e0) arising from a use of `handle'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: handle (\ _ -> return Nothing)
In the expression:
handle (\ _ -> return Nothing)
$ do { h <- openFile path ReadMode;
size <- hFileSize h;
hClose h;
return (Just size) }
In an equation for `saferFileSize':
saferFileSize path
= handle (\ _ -> return Nothing)
$ do { h <- openFile path ReadMode;
size <- hFileSize h;
hClose h;
.... }
这是怎么回事?为什么不编译?
Haskell网站上'handle'函数的文档对此很不清楚(至少入门级别的人 - 需要文档的人)https://wiki.haskell.org/Exception感谢编译器只需要我们指定异常类型来处理的非常明确的解释! – jocull