🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Files in Depth

Haskell files in depth are the tools for appending, splitting, and measuring file text beyond a single write and read. They let a program grow a file and check what it holds.

Appending keeps the old text

The first write stores one line. The append adds a second line after it.

main :: IO ()
main = do
  writeFile "deep-a.txt" "one\n"
  appendFile "deep-a.txt" "two\n"
  txt <- readFile "deep-a.txt"
  putStr txt

Lines splits text into a list

The file holds three short lines. lines turns them into a list the program can count.

main :: IO ()
main = do
  writeFile "deep-b.txt" "a\nbb\nccc\n"
  txt <- readFile "deep-b.txt"
  print (length (lines txt))
  print (lines txt)

Unlines builds text from lines

Numbers become text with show. unlines joins them with a newline after each one.

main :: IO ()
main = do
  writeFile "deep-c.txt" (unlines (map show [10,20,30]))
  txt <- readFile "deep-c.txt"
  putStr txt

Example

main :: IO ()
main = do
  writeFile "deep-log.txt" "start\n"
  appendFile "deep-log.txt" "step1\n"
  appendFile "deep-log.txt" "step2\n"
  txt <- readFile "deep-log.txt"
  print (length (lines txt))
  print (lines txt)

Key points

  • Append: appendFile adds text to the end of a file without erasing what is already there.
  • Lines: lines splits file text into one string for each line.
  • Unlines: unlines joins a list of lines into file text with a newline after each line.
  • Show numbers: show turns a number into text before it is written to a file.
  • Length: length counts the lines or characters in file text.

In this example, the program writes a start line to a log file. It appends two more lines to the same file. It reads the file back and prints how many lines it holds and the lines themselves.

Note

readFile reads lazily, so its text must be printed or measured before the same path is written again.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does appendFile do to a file that already has text?