2011-10-24 30 views
13

Tôi đang cố gắng để có được kích thước của tập tin như Real World Haskell khuyến cáo:Nhận kích thước của tập tin trong Haskell

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

Và tôi nhận được lỗi này:

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

Nhưng tôi không thể hình những gì đang xảy ra.

Trả lời

14

Sau khi tôi đã đi google tôi giải quyết vấn đề như thế này:

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 
+8

Lưu ý rằng lý do cho điều này là Real World Haskell đã được viết trước khi 'Control.Exception' được tân trang trong' phiên bản base' 4. (Giao diện cũ không được dùng nữa, nhưng vẫn có sẵn trong 'Control.OldException'). – hammar

+2

Bạn có thể thực hiện việc này ngắn hơn bằng cách bật 'ScopedTypeVariables' -' (\ (_ :: SomeException) -> return Nothing) '. –

Các vấn đề liên quan