在Haskell中获取文件大小

fra*_*nza 13 haskell

我试图获得像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)
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

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 })
Run Code Online (Sandbox Code Playgroud)

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

fra*_*nza 14

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

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
Run Code Online (Sandbox Code Playgroud)

  • 请注意,其原因是Real.net Haskell是在`base.version`版本4中修改了`Control.Exception`之前编写的.旧的接口已被弃用,但在`Control.OldException`中仍然可用. (8认同)
  • 你可以通过启用`ScopedTypeVariables` - `(\(_ :: SomeException) - > return Nothing)来缩短它. (2认同)