In this chapter, you’re going to learn how to receive input from the keyboard and print stuff to the screen.

But first, we’ll cover the basics of input and output (I/O):

  • What are I/O actions?

  • How do I/O actions enable us to do I/O?

  • When are I/O actions actually performed?

Dealing with I/O brings up the issue of constraints on how Haskell functions can work, so we’ll look at how we get around that first.

Separating the Pure from the Impure

By now, you’re used to the fact that Haskell is a purely functional language. Instead of giving the computer a series of steps to execute, you give it definitions of what certain things are. In addition, a function isn’t allowed to have side effects . A function can give us back only some result based on the parameters we supplied to it. If a function is called two times with the same parameters, it must return the same result.

While this may seem a bit limiting at first, it’s actually really cool. In an imperative language, you have no guarantee that a simple function that should just crunch some numbers won’t burn down your house or kidnap your dog while crunching those numbers. For instance, when we were making a binary search tree in the previous chapter, we didn’t insert an element into a tree by modifying the tree itself; instead, our function actually returned a new tree with the new element inserted into that.

image with no caption

The fact that functions cannot change state—like updating global variables, for example—is good, because it helps us reason about our programs. However, there’s one problem with this: If a function can’t change anything in the world, how is it supposed to tell us what it calculated? To do that, it must change the state of an output device (usually the state of the screen), which then emits photons that travel to our brain, which changes the state of our mind, man.

But don’t despair, all is not lost. Haskell has a really clever system for dealing with functions that have side effects. It neatly separates the part of our program that is pure and the part of our program that is impure, which does all the dirty work like talking to the keyboard and the screen. With those two parts separated, we can still reason about our pure program and take advantage of all the things that purity offers—like laziness, robustness, and composability—while easily communicating with the outside world. You’ll see this at work in this chapter.

Hello, World!

Until now, we’ve always loaded our functions into GHCi to test them. We’ve also explored the standard library functions in that way. Now we’re finally going to write our first real Haskell program! Yay! And sure enough, we’re going to do the good old Hello, world! schtick.

image with no caption

For starters, punch the following into your favorite text editor:

main = putStrLn "hello, world"

We just defined main , and in it we call a function called putStrLn with the parameter "hello, world" . Save that file as helloworld.hs .

We’re going to do something we’ve never done before: compile our program, so that we get an executable file that we can run! Open your terminal, navigate to the directory where helloworld.hs is located, and enter the following:

$ ghc --make helloworld

This invokes the GHC compiler and tells it to compile our program. It should report something like this:

[1 of 1] Compiling Main ( helloworld.hs, helloworld.o )
Linking helloworld ...

Now you can run your program by entering the following at the terminal:

$ ./helloworld

Note

If you’re using Windows, instead of doing ./helloworld , just type in helloworld.exe to run your program.

Our program prints out the following:

hello, world

And there you go—our first compiled program that prints something to the terminal. How extraordinarily boring!

Let’s examine what we wrote. First, let’s look at the type of the function putStrLn :

ghci> :t putStrLn
putStrLn :: String -> IO ()
ghci> :t putStrLn "hello, world"
putStrLn "hello, world" :: IO ()

We can read the type of putStrLn like this: putStrLn takes a string and returns an I/O action that has a result type of () (that is, the empty tuple, also known as unit ).

An I/O action is something that, when performed, will carry out an action with a side effect (such as reading input or printing stuff to the screen or a file) and will also present some result. We say that an I/O action yields this result. Printing a string to the terminal doesn’t really have any kind of meaningful return value, so a dummy value of () is used.

Note

The empty tuple is the value (), and it also has a type of ().

So when will an I/O action be performed? Well, this is where main comes in. An I/O action will be performed when we give it a name of main and then run our program.

Gluing I/O Actions Together

Having your whole program be just one I/O action seems kind of limiting. That’s why we can use do syntax to glue together several I/O actions into one. Take a look at the following example:

main = do
    putStrLn "Hello, what's your name?"
    name <- getLine
    putStrLn ("Hey " ++ name ++ ", you rock!")

Ah, interesting—new syntax! And this reads pretty much like an imperative program. If you compile and run it, it will behave just as you expect.

Notice that we said do and then we laid out a series of steps, as we would in an imperative program. Each of these steps is an I/O action. By putting them together with do syntax, we glued them into one I/O action. The action that we got has a type of IO () , as that’s the type of the last I/O action inside. Because of that, main always has a type signature of main :: IO something , where something is some concrete type. We don’t usually specify a type declaration for main .

How about that third line, which states name <- getLine ? It looks like it reads a line from the input and stores it into a variable called name . Does it really? Well, let’s examine the type of getLine .

ghci> :t getLine
getLine :: IO String

image with no caption

We see that getLine is an I/O action that yields a String . That makes sense, because it will wait for the user to input something at the terminal, and then that something will be represented as a string.

So what’s up with name <- getLine then? You can read that piece of code like this: perform the I/O action getLine , and then bind its result value to name . getLine has a type of IO String , so name will have a type of String .

You can think of an I/O action as a box with little feet that will go out into the real world and do something there (like write some graffiti on a wall) and maybe bring back some data. Once it has fetched that data for you, the only way to open the box and get the data inside it is to use the <- construct. And if we’re taking data out of an I/O action, we can take it out only when we’re inside another I/O action. This is how Haskell manages to neatly separate the pure and impure parts of our code. getLine is impure, because its result value is not guaranteed to be the same when performed twice.

When we do name <- getLine , name is just a normal string, because it represents what’s inside the box. For example, we can have a really complicated function that takes your name (a normal string) as a parameter and tells you your fortune based on your name, like this:

main = do
    putStrLn "Hello, what's your name?"
    name <- getLine
    putStrLn $ "Zis is your future: " ++ tellFortune name

The tellFortune function (or any of the functions it passes name to) does not need to know anything about I/O—it’s just a normal String -> String function!

To see how normal values differ from I/O actions, consider the following line. Is it valid?

nameTag = "Hello, my name is " ++ getLine

If you said no, go eat a cookie. If you said yes, drink a bowl of molten lava. (Just kidding—don’t!) This doesn’t work because ++ requires both its parameters to be lists over the same type. The left parameter has a type of String (or [Char] , if you will), while getLine has a type of IO String . Remember that you can’t concatenate a string and an I/O action. First, you need to get the result out of the I/O action to get a value of type String , and the only way to do that is to do something like name <- getLine inside some other I/O action.

If we want to deal with impure data, we must do it in an impure environment. The taint of impurity spreads around much like the undead scourge, and it’s in our best interest to keep the I/O parts of our code as small as possible.

Every I/O action that is performed yields a result. That’s why our previous example could also have been written like this:

main = do
    foo <- putStrLn "Hello, what's your name?"
    name <- getLine
    putStrLn ("Hey " ++ name ++ ", you rock!")

However, foo would just have a value of () , so doing that would be kind of moot. Notice that we didn’t bind the last putStrLn to anything. That’s because in a do block, the last action cannot be bound to a name as the first two were. You’ll see exactly why that is so when we venture off into the world of monads, starting in Chapter 13 . For now, the important point is that the do block automatically extracts the value from the last action and yields that as its own result.

Except for the last line, every line in a do block that doesn’t bind can also be written with a bind. So putStrLn "BLAH" can be written as _ <- putStrLn "BLAH" . But that’s useless, so we leave out the <- for I/O actions that don’t yield an important result, like putStrLn .

What do you think will happen when we do something like the following?

myLine = getLine

Do you think it will read from the input and then bind the value of that to name ? Well, it won’t. All this does is give the getLine I/O action a different name called myLine . Remember that to get the value out of an I/O action, you must perform it inside another I/O action by binding it to a name with <- .

I/O actions will be performed when they are given a name of main or when they’re inside a bigger I/O action that we composed with a do block. We can also use a do block to glue together a few I/O actions, and then we can use that I/O action in another do block, and so on. They will be performed if they eventually fall into main .

There’s also one more case when I/O actions will be performed: when we type out an I/O action in GHCi and press enter .

ghci> putStrLn "HEEY"
HEEY

Even when we just punch in a number or call a function in GHCi and press enter , GHCi will apply show to the resulting value, and then it will print it to the terminal by using putStrLn .

Using let Inside I/O Actions

When using do syntax to glue together I/O actions, we can use let syntax to bind pure values to names. Whereas <- is used to perform I/O actions and bind their results to names, let is used when we just want to give names to normal values inside I/O actions. It’s similar to the let syntax in list comprehensions.

Let’s take a look at an I/O action that uses both <- and let to bind names.

import Data.Char

main = do
    putStrLn "What's your first name?"
    firstName <- getLine
    putStrLn "What's your last name?"
    lastName <- getLine
    let bigFirstName = map toUpper firstName
        bigLastName = map toUpper lastName
    putStrLn $ "hey " ++ bigFirstName ++ " "
                      ++ bigLastName
                      ++ ", how are you?"

See how the I/O actions in the do block are lined up? Also notice how the let is lined up with the I/O actions, and the names of the let are lined up with each other? That’s good practice, because indentation is important in Haskell.

We wrote map toUpper firstName , which turns something like "John" into a much cooler string like "JOHN" . We bound that uppercased string to a name and then used it in a string that we printed to the terminal.

You may be wondering when to use <- and when to use let bindings. <- is for performing I/O actions and binding their results to names. map toUpper firstName , however, isn’t an I/O action—it’s a pure expression in Haskell. So you can use <- when you want to bind the results of I/O actions to names, and you can use let bindings to bind pure expressions to names. Had we done something like let firstName = getLine , we would have just called the getLine I/O action a different name, and we would still need to run it through a <- to perform it and bind its result.

Putting It in Reverse

To get a better feel for doing I/O in Haskell, let’s make a simple program that continuously reads a line and prints out the same line with the words reversed. The program’s execution will stop when we input a blank line. This is the program:

main = do
    line <- getLine
    if null line
        then return ()
        else do
            putStrLn $ reverseWords line
            main

reverseWords :: String -> String
reverseWords = unwords . map reverse . words

To get a feel for what it does, save it as reverse.hs , and then compile and run it:

$ ghc --make reverse.hs
[1 of 1] Compiling Main             ( reverse.hs, reverse.o )
Linking reverse ...
$ ./reverse
clean up on aisle number nine
naelc pu no elsia rebmun enin
the goat of error shines a light upon your life
eht taog fo rorre senihs a thgil nopu ruoy efil
it was all a dream
ti saw lla a maerd

Our reverseWords function is just a normal function. It takes a string like "hey there man" and applies words to it to produce a list of words like ["hey","there","man"] . We map reverse over the list, getting ["yeh","ereht","nam"] , and then we put that back into one string by using unwords . The final result is "yeh ereht nam" .

What about main ? First, we get a line from the terminal by performing getLine and call that line line . Next we have a conditional expression. Remember that in Haskell, every if must have a corresponding else , because every expression must have some sort of value. Our if says that when a condition is true (in our case, the line that we entered is blank), we perform one I/O action; when it isn’t true, the I/O action under the else is performed.

Because we need to have exactly one I/O action after the else , we use a do block to glue together two I/O actions into one. We could also write that part as follows:

else (do
    putStrLn $ reverseWords line
    main)

This makes it clearer that the do block can be viewed as one I/O action, but it’s uglier.

Inside the do block, we apply reverseWords to the line that we got from getLine and then print that to the terminal. After that, we just perform main . It’s performed recursively, and that’s okay, because main is itself an I/O action. So in a sense, we go back to the start of the program.

If null line is True , the code after the then is executed: return () . You might have used a return keyword in other languages to return from a subroutine or function. But return in Haskell is nothing like the return in most other languages.

In Haskell (and in I/O actions specifically), return makes an I/O action out of a pure value. Returning to the box analogy for I/O actions, return takes a value and wraps it up in a box. The resulting I/O action doesn’t actually do anything; it just yields that value as its result. So in an I/O context, return "haha" will have a type of IO String .

What’s the point of just transforming a pure value into an I/O action that doesn’t do anything? Well, we needed some I/O action to carry out in the case of an empty input line. That’s why we made a bogus I/O action that doesn’t do anything by writing return () .

Unlike in other languages, using return doesn’t cause the I/O do block to end in execution. For instance, this program will quite happily continue all the way to the last line:

main = do
    return ()
    return "HAHAHA"
    line <- getLine
    return "BLAH BLAH BLAH"
    return 4
    putStrLn line

Again, all these uses of return do is make I/O actions that yield a result, which is then thrown away because it isn’t bound to a name.

We can use return in combination with <- to bind stuff to names:

main = do
    a <- return "hell"
    b <- return "yeah!"
    putStrLn $ a ++ " " ++ b

So you see, return is sort of the opposite of <- . While return takes a value and wraps it up in a box, <- takes a box (and performs it) and takes the value out of it, binding it to a name. But doing this is kind of redundant, especially since you can use let in do blocks to bind to names, like so:

main = do
    let a = "hell"
        b = "yeah"
    putStrLn $ a ++ " " ++ b

When dealing with I/O do blocks, we mostly use return either because we need to create an I/O action that doesn’t do anything or because we don’t want the I/O action that’s made up from a do block to have the result value of its last action. When we want it to have a different result value, we use return to make an I/O action that always yields our desired result, and we put it at the end.

Some Useful I/O Functions

Haskell comes with a bunch of useful functions and I/O actions. Let’s take a look at some of them to see how they’re used.

putStr

putStr is much like putStrLn , in that it takes a string as a parameter and returns an I/O action that will print that string to the terminal. However, putStr doesn’t jump into a new line after printing out the string, whereas putStrLn does. For example, look at this code:

main = do
    putStr "Hey, "
    putStr "I'm "
    putStrLn "Andy!"

If we compile and run this, we get the following output:

Hey, I'm Andy!

putChar

The putChar function takes a character and returns an I/O action that will print it to the terminal:

main = do
    putChar 't'
    putChar 'e'
    putChar 'h'

putStr can be defined recursively with the help of putChar . The base case of putStr is the empty string, so if we’re printing an empty string, we just return an I/O action that does nothing by using return () . If it’s not empty, then we print the first character of the string by doing putChar and then print the rest of them recursively:

putStr :: String -> IO ()
putStr [] = return ()
putStr (x:xs) = do
    putChar x
    putStr xs

Notice how we can use recursion in I/O, just as we can use it in pure code. We define the base case and then think what the result actually is. In this case, it’s an action that first outputs the first character and then outputs the rest of the string.

print

print takes a value of any type that’s an instance of Show (meaning that we know how to represent it as a string), applies show to that value to “stringify” it, and then outputs that string to the terminal. Basically, it’s just putStrLn . show . It first runs show on a value, and then feeds that to putStrLn , which returns an I/O action that will print out our value.

main = do
    print True
    print 2
    print "haha"
    print 3.2
    print [3,4,3]

Compiling this and running it, we get the following output:

True
2
"haha"
3.2
[3,4,3]

As you can see, it’s a very handy function. Remember how we talked about how I/O actions are performed only when they fall into main or when we try to evaluate them at the GHCi prompt? When we type out a value (like 3 or [1,2,3] ) and press enter , GHCi actually uses print on that value to display it on the terminal!

ghci> 3
3
ghci> print 3
3
ghci> map (++"!") ["hey","ho","woo"]
["hey!","ho!","woo!"]
ghci> print $ map (++"!") ["hey","ho","woo"]
["hey!","ho!","woo!"]

When we want to print out strings, we usually use putStrLn because we don’t want the quotes around them. However, for printing out values of other types to the terminal, print is used the most often.

when

The when function is found in Control.Monad (to access it, use import Control.Monad ). It’s interesting because in a do block, it looks like a flow-control statement, but it’s actually a normal function.

when takes a Bool and an I/O action, and if that Bool value is True , it returns the same I/O action that we supplied to it. However, if it’s False , it returns the return () action, which doesn’t do anything.

Here’s a small program that asks for some input and prints it back to the terminal, but only if that input is SWORDFISH :

import Control.Monad

main = do
    input <- getLine
    when (input == "SWORDFISH") $ do
        putStrLn input

Without when , we would need to write the program like this:

main = do
    input <- getLine
    if (input == "SWORDFISH")
        then putStrLn input
        else return ()

As you can see, the when function is useful when we want to perform some I/O actions when a condition is met, but do nothing otherwise.

sequence

The sequence function takes a list of I/O actions and returns an I/O action that will perform those actions one after the other. The result that this I/O action yields will be a list of the results of all the I/O actions that were performed. For instance, we could do this:

main = do
    a <- getLine
    b <- getLine
    c <- getLine
    print [a,b,c]

Or we could do this:

main = do
    rs <- sequence [getLine, getLine, getLine]
    print rs

The results of both these versions are exactly the same. sequence [getLine, getLine, getLine] makes an I/O action that will perform getLine three times. If we bind that action to a name, the result is a list of all the results. So in this case, the result would be a list of three things that the user entered at the prompt.

A common pattern with sequence is when we map functions like print or putStrLn over lists. Executing map print [1,2,3,4] won’t create an I/O action, but instead will create a list of I/O actions. Effectively, this is the same as writing this:

[print 1, print 2, print 3, print 4]

If we want to transform that list of I/O actions into an I/O action, we must sequence it:

ghci> sequence $ map print [1,2,3,4,5]
1
2
3
4
5
[(),(),(),(),()]

But what’s with the [(),(),(),(),()] at the end of the output? Well, when we evaluate an I/O action in GHCi, that action is performed, and then its result is printed out, unless that result is () . That’s why evaluating putStrLn "hehe" in GHCi just prints out hehe — putStrLn "hehe" yields () . But when we enter getLine in GHCi, the result of that I/O action is printed out, because getLine has a type of IO String .

mapM

Because mapping a function that returns an I/O action over a list and then sequencing it is so common, the utility functions mapM and mapM_ were introduced. mapM takes a function and a list, maps the function over the list, and then sequences it. mapM_ does the same thing, but it throws away the result later. We usually use mapM_ when we don’t care what result our sequenced I/O actions have. Here’s an example of mapM :

ghci> mapM print [1,2,3]
1
2
3
[(),(),()]

But we don’t care about the list of three units at the end, so it’s better to use this form:

ghci> mapM_ print [1,2,3]
1
2
3

forever

The forever function takes an I/O action and returns an I/O action that just repeats the I/O action it got forever. It’s located in Control.Monad . The following little program will indefinitely ask the user for some input and spit it back in all uppercase characters:

import Control.Monad
import Data.Char

main = forever $ do
    putStr "Give me some input: "
    l <- getLine
    putStrLn $ map toUpper l

forM

forM (located in Control.Monad ) is like mapM , but its parameters are switched around. The first parameter is the list, and the second is the function to map over that list, which is then sequenced. Why is that useful? Well, with some creative use of lambdas and do notation, we can do stuff like this:

import Control.Monad

main = do
    colors <- forM [1,2,3,4] (\a -> do
        putStrLn $ "Which color do you associate with the number "
                   ++ show a ++ "?"
        color <- getLine
        return color)
    putStrLn "The colors that you associate with 1, 2, 3 and 4 are: "
    mapM putStrLn colors

Here’s what we get when we try this out:

Which color do you associate with the number 1?
white
Which color do you associate with the number 2?
blue
Which color do you associate with the number 3?
red
Which color do you associate with the number 4?
orange
The colors that you associate with 1, 2, 3 and 4 are:
white
blue
red
orange

The (\a -> do ... ) lambda is a function that takes a number and returns an I/O action. Notice that we call return color in the inside do block. We do that so that the I/O action that the do block defines yields the string that represents our color of choice. We actually did not have to do that though, since getLine already yields our chosen color, and it’s the last line in the do block. Doing color <- getLine and then return color is just unpacking the result from getLine and then repacking it—it’s the same as just calling getLine .

The forM function (called with its two parameters) produces an I/O action, whose result we bind to colors . colors is just a normal list that holds strings. At the end, we print out all those colors by calling mapM putStrLn colors .

You can think of forM as saying, “Make an I/O action for every element in this list. What each I/O action will do can depend on the element that was used to make the action. Finally, perform those actions and bind their results to something.” (Although we don’t need to bind it; we could also just throw it away.)

We could have actually achieved the same result without forM , but using forM makes the code more readable. Normally, we use forM when we want to map and sequence some actions that we define on the spot using do notation.

I/O Action Review

Let’s run through a quick review of the I/O basics. I/O actions are values much like any other value in Haskell. We can pass them as parameters to functions, and functions can return I/O actions as results.

What’s special about I/O actions is that if they fall into the main function (or are the result in a GHCi line), they are performed. And that’s when they get to write stuff on your screen or play “Yakety Sax” through your speakers. Each I/O action can also yield a result to tell you what it got from the real world.