The problems with lazy I/O
Let's use the
hGetLine
function alongside the hGetContents
function:
main = do h <- openFile "jabberwocky.txt" ReadMode firstLine <- hGetLine h -- returns a string contents <- hGetContents h -- returns a "promise" hClose h -– close file print $ words firstLine print $ words contents
We close the file before consuming the firstLine
string and the contents
stream:
print $ words firstLine ["'Twas","brillig,","and","the","slithy","toves"] print $ words contents []
The contents
is a live stream that gets turned off when the file is closed. The firstLine
is an eager string and survives the closing of the file.
The preceding example points to some serious problems with the lazy I/O:
- The order of the side effects is tied to the order of the lazy evaluation. Because the order of lazy evaluation is not explicit, the order of effects...