At the beginning of this chapter, you learned about laziness and what that means for performing IO in Haskell applications. After that we looked at several small examples of how to work with IO in Haskell, building up more complex IO actions from smaller ones and creating programs that have useful side effects. Although the examples we looked at should have helped you gain an intuition for working with IO, so far we’ve managed to get away with avoiding having to understand too much about the details of how IO is working, and without having to think too much about the performance of our application. In Haskell applications that do a lot of IO, it’s likely that sooner rather than later you’ll encounter a scenario where laziness and performance are significant concerns for how you structure your program.
In this section, we’ll look in more detail at how IO actions are evaluated in Haskell applications, and what that means for the stability and performance of your programs. You’ll also get some hands-on experience working with lazy IO, and some of the bugs that can arise when laziness and IO interact in unexpected ways.
When we have a basic IO action, like we might get from the getArgs function we’ve been working with, it’s tempting to think like we’re working with a strictly evaluated language and say that the function performs some IO and returns a value. In the cases that we’ve seen so far that intuition even appears to hold. In reality, this view of IO in Haskell is slightly incorrect and if we don’t work to counter our first intuition we can introduce subtle bugs in our program. Having a better understanding of IO will also make it easier to fully understand the way IO is working as we continue through this chapter.
Let’s begin by taking a look back at some examples of how laziness works in Haskell, and in particular what that means for IO actions in general. After that we’ll look at some real-world examples of the interaction betwen laziness and IO, and you’ll learn how to avoid errors introduced when IO actions are too lazy.
Haskell expressions have a type that’s evaluated by the compiler when we’re building the program, and it has a value that will be computed by the running program when it’s needed. This is different from strict languages where the value of an expression is calculated as soon as the expression is encountered or assigned to a variable. Remember from Chapter 1, Getting Started with Haskell when we used this example:
| | ignoreUnevaluated :: Int |
| | ignoreUnevaluated = |
| | let infinity = sum [1..] in 12 |
We were able to create a the variable infinity and assign it to a computation that would never finish, but we could still run the function. It turns out we can do exactly the same thing with IO actions:
| | ignoreUnevaluatedIO :: IO () |
| | ignoreUnevaluatedIO = |
| | let screamIntoTheVoid = putStrLn "quack" |
| | in return () |
If you try running ignoreUnevaluatedIO you’ll notice that you don’t get any output. Since we’re never looking at the value of screamIntoTheVoid it never gets computed, never becomes part of the history of the real world that we’re returning, and never outputs anything to the screen.
It’s not only the entire IO a that can go unevaluated. The side effects captured in the IO action are evaluated separately from the value associated with the IO action. Sometimes that value isn’t even evaluated at all. Let’s look at another example to highlight how this works:
| | lazyIODemo :: IO () |
| | lazyIODemo = |
| | let sayHello :: IO () |
| | sayHello = putStrLn "Hello" |
| | raiseAMathError :: IO Int |
| | raiseAMathError = putStrLn "I'm part of raiseAMathError" |
| | >> return (1 `div` 0) |
| | in sayHello |
| | >> raiseAMathError |
| | >> sayHello |
In this example, we’re creating two IO actions, sayHello and raiseAMathError . We use >> to sequence them into a single new IO action. The IO action that we’ve named raiseAMathError is interesting. The IO portion is nothing unusual, but the value we’re associating with it is an uncomputable value of type Int . If we actually try to evaluate the expression 1 ‘div‘ 0 we would get a runtime exception caused by our attempt to divide by zero. Since we use (>>) we disregard the value inside of the IO action, and so we never need to actually calculate it. That means the error is never raised. The end result is that raiseAMathError is an IO action that has perfectly normal every day side effects and also a unevaluated expression for an uncomputable value.
If you run lazyIODemo you might be surprised to find that there’s no exception raised at all even though the side effects of raiseAMathError are evaluated and the message is printed to the screen. This is because >> and >>= require that any previous IO actions are evaluated before the current one. This makes intuitive sense if you think about how we can’t read the contents of a file before we open it. Less intuitively is that the >> and >>= functions don’t force the evaluation of the value contained in the IO action. If you think about reading a very large file from disk, this starts to make a little bit more sense. While we want to make sure that the file exists and that we can open it, it is reasonable to make sure we really need the contents of the file before we actually do the work of reading it. After all, why should we read the whole file if we only need to use the first few characters.
| Understanding Laziness |
|---|
|
| It can be hard to understand exactly when and how values are evaluated in Haskell. If you’re finding these examples a little challenging to follow, consider bookmarking this section and revisiting it after you’ve finished the chapter on mutable data where you’ll learn about how Haskell expressions are evaluated in much more detail. |
Next let’s look at an example of a program that might unexpectedly crash, and see how better understanding IO actions and lazy evaluation can help us rewrite this program so it no longer crashes. We’ll start by creating a simple program that will create 500 files in /tmp/test/ , creatively named with the numbers 1 through 500, whose contents will be the file names. The important parts here are that we have a lot of files, and they have some data in them that we want to read. Our program will create the files, then read them and write their contents to the screen. We’re using readFile and writeFile , which are both provided by System.IO as part of the standard library, and as you might guess they read and write a file. We’re also using mapM , which is a function we’ll talk more about later in this chapter. For now, just know that it works a lot like a special version of map that we can use for our IO actions. Instead of getting [IO a] like we would with a regular map, mapM gives us IO [a] , so instead of getting many small IO actions containing a single value, we get one big IO action and all of the values. In this example, we’ll include a few extra type annotations that would normally be unnecessary, but they’ll help you make sense of what’s going on as you are learning about IO .
| | makeAndReadFile :: Int -> IO String |
| | makeAndReadFile fnumber = |
| | let fname = "/tmp/test/" <> show fnumber |
| | in writeFile fname fname >> readFile fname |
| | |
| | unsafe :: IO () |
| | unsafe = |
| | let files = mapM makeAndReadFile [1..50000] :: IO [ String ] |
| | in files >>= (putStrLn . show) |
If you try to run this function, you are likely to get an error that looks something like this:
| | *** Exception: getCurrentDirectory:getWorkingDirectory: |
| | resource exhausted (Too many open files) |
The exact behavior of this example will depend on your system. You may be able to reproduce the error with fewer files, or you might need more. On some systems you might not be able to reproduce the error at all. The important part of this example is demonstrating that what should have been a straightforward program crashed unexpectedly. Isn’t that exactly what Haskell is supposed to prevent?
This unexpected bug is caused because we didn’t account for the way that lazy IO works in Haskell. When we call readFile we’re not actually going out to the real world and reading the file at all; instead, we’re creating an unevaluated expression that represents the contents of the file, and associating them with a state in the real world where the file has been opened. None of the actual work has been done yet. When we bind files to our expression putStrLn . show we suddenly need to evaluate all of our strings, which means we need to actually do the work of trying to open all of our files at once. Since readFile doesn’t close the file handle until the contents of the file have been read, and we’re now trying to open all of the files before we print them out, we end up opening more files than the system will allow and crashing.
So what can we do about this? We are running out of file handles because we are trying to open all of the files at once before we print anything out. If we refactor our code so that each IO action both gets the file data and writes it to the screen, then we can close the file before we move on to the next IO action. We’ll start by creating a helper function, makeAndShow , that gets the file contents and writes it to the screen:
| | makeAndShow :: Int -> IO () |
| | makeAndShow n = |
| | makeAndReadFile n >>= putStrLn |
You might at first think about making a very simple modification to our unsafe function to use this new function:
| | safe :: IO () |
| | safe = |
| | mapM makeAndShow [1..500] |
If you try to build that, you’ll realize it doesn’t quite work, because mapM wants to give us a list of values. Since all of our values are just () there’s not much sense in that. We could change the type of our function to IO [()] but that’s a bit of a code smell. Let’s see if we can do better. We know that >> lets us sequence IO actions without caring about the value, and we can use foldl to reduce a list of values. We can put those two ideas together to reduce a list down to a single IO action:
| | safe :: IO () |
| | safe = |
| | foldl ( \ io id -> |
| | io >> makeAndShow id |
| | ) (return ()) [1..500] |
We start our fold with an empty IO action containing an initial value of () . Then we reduce our list with >> , each time sequencing the previous IO action with the current one, and discarding the results. In the end, we’re left with a single IO action.
This pattern turns out to be a very common one, and there’s a built-in function for it, called mapM_ . We can use it to implement the final version of our function:
| | safe :: IO () |
| | safe = mapM_ makeAndShow [1..500] |
Lazy IO, especially lazy file IO, is a common source of errors in Haskell applications. Once you understand how IO works, and the impact of laziness, you can proactively design your applications to avoid many of the common pitfalls.