Lesson 22. Interacting with the command line and lazy I/O
After reading lesson 22, you’ll be able to
- Access command-line arguments
- Use the traditional approach to interacting through I/O
- Write I/O code using lazy evaluation to make I/O easier
Often when people first learn about I/O and Haskell, they assume that I/O is somewhat of a challenge for Haskell because Haskell is all about pure programs and I/O is anything but pure. But there’s another way to view I/O that makes it uniquely suited to Haskell, and somewhat clunky in other programming languages. Often when working with I/O in any language, we talk about I/O streams, but what is a stream? One good way to understand I/O streams is as a lazily evaluated list of characters. STDIN streams user input into a program until an eventual end is reached. But this end isn’t always known (and in theory could never occur). This is exactly how to think about lists in Haskell when using lazy evaluation.
This view of I/O is used in nearly every programming language when reading from large files. Often it’s impractical, or even impossible, to read a large file into memory before operating on it. But imagine that a given large file was simply some text assigned to a variable, and that variable was a lazy list. As you learned earlier, lazy evaluation allows you to operate on infinitely long lists. No matter how large your input is, you can handle it if you treat the problem like a large list.