Files

Dear Computer

Chapter 7: Immutability and I/O

Files

The simplest way to read a file in Haskell is the readFile function. We pass it the name of the file as a String, and it slurps up all the text and returns an IO String, which we unpack using the <- operator:

Haskell
main = do
  text <- readFile "playlist.txt"
  putStrLn text

If we want to process the file line by line, we use the lines function, which splits up a String on its linebreaks. It is a pure function, not an IO function, which means we assign its result to a variable using =. Here it is used in a let binding:

Haskell
main = do
  text <- readFile "playlist.txt"
  let entries = lines text
  putStrLn (show entries)

There's also a similar words function that breaks the text up on any whitespace, not just linebreaks.

The counterpart to readFile is writeFile. We pass it the name of a file and the String to write:

Haskell
main = do
  writeFile "baby-names.txt" "Slar\nBizness\nRuckus\n"

If we don't want to assemble a single String that we output all at once, we can use openFile from the System.IO module. It returns a file handle, which we can pass to the accompanying hPutStrLn to output one line at a time:

Haskell
import System.IO

main = do
  file <- openFile "baby-names.xt" WriteMode
  hPutStrLn file "Slar"
  hPutStrLn file "Bizness"
  hPutStrLn file "Ruckus"
  hClose file
← IterationGuessing Game →