gpt4 book ai didi

haskell - 如何使用 hFileSize 在 Haskell 中获取文件大小

转载 作者:行者123 更新时间:2023-12-03 15:26:34 25 4
gpt4 key购买 nike

我正在尝试获取 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 })

但我无法弄清楚发生了什么。

最佳答案

在我去谷歌后,我解决了这样的问题:

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

关于haskell - 如何使用 hFileSize 在 Haskell 中获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7878065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com