[Haskell-cafe] problem with IO, strictness, and "let"

Stefan O'Rear stefanor at cox.net
Fri Jul 13 00:30:03 EDT 2007

On Thu, Jul 12, 2007 at 09:22:09PM -0700, Michael Vanier wrote:
> I stumbled across a problem with IO and strictness that I could fix, but I 
> can't understand why the fix works.  I've compressed it down into a program 
> which simply computes the number of lines in a file.  Here is a version 
> that doesn't work:
> module Main where
> import System.IO
> import System.Environment
> process_file :: FilePath -> IO ()
> process_file filename =
>     do h <- openFile filename ReadMode
>        c <- hGetContents h
>        let cs = unlines $ lines c
>        hClose h
>        putStrLn $ show $ length cs

The problem is that you're closing the file twice.  When you call any
function of the getContents family, you assign to that function the
responsibility to close the file, no sooner than it is no longer needed.
Don't call hClose yourself, Bad Things will happen.

If you get rid of hClose, laziness will not hurt you - infact it will
help you, by allowing your program to run in constant space.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070712/c67cdb0f/attachment.bin

More information about the Haskell-Cafe mailing list