[Haskell-beginners] Buggy behavior of "withFile"

Kim-Ee Yeoh ky3 at atamo.com
Fri Dec 12 08:36:32 UTC 2014


On Wed, Dec 10, 2014 at 3:36 AM, Mike Meyer <mwm at mired.org> wrote:
>
> If I'm right, you need to force the evaluation of res before the return,
> with something like "res seq return res" instead of just "return res".  Or
> use the BangPatterns extension and then write "!res <- hGetContents h"


This will read one byte (or none at all if the file is empty).

That one byte will then be displayed by the putStr outside the withFile
expression. It's a small but noticeable improvement to nothing being
displayed at all.

Why one byte? Because seq evaluates only to weak head normal form (WHNF),
which in the case of a list, amounts to determining whether it's [] or
(x:xs).

You could write

res <- hGetContents h
evaluate $ length res         -- Control.Exception.evaluate
return res

but if you're going to do that, you're better off using Strict I/O. And in
fact, strict _bytestring_ I/O because the spatial footprint of lists is 10x
bytestrings.

But really, the default built-in lazy I/O on standard lists are fine for
general usage. Avoid premature optimization.

-- Kim-Ee
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20141212/016d4f91/attachment.html>


More information about the Beginners mailing list