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

问题描述 投票:13回答:1

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

但是我不知道发生了什么。

haskell
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.