
That makes sense. Thanks! Mike Stefan O'Rear wrote:
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.
Stefan