Lesson 24. Working with files

 

After reading lesson 24, you’ll be able to

  • Work with file handles in Haskell
  • Read from and write to files
  • Understand limitations of lazy evaluation for I/O

One of the most important uses of I/O is to read and write from files. So far in this unit, you’ve learned a bit of the syntax behind IO types in Haskell, saw how to build command-line programs using lazy evaluation, and learned about efficient text processing by using the Text type. Now you’ll look at working with files, including how they can make using lazy I/O a bit tricky. You’ll start with the basics of opening, closing, reading from, and writing to simple files. Then you’ll write a program that takes various statistics from an input file (including word count and character count) and writes them to a file. You’ll discover that even in this rather straightforward task, lazy evaluation can be a major headache. The solution is to use strict data types to force the program to perform as you’d expect.

Consider this

In lesson 22, you saw a way to add up numbers entered in as user input. How can you write the same program that works with a file rather than user input (other than manually piping the file into your program)?

24.1. Opening and closing files

Before learning how files work in Haskell, you need to have a file to work with. You’ll look at the basics of opening and closings files. Your first task is to open and close a text file. Here’s the hello.txt file you’ll start with.

24.2. Simple I/O tools

24.3. The trouble with lazy I/O

24.4. Strict I/O

Summary