Skip to content

Instantly share code, notes, and snippets.

@bluegraybox
Created November 11, 2013 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluegraybox/7418353 to your computer and use it in GitHub Desktop.
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.
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 ()
@bluegraybox
Copy link
Author

To run it, do something like:

$ cat - > test.txt 
This is the first line.
This is the second line.
^d
$ ghc --make file_io_example && ./file_io_example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment