[Haskell-cafe] letting go of file handles and Data.Binary

Duncan Coutts duncan.coutts at worc.ox.ac.uk
Sun Apr 20 17:34:56 EDT 2008


On Sun, 2008-04-20 at 14:24 -0700, Bryan O'Sullivan wrote:
> Doh!  For all that I wrote about encodeFile, substitute decodeFile.


Indeed the version of encodeFile you wrote should be exactly identical
to the original because the lazy bytestring writeFile already uses
bracket like that:

writeFile :: FilePath -> ByteString -> IO ()
writeFile f txt = bracket (openBinaryFile f WriteMode) hClose
    (\hdl -> hPut hdl txt)

> strictDecodeFile :: Binary a => FilePath -> (a -> b) -> IO ()
> strictDecodeFile path force =
>     bracket (openFile path ReadMode) hClose $ \h -> do
>       c <- L.hGetContents h
>       force (decode c) `seq` return ()

Yes, the problem with Ben's program was that decodeFile is lazily
reading the file and lazily decoding. If the decoding consumes all the
input then it should be possible to avoid rewriting decodeFile and use:

  dat2 <- decodeFile fname
  evaluate dat2
  removeFile fname

It's not immediately clear to me if we can make the decodeFile behave
like your version. I'd have to go think about whether running the Get
monad can lazily return values or if it always consumes all the input
it'll ever need.

Duncan



More information about the Haskell-Cafe mailing list