Created
November 11, 2013 18:55
-
-
Save bluegraybox/7418353 to your computer and use it in GitHub Desktop.
Shows how lazy evaluation of hGetContents interacts with the withFile's automatic handle close.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.Char | |
import System.IO | |
readFirstLine = withFile "test.txt" ReadMode (\handle -> do | |
line <- hGetLine handle | |
return line) | |
readAndPrintTestFile = withFile "test.txt" ReadMode (\handle -> do | |
contents <- hGetContents handle | |
-- unless we output contents in some way, it isn't evaluated, and will be empty | |
putStrLn contents | |
return contents) | |
readTestFile = withFile "test.txt" ReadMode (\handle -> do | |
contents <- hGetContents handle | |
let c = map toUpper contents -- this doesn't evaluate contents! | |
return contents) | |
main = do | |
putStrLn "==== Reading first line ====" | |
line <- readFirstLine | |
putStrLn line | |
putStrLn "==== Reading and printing whole file ====" | |
contents <- readAndPrintTestFile | |
putStrLn contents | |
putStrLn "==== Reading whole file ====" | |
contents <- readTestFile | |
putStrLn contents | |
putStrLn "==== Done ====" | |
return () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run it, do something like: