On Wed, Dec 10, 2014 at 3:36 AM, Mike Meyer <mwm@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.