2011-10-24 18 views
13

我試圖得到像真實世界哈斯克爾文件的大小獲取文件的大小建議:在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 }) 

但我不能圖瞭解正在發生的事情。

回答

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

請注意,這樣做的原因是,Control.Exception'在'base'版本4.修補前'真實世界哈斯克爾寫(舊的接口已棄用,但仍可在Control.OldException中找到)。 – hammar

+2

通過打開'ScopedTypeVariables' - '(\(_ :: SomeException) - > return Nothing)''可以縮短這個時間。 –