Haskell’s approach to IO is different from other languages you might have worked with because, as a pure and lazily evaluated language, it has some constraints that don’t exist in other languages. Understanding the challenges that come with doing IO in a pure and lazy language is the first step to understanding how to do IO in Haskell. In this section, you’ll first learn about how purity and laziness present challenges to doing IO. After that, you’ll learn about IO and IO actions and how they address the challenges introduced by purity and laziness.

Understanding the Problems with IO

Laziness and purity are interesting and useful properties of Haskell, but they make IO particularly tricky. You learned about purity and laziness back in Chapter 1, ​ Getting Started with Haskell ​ , but at the time we didn’t take the time to look more deeply at why they made IO challenging. Now that you’re learning about IO, it’s going to be helpful to think about the challenges that come about with pure lazy IO.

When we can’t interact with anything except our input values, or affect anything except our output values, then reading or writing data from the world outside of our program is going to present a challenge. Even if we were to cheat just a little bit and say that we’ll allow a impurity just for the sake of letting us do IO, we still have the problem of laziness. Since laziness requires that we always use the result of some work before the work is actually done, there’s a lot of IO that might never get executed, or might not get executed in the order that we’d expect.

Haskell’s combination of laziness and purity present an interesting challenge for managing IO. In fact, early versions of Haskell used an entirely different approach to solving the problem of how to do IO. The solution that you’ll learn about throughout the rest of this chapter has been part of Haskell since Haskell 98. [12] The first time you see how IO is handled in Haskell programs it can seem a bit complex, but as you work through the next few chapters you’ll start to learn how IO works and it will eventually feel quite natural.

Keeping IO Pure

The IO type is how we keep track of the state of the real world in a Haskell program. Understanding how IO works is an important insight that will help you work with Haskell more effectively even when you aren’t actually doing IO.

Haskell being a pure language means we can’t just change the value of things, and that includes changing the external environment. Instead of changing the value of the external environment in place, we need to keep track of all the changes we wanted to make. The changes that IO is keeping track of have a special name: side effects . A side effect is anything that happens outside of the function. For example, writing a file might return the number of bytes written, but it has the side effect of changing the contents of the file on disk. Even things like reading a file or looking at an environment variable have side effects, because they rely on information outside of the function.

Generally you won’t see IO used by itself. Instead, it’s common to pair the side effects with the value they were used to calculate. For example, if we wanted to read the contents of a file as a string we would represent that as IO String . The IO keeps track of the fact that the file is open and has been read, and the String has the actual value of the data. We call values like this IO Actions . Most of the time when we want to refer to any sort of IO action we’ll use a type variable and write it IO a .

The way that IO keeps track of this is an implementation detail that we won’t dive into in this book, but throughout this chapter you’ll learn enough about IO to build a good intuition for how to use it effectively.

Keeping IO Lazy

Laziness can present some unique challenges for working with IO when we want to do more than one IO Action. If you remember from back in Chapter 1, ​ Getting Started with Haskell ​ when we first introduced laziness, you learned about how Haskell expressions are only computed when the value is needed. This can make doing IO tricky because it means we need to be careful about using the values from our IO actions to ensure that the computations are actually carried out in the order we expect.

Let’s look at an example. Say that we wanted to write a program that writes the string “Hello, Haskell” to /tmp/hello , then it reads the contents of /tmp/hello and prints that to the screen. In a lot of languages we could write something like:

​  writeReadFile =
​  writeFile ​ "Hello, Haskell" ​ ​ "/tmp/hello" ​
​  ​ let ​ contents = readFile ​ "/tmp/hello" ​
​  print contents

Ignoring the incorrect syntax for a moment, we have a basic problem with writing code like this. Since we never look at the result of writeFile there’s no way to be sure it would be called before readFile , so we could print whatever data happened to be in the file when we started our program—or even worse, our program might crash because the file didn’t already exist.

We can get around the problem of not knowing what order our IO operations will run in if we ensure that the returned value of an IO action is used. To do that, we have to make computing the value of an IO action necessary to run the next IO action. To do that, we need to do two things: we need a way to combine IO actions, and a way to sequence them.

Combining IO actions lets us build up a single IO action from smaller pieces. If we wanted to copy a file, for example, we would want to perform two separate IO actions: reading the contents of the source file, and writing that to the destination file. Combining IO actions lets us represent those as a single larger IO action.

When we combine our IO actions, it’s important that we keep in mind that we care about the order in which we combine our IO actions. Sometimes, when we’re adding or multiplying numbers for example, we don’t care which order we do things in. If we compute a + b we’ll always get the same thing as b + a for any numbers we care to choose for a and b . We call functions like (+) where we can provide the arguments in any order commutative . Other times, joining strings for instance, we do care about the order. The string "hello, " <> "world" is going to be quite different from "world" <> "hello, " . Combining IO actions isn’t commutative. When we copy a file, like in our earlier example, it matters quite a lot that we read the contents of the source file before we write the contents to our destination file.

So how do we go about doing this combining and sequencing of our IO actions?

Let’s start by writing a function that needs to sequence some IO actions, with a comment representing the part we need to fill in. For this example, we’ll use a simple file copy function that reads data from an input file and writes it to an output file:

​  copyFile :: ​ FilePath ​ -> ​ FilePath ​ -> ​ IO ​ ()
​  copyFile src dst =
​  (readFile src) ​ {- interesting stuff here -} ​ (writeFile dst)

In this example, we’re reading the contents of our file with readFile , and we’re trying to write something with writeFile , but there’s clearly an interesting middle bit that we’re missing.

We can get an idea of what needs to go in the middle of our function by looking at the types of the functions we do know about. In this case, we have this:

  • readFile :: FilePath -> IO String
  • writeFile :: String -> IO ()

We can also use a type hole to help us figure out what should go into our missing part of the code:

​  copyFile :: ​ FilePath ​ -> ​ FilePath ​ -> ​ IO ​ ()
​  copyFile src dst =
​  (readFile src) `​ _ ​` (writeFile dst)

The compiler gives us a lot more detail than we might want from this particular type hole, but the most relevant bit tells us what we might have expected from the types of readFile and writeFile :

​  • Found hole: _ :: IO String -> (String -> IO ()) -> IO ()

We might not know how to write our missing function, but at least now we know what its type signature should be. We’ll need to come up with a name for our function too, so that we can write it. Since we want to use this function to provide sequential ordering to our IO actions, let’s call it andThen . After all, it makes a certain intuitive sense to read the code and say “read the source file contents andThen write the destination file contents.”

We could start by making a function with exactly the type that our read and write functions use, and the type hole suggested:

​  andThen :: ​ IO ​ ​ String ​ -> (​ String ​ -> ​ IO ​ ()) -> ​ IO ​ ()

This is a little bit too restrictive though. As you might have guessed, this general problem of making sure we can do one IO action and then another comes up frequently, so we’ll pick a more general type for our function:

​  andThen :: ​ IO ​ a -> (a -> ​ IO ​ b) -> ​ IO ​ b
​  andThen = undefined

You’ll learn how to implement andThen yourself in ​ Ordering and Combining IO Actions ​ , but for now let’s leave it undefined so that we can focus on what we can learn from the types. Learning how to reason about the behavior of a function based on its type signature is a very useful skill when you’re working with Haskell.

Our type signature can tell us a lot about how our function needs to behave. The first thing we can understand about it comes from looking at its return type, IO b . The fact that it’s an IO action tells us that we’re doing something that involves side effects, even if we don’t know for sure yet what those side effects are. Even more enlightening is the fact that we’re returning an IO b .

Returning a type variable in a Haskell function tells us a lot about the structure of our function. Because b could be any sort of value, our function can’t actually make one directly. We can only create an output value of type b if we were passed in a b or a function returning a b .

If you think about a function that returns an Int , we might not necessarily have to depend on any input in particular to return one. We could always just return 5 or 42 or 197 no matter what input we were given. To return a b though, what should we return? There’s no way our function can actually decide.

Being unable to create a b directly takes us to our second parameter, a function a -> IO b . We can’t create an a any more than we could create a b , but now we know that if we do have an a we could create an IO b from it. Luckily for us, the first parameter of our function is an IO action, IO a .

So we must return an IO b , but the only way for our function to possibly create one of those is by passing the a from our IO a into the function a -> IO b . Somehow we need to separate out the value from an IO action and pass it to a function that generates a new IO action, and then return an IO action with the value we got back from the function call.

What does this have to do with sequencing? As long as the value of b depends on the value of a , we have to actually compute a first. Since our a is part of an IO action, all of the side effects that go along with a are going to be computed before we can use it to generate our IO b . This dependency ensures that our IO actions have to happen in the right sequence.

If our andThen function provides a way for us to sequence IO operations by forcing values to depend on one another, what about combining them? It turns out that the nature of IO means that we don’t actually have to do much to combine the values at all, instead we can rely on the language runtime, operating system, and hardware hosting our program. In other word, side effects are things that happen on the system in the real world. They are combined implicitly by virtue of being part of a program that is running on that system.

So, with our andThen function providing both a way to ensure our IO actions happen in the right order, and trusting that they are combined the way that we would expect, let’s use it in our copy function:

​  copyFile :: ​ FilePath ​ -> ​ FilePath ​ -> ​ IO ​ ()
​  copyFile src dst =
​  (readFile src) `andThen` (writeFile dst)

We can even string together many different actions into a much longer statement. Imagine that instead of using readFile and writeFile we wanted to be more explicit about how we were doing our file operations:

​  longCopy :: ​ FilePath ​ -> ​ FilePath ​ -> ​ IO ​ ()
​  longCopy src dst =
​  openFile src ​ ReadMode ​ `andThen`
​  hGetContents `andThen`
​  ​ \ ​contents ->
​  openFile dst ​ WriteMode ​ `andThen`
​  flip hPutStr contents

You might find yourself wondering, if we can combine and order our IO actions, how we ever actually get a new IO action in the first place.

Let’s consider another example program. In this example, we’re going to write a program that might print the contents of a file to the screen, but if the path is /etc/passwd , we want to print out a special message:

​  noPassword :: ​ FilePath ​ -> ​ IO ​ ​ String ​
​  noPassword path =
​  ​ case ​ path ​ of ​
​  ​ "/etc/passwd" ​ -> newIO ​ "hey, that's a secret!" ​
​  fname -> readFile fname
​  
​  showFile path = noPassword path `andThen` putStrLn

In our example, if the user provides a valid filename we can use the IO action that we get out of readFile , but if they ask us for the contents of /etc/passwd we want to return the string “hey, that’s a secret!” The return type of our function is IO String , so we have to return our message as part of an IO action, even though in our special case we don’t actually have any side effects. To do that, we’ll need to introduce a new function, newIO . In our example program, newIO has the type newIO :: String -> IO String , but just like we did with andThen , we’ll want to make our version a bit more generic than that:

​  newIO :: a -> ​ IO ​ a
​  newIO = undefined

In the next section, we’ll talk about how IO works in real Haskell programs, and you’ll learn how to write your own version of newIO and andThen using the standard libraries that come with Haskell for doing IO.