[Haskell-cafe] Data.Binary, strict reading

Duncan Coutts duncan.coutts at worc.ox.ac.uk
Fri Feb 27 12:57:24 EST 2009

On Thu, 2009-02-26 at 09:17 +0000, Neil Mitchell wrote:

> > I suggest you use withFile instead and decode from the Handle that gives
> > you (via hGetContents) rather than decodeFile from the file name. That
> > makes it much clearer. Of course you have to avoid doing lazy stuff, but
> > that should be ok, Binary is strict in reading by default.
> That was my first attempt, but the types didn't match up. I can
> withFile using a System.IO handle, but Data.Binary doesn't seem to be
> able to start going from a Handle. I guess I have to hop via the
> ByteString bit myself with hGetContents. That's perfectly fine, and
> much better than currently. However

Yes, you would use hGetContents.

> > readDB = io $ (dbLocation >>= r) `catch` (λ_ →  return empty)
> >       where r x = fmap (decode · BL.fromChunks · return) $ B.readFile x
> This seems to be a very nice way of doing it, the strictness is
> explicit in the ByteString.readFile. I've gone for this in my code.

I still think my suggestion was nicer. It makes the resource boundedness
completely explicit, not relying on any strictness properties. It also
doesn't unnecessarily read the whole file into memory before processing,
though I expect for your example that doesn't matter too much.


More information about the Haskell-Cafe mailing list