Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get size of file in Haskell using hFileSize

Tags:

haskell

I'm trying to get size of file like Real World Haskell recommends:

getFileSize :: FilePath -> IO (Maybe Integer)
getFileSize path = handle (\_ -> return Nothing)
                   $ bracket (openFile path ReadMode) (hClose) (\h -> do size <- hFileSize h
                                                                         return $ Just size)

And I get this error:

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 })

But I can't figure out what is going on.

like image 509
franza Avatar asked Oct 24 '11 15:10

franza


1 Answers

After I went google I solved the problem like this:

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
like image 120
franza Avatar answered Nov 02 '22 16:11

franza