我讀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