我正在努力获得像Real World Haskell建议的文件大小:
getFileSize :: FilePath -> IO (Maybe Integer)
getFileSize path = handle (\_ -> return Nothing)
$ bracket (openFile path ReadMode) (hClose) (\h -> do size <- hFileSize h
return $ Just size)
我收到了这个错误:
Ambiguous type variable `e0' in the constraint:
(GHC.Exception.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)
$ bracket
(openFile path ReadMode)
(hClose)
(\ h
-> do { size <- hFileSize h;
return $ Just size })
In an equation for `getFileSize':
getFileSize path
= handle (\ _ -> return Nothing)
$ bracket
(openFile path ReadMode)
(hClose)
(\ h
-> do { size <- hFileSize h;
return $ Just size })
但我无法弄清楚发生了什么。
答案 0 :(得分:14)
我去google后解决了这个问题:
getFileSize :: FilePath -> IO (Maybe Integer)
getFileSize path = handle handler
$ bracket (openFile path ReadMode) (hClose) (\h -> do size <- hFileSize h
return $ Just size)
where
handler :: SomeException -> IO (Maybe Integer)
handler _ = return Nothing