2011-10-24 35 views
13

Sto cercando di ottenere la dimensione del file, come Real World Haskell raccomanda:Ottenere la dimensione del file in Haskell

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

E io ottenere questo errore:

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

Ma io non riesco a capire fuori cosa sta succedendo.

risposta

14

Dopo sono andato google ho risolto il problema in questo modo:

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

Nota che la ragione di questo è che Real World Haskell è stato scritto prima 'Control.Exception' è stato rinnovato nel' base' versione 4. (La vecchia interfaccia è deprecata, ma ancora disponibile in 'Control.OldException'). – hammar

+2

Puoi accorciare questo accendendo 'ScopedTypeVariables' -' (\ (_ :: SomeException) -> return Nothing) '. –

Problemi correlati