Now that you understand the concepts behind Haskell’s I/O, we can start doing fun stuff with it. In this chapter, we’ll interact with files, make random numbers, deal with command-line arguments, and more. Stay tuned!

Files and Streams

Armed with the knowledge about how I/O actions work, we can move on to reading and writing files with Haskell. But first, let’s take a look at how we can use Haskell to easily process streams of data. A stream is a succession of pieces of data entering or exiting a program over time. For instance, when you’re inputting characters into a program via the keyboard, those characters can be thought of as a stream.

Input Redirection

Many interactive programs get the user’s input via the keyboard. However, it’s often more convenient to get the input by feeding the contents of a text file to the program. To achieve this, we use input redirection .

Input redirection will come in handy with our Haskell programs, so let’s take a look at how it works. To begin, create a text file that contains the following little haiku, and save it as haiku.txt :

I'm a lil' teapot
What's with that airplane food, huh?
It's so small, tasteless

Yeah, the haiku sucks—what of it? If anyone knows of any good haiku tutorials, let me know.

Now we’ll write a little program that continuously gets a line from the input and then prints it back in all uppercase:

import Control.Monad
import Data.Char

main = forever $ do
    l <- getLine
    putStrLn $ map toUpper l

Save this program as capslocker.hs and compile it.

Instead of inputting lines via the keyboard, we’ll have haiku.txt be the input by redirecting it into our program. To do that, we add a < character after our program name and then specify the file that we want to act as the input. Check it out:

$ ghc --make capslocker
[1 of 1] Compiling Main             ( capslocker.hs, capslocker.o )
Linking capslocker ...
$ ./capslocker < haiku.txt
I'M A LIL' TEAPOT
WHAT'S WITH THAT AIRPLANE FOOD, HUH?
IT'S SO SMALL, TASTELESS
capslocker <stdin>: hGetLine: end of file

What we’ve done is pretty much equivalent to running capslocker , typing our haiku at the terminal, and then issuing an end-of-file character (usually done by pressing ctrl -D). It’s like running capslocker and saying, “Wait, don’t read from the keyboard. Take the contents of this file instead!”

Getting Strings from Input Streams

Let’s take a look at an I/O action that makes processing input streams easier by allowing us to treat them as normal strings: getContents . getContents reads everything from the standard input until it encounters an end-of-file character. Its type is getContents :: IO String . What’s cool about getContents is that it does lazy I/O. This means that when we do foo <- getContents , getContents doesn’t read all of the input at once, store it in memory, and then bind it to foo . No, getContents is lazy! It will say, “Yeah yeah, I’ll read the input from the terminal later as we go along, when you really need it!”

In our capslocker.hs example, we used forever to read the input line by line and then print it back in uppercase. If we opt to use getContents , it takes care of the I/O details for us, such as when to read input and how much of that input to read. Because our program is about taking some input and transforming it into some output, we can make it shorter by using getContents :

import Data.Char

main = do
    contents <- getContents
    putStr $ map toUpper contents

We run the getContents I/O action and name the string it produces contents . Then we map toUpper over that string and print that result to the terminal. Keep in mind that because strings are basically lists, which are lazy, and getContents is I/O lazy; it won’t try to read all of the content at once and store that into memory before printing out the caps-locked version. Rather, it will print out the caps-locked version as it reads, because it will read a line from the input only when it must.

Let’s test it:

$ ./capslocker < haiku.txt
I'M A LIL' TEAPOT
WHAT'S WITH THAT AIRPLANE FOOD, HUH?
IT'S SO SMALL, TASTELESS

So, it works. What if we just run capslocker and try to type in the lines ourselves? (To exit the program, just press ctrl -D.)

$ ./capslocker
hey ho
HEY HO
lets go
LETS GO

Pretty nice! As you can see, it prints our caps-locked input line by line.

When the result of getContents is bound to contents , it’s not represented in memory as a real string, but more like a promise that the string will be produced eventually. When we map toUpper over contents , that’s also a promise to map that function over the eventual contents. Finally, when putStr happens, it says to the previous promise, “Hey, I need a caps-locked line!” It doesn’t have any lines yet, so it says to contents , “How about getting a line from the terminal?” And that’s when getContents actually reads from the terminal and gives a line to the code that asked it to produce something tangible. That code then maps toUpper over that line and gives it to putStr , which prints the line. And then putStr says, “Hey, I need the next line—come on!” This repeats until there’s no more input, which is signified by an end-of-file character.

Now let’s make a program that takes some input and prints out only those lines that are shorter than 10 characters:

main = do
    contents <- getContents
    putStr (shortLinesOnly contents)

shortLinesOnly :: String -> String
shortLinesOnly = unlines . filter (\line -> length line < 10) . lines

We’ve made the I/O part of our program as short as possible. Because our program is supposed to print something based on some input, we can implement it by reading the input contents, running a function on them, and then printing out what that function gives back.

The shortLinesOnly function takes a string, like "short\nlooooooong\nbort" . In this example, that string has three lines: two of them are short, and the middle one is long. It applies the lines function to that string, which converts it to ["short", "looooooong", "bort"] . That list of strings is then filtered so that only those lines that are shorter than 10 characters remain in the list, producing ["short", "bort"] . Finally, unlines joins that list into a single newline-delimited string, giving "short\nbort" .

Let’s give it a go. Save the following text as shortlines.txt .

i'm short
so am i
i am a loooooooooong line!!!
yeah i'm long so what hahahaha!!!!!!
short line
loooooooooooooooooooooooooooong
short

And now we’ll compile our program, which we saved as shortlinesonly.hs :

$ ghc --make shortlinesonly
[1 of 1] Compiling Main             ( shortlinesonly.hs, shortlinesonly.o )
Linking shortlinesonly ...

To test it, we’re going to redirect the contents of shortlines.txt into our program, as follows:

$ ./shortlinesonly < shortlines.txt
i'm short
so am i
short

You can see that only the short lines were printed to the terminal.

Transforming Input

The pattern of getting some string from the input, transforming it with a function, and outputting the result is so common that there is a function that makes that job even easier, called interact . interact takes a function of type String -> String as a parameter and returns an I/O action that will take some input, run that function on it, and then print out the function’s result. Let’s modify our program to use interact :

main = interact shortLinesOnly

shortLinesOnly :: String -> String
shortLinesOnly = unlines . filter (\line -> length line < 10) . lines

We can use this program either by redirecting a file into it or by running it and then giving it input from the keyboard, line by line. Its output is the same in both cases, but when we’re doing input via the keyboard, the output is interspersed with what we typed in, just as when we manually typed in our input to our capslocker program.

Let’s make a program that continuously reads a line and then outputs whether or not that line is a palindrome. We could just use getLine to read a line, tell the user if it’s a palindrome, and then run main all over again. But it’s simpler if we use interact . When using interact , think about what you need to do to transform some input into the desired output. In our case, we want to replace each line of the input with either "palindrome" or "not a palindrome" .

respondPalindromes :: String -> String
respondPalindromes =
    unlines .
    map (\xs -> if isPal xs then "palindrome" else "not a palindrome") .
    lines

isPal :: String -> Bool
isPal xs = xs == reverse xs

This program is pretty straightforward. First, it turns a string like this:

"elephant\nABCBA\nwhatever"

into an array like this:

["elephant", "ABCBA", "whatever"]

Then it maps the lambda over it, giving the results:

["not a palindrome", "palindrome", "not a palindrome"]

Next, unlines joins that list into a single, newline-delimited string. Now we just make a main I/O action:

main = interact respondPalindromes

Let’s test it:

$ ./palindromes
hehe
not a palindrome
ABCBA
palindrome
cookie
not a palindrome

Even though we created a program that transforms one big string of input into another, it acts as if we made a program that does it line by line. That’s because Haskell is lazy, and it wants to print the first line of the result string, but it can’t because it doesn’t have the first line of the input yet. So as soon as we give it the first line of input, it prints the first line of the output. We get out of the program by issuing an end-of-line character.

We can also use this program by just redirecting a file into it. Create the following file and save it as words.txt .

dogaroo
radar
rotor
madam

This is what we get by redirecting it into our program:

$ ./palindrome < words.txt
not a palindrome
palindrome
palindrome
palindrome

Again, we get the same output as if we had run our program and put in the words ourselves at the standard input. We just don’t see the input that our program gets because that input came from the file.

So now you see how lazy I/O works and how we can use it to our advantage. You can just think in terms of what the output is supposed to be for some given input and write a function to do that transformation. In lazy I/O, nothing is eaten from the input until it absolutely must be, because what we want to print right now depends on that input.

Reading and Writing Files

So far, we’ve worked with I/O by printing stuff to the terminal and reading from it. But what about reading and writing files? Well, in a way, we’ve already been doing that.

One way to think about reading from the terminal is that it’s like reading from a (somewhat special) file. The same goes for writing to the terminal— it’s kind of like writing to a file. We can call these two files stdout and stdin , meaning standard output and standard input, respectively. Writing to and reading from files is very much like writing to the standard output and reading from the standard input.

We’ll start off with a really simple program that opens a file called girlfriend.txt , which contains a verse from Avril Lavigne’s hit song “Girlfriend,” and just prints out to the terminal. Here’s girlfriend.txt :

Hey! Hey! You! You!
I don't like your girlfriend!
No way! No way!
I think you need a new one!

And here’s our program:

import System.IO

main = do
    handle <- openFile "girlfriend.txt" ReadMode
    contents <- hGetContents handle
    putStr contents
    hClose handle

If we compile and run it, we get the expected result:

$ ./girlfriend
Hey! Hey! You! You!
I don't like your girlfriend!
No way! No way!
I think you need a new one!

Let’s go over this line by line. The first line is just four exclamations, to get our attention. In the second line, Avril tells us that she doesn’t like our current partner of the female persuasion. The third line serves to emphasize that disapproval, and the fourth line suggests we should go about finding a suitable replacement.

Let’s also go over the program line by line. Our program is several I/O actions glued together with a do block. In the first line of the do block is a new function called openFile . It has the following type signature:

openFile :: FilePath -> IOMode -> IO Handle

openFile takes a file path and an IOMode and returns an I/O action that will open a file and yield the file’s associated handle as its result. FilePath is just a type synonym for String , defined as follows:

type FilePath = String

IOMode is a type that’s defined like this:

data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode

Just like our type that represents the seven possible values for the days of the week, this type is an enumeration that represents what we want to do with our opened file. Notice that this type is IOMode and not IO Mode . IO Mode would be the type of I/O action that yields a value of some type Mode as its result. IOMode is just a simple enumeration.

image with no caption

Finally, openFile returns an I/O action that will open the specified file in the specified mode. If we bind that action’s result to something, we get a Handle , which represents where our file is. We’ll use that handle so we know which file to read from.

In the next line, we have a function called hGetContents . It takes a Handle , so it knows which file to get the contents from, and returns an IO String —an I/O action that holds contents of the file as its result. This function is pretty much like getContents . The only difference is that getContents will automatically read from the standard input (that is, from the terminal), whereas hGetContents takes a file handle that tells it which file to read from. In all other respects, they work the same.

Just like getContents , hGetContents won’t attempt to read all the file at once and store it in memory but will read the content only as needed. This is really cool because we can treat contents as the whole content of the file, but it’s not really loaded in memory. So if this were a really huge file, doing hGetContents wouldn’t choke up our memory.

Note the difference between a handle and the actual contents of the file. A handle just points to our current position in the file. The contents are what’s actually in the file. If you imagine your whole filesystem as a really big book, the handle is like a bookmark that shows where you’re currently reading (or writing).

With putStr contents , we print the contents out to the standard output, and then we do hClose , which takes a handle and returns an I/O action that closes the file. You need to close the file yourself after opening it with openFile ! Your program may terminate if you try to open a file whose handle hasn’t been closed.

Using the withFile Function

Another way of working with the contents of a file as we just did is to use the withFile function, which has the following type signature:

withFile :: FilePath -> IOMode -> (Handle -> IO a) -> IO a

It takes a path to a file, an IOMode , and a function that takes a handle and returns some I/O action. Then it returns an I/O action that will open that file, do something with the file, and close it. Furthermore, if anything goes wrong while we’re operating on our file, withFile makes sure that the file handle gets closed. This might sound a bit complicated, but it’s really simple, especially if we use lambdas.

Here’s our previous example rewritten to use withFile :

import System.IO

main = do
    withFile "girlfriend.txt" ReadMode (\handle -> do
        contents <- hGetContents handle
        putStr contents)

(\handle -> ...) is the function that takes a handle and returns an I/O action, and it’s usually done like this, with a lambda. It needs to take a function that returns an I/O action, rather than just taking an I/O action to do and then closing the file, because the I/O action that we would pass to it wouldn’t know on which file to operate. This way, withFile opens the file and then passes the handle to the function we gave it. It gets an I/O action back from that function and then makes an I/O action that’s just like the original action, but it also makes sure that the file handle gets closed, even if something goes awry.

It’s Bracket Time

Usually, if a piece of code calls error (such as when we try to apply head to an empty list) or if something goes very wrong when doing input and output, our program terminates, and we see some sort of error message. In such circumstances, we say that an exception gets raised. The withFile function makes sure that despite an exception being raised, the file handle is closed.

This sort of scenario comes up often. We acquire some resource (like a file handle), and we want to do something with it, but we also want to make sure that the resource gets released (for example, the file handle is closed). Just for such cases, the Control.Exception module offers the bracket function. It has the following type signature:

image with no caption

bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c

Its first parameter is an I/O action that acquires a resource, such as a file handle. Its second parameter is a function that releases that resource. This function gets called even if an exception has been raised. The third parameter is a function that also takes that resource and does something with it. The third parameter is where the main stuff happens, like reading from a file or writing to it.

Because bracket is all about acquiring a resource, doing something with it, and making sure it gets released, implementing withFile is really easy:

withFile :: FilePath -> IOMode -> (Handle -> IO a) -> IO a
withFile name mode f = bracket (openFile name mode)
    (\handle -> hClose handle)
    (\handle -> f handle)

The first parameter that we pass to bracket opens the file, and its result is a file handle. The second parameter takes that handle and closes it. bracket makes sure that this happens even if an exception is raised. Finally, the third parameter to bracket takes a handle and applies the function f to it, which takes a file handle and does stuff with that handle, like reading from or writing to the corresponding file.

Grab the Handles!

Just as hGetContents works like getContents but for a specific file, functions like hGetLine , hPutStr , hPutStrLn , hGetChar , and so on work just like their counterparts without the h but take only a handle as a parameter and operate on that specific file instead of on standard input or standard output. For example, putStrLn takes a string and returns an I/O action that will print out that string to the terminal and a newline after it. hPutStrLn takes a handle and a string and returns an I/O action that will write that string to the file associated with the handle and then put a newline after it. In the same vein, hGetLine takes a handle and returns an I/O action that reads a line from its file.

Loading files and then treating their contents as strings is so common that we have three nice little functions to make our work even easier: readFile , writeFile , and appendFile.

The readFile function has a type signature of readFile :: FilePath -> IO String . (Remember that FilePath is just a fancy name for String .) readFile takes a path to a file and returns an I/O action that will read that file (lazily, of course) and bind its contents to something as a string. It’s usually more handy than calling openFile and then calling hGetContents with the resulting handle. Here’s how we could have written our previous example with readFile :

import System.IO

main = do
    contents <- readFile "girlfriend.txt"
    putStr contents

Because we don’t get a handle with which to identify our file, we can’t close it manually, so Haskell does that for us when we use readFile .

The writeFile function has a type of writeFile :: FilePath -> String -> IO () . It takes a path to a file and a string to write to that file and returns an I/O action that will do the writing. If such a file already exists, it will be stomped down to zero length before being written to. Here’s how to turn girlfriend.txt into a caps-locked version and write it to girlfriendcaps.txt :

import System.IO
import Data.Char

main = do
    contents <- readFile "girlfriend.txt"
    writeFile "girlfriendcaps.txt" (map toUpper contents)

The appendFile function has the same type signature as writeFile and acts almost the same way. The only difference is that appendFile doesn’t truncate the file to zero length if it already exists. Instead, it appends stuff to the end of that file.

To-Do Lists

Let’s put the appendFile function to use by making a program that adds a task to a text file that lists stuff that we have to do. We’ll assume that the file is named todo.txt and that it contains one task per line. Our program will take a line from the standard input and add it to our to-do list:

import System.IO

main = do
    todoItem <- getLine
    appendFile "todo.txt" (todoItem ++ "\n")

Notice that we added the "\n" to the end of each line, because getLine doesn’t give us a newline character at the end.

Save the file as appendtodo.hs , compile it, and then run it a few times and give it some to-do items.

$ ./appendtodo
Iron the dishes
$ ./appendtodo
Dust the dog
$ ./appendtodo
Take salad out of the oven
$ cat todo.txt
Iron the dishes
Dust the dog
Take salad out of the oven

Note

cat is a program on Unix-type systems that can be used to print text files to the terminal. On Windows systems, you can use your favorite text editor to see what’s inside todo.txt at any given time.

Deleting Items

We already made a program to add a new item to our to-do list in todo.txt . Now let’s make a program to remove an item. We’ll use a few new functions from System.Directory and one new function from System.IO , which will all be explained after the code listing.

import System.IO
import System.Directory
import Data.List

main = do
    contents <- readFile "todo.txt"
    let todoTasks = lines contents
        numberedTasks = zipWith (\n line -> show n ++ " - " ++ line)
                                    [0..] todoTasks
    putStrLn "These are your TO-DO items:"
    mapM_ putStrLn numberedTasks
    putStrLn "Which one do you want to delete?"
    numberString <- getLine
    let number = read numberString
        newTodoItems = unlines $ delete (todoTasks !! number) todoTasks
    (tempName, tempHandle) <- openTempFile "." "temp"
    hPutStr tempHandle newTodoItems
    hClose tempHandle
    removeFile "todo.txt"
    renameFile tempName "todo.txt"

First, we read todo.txt and bind its contents to contents . Then we split the contents into a list of strings, with one line for each string. So todoTasks is now something like this:

["Iron the dishes", "Dust the dog", "Take salad out of the oven"]

We zip the numbers from 0 onward and that list with a function that takes a number (like 3 ) and a string (like "hey" ) and returns a new string (like "3 - hey" ). Now numberedTasks looks like this:

["0 - Iron the dishes"
,"1 - Dust the dog"
,"2 - Take salad out of the oven"
]

We then use mapM_ putStrLn numberedTasks to print each task on a separate line, ask the user which one to delete, and wait for the user to enter a number. Let’s say we want to delete number 1 ( Dust the dog ), so we punch in 1 . numberString is now "1" , and because we want a number rather than a string, we apply read to that to get 1 and use a let to bind that to number .

Remember the delete and !! functions from Data.List ? !! returns an element from a list with some index. delete deletes the first occurrence of an element in a list and returns a new list without that occurrence. (todoTasks !! number) results in "Dust the dog" . We delete the first occurrence of "Dust the dog" from todoTasks and then join that into a single line with unlines and name that newTodoItems .

Then we use a function that we haven’t met before, from System.IO : openTempFile . Its name is pretty self-explanatory. It takes a path to a temporary directory and a template name for a file and opens a temporary file. We used "." for the temporary directory, because . denotes the current directory on just about any operating system. We used "temp" as the template name for the temporary file, which means that the temporary file will be named temp plus some random characters. It returns an I/O action that makes the temporary file, and the result in that I/O action is a pair of values: the name of the temporary file and a handle. We could just open a normal file called todo2.txt or something like that, but it’s better practice to use openTempFile so you know you’re probably not overwriting anything.

Now that we have a temporary file opened, we write newTodoItems to it. The old file is unchanged, and the temporary file contains all the lines that the old one does, except the one we deleted.

After that, we close both the original and the temporary files, and remove the original one with removeFile , which takes a path to a file and deletes it. After deleting the old todo.txt , we use renameFile to rename the temporary file to todo.txt . removeFile and renameFile (which are both in System.Directory ) take file paths, not handles, as their parameters.

Save this as deletetodo.hs , compile it, and try it:

$ ./deletetodo
These are your TO-DO items:
0 - Iron the dishes
1 - Dust the dog
2 - Take salad out of the oven
Which one do you want to delete?
1

Now let’s see which items remain:

$ cat todo.txt
Iron the dishes
Take salad out of the oven

Ah, cool! Let’s delete one more item:

$ ./deletetodo
These are your TO-DO items:
0 - Iron the dishes
1 - Take salad out of the oven
Which one do you want to delete?
0

And examining the file, we see that only one item remains:

$ cat todo.txt
Take salad out of the oven

So, everything is working. However, there’s one thing that about this program that’s kind of off. If something goes wrong after we open our temporary file, the program terminates, but the temporary file doesn’t get cleaned up. Let’s remedy that.

Cleaning Up

To make sure our temporary file is cleaned up in case of a problem, we’re going to use the bracketOnError function from Control.Exception . It’s very similar to bracket , but whereas the bracket will acquire a resource and then make sure that some cleanup always gets done after we’ve used it, bracketOnError performs the cleanup only if an exception has been raised. Here’s the code:

import System.IO
import System.Directory
import Data.List
import Control.Exception

main = do
    contents <- readFile "todo.txt"
    let todoTasks = lines contents
        numberedTasks = zipWith (\n line -> show n ++ " - " ++ line)
                                    [0..] todoTasks
    putStrLn "These are your TO-DO items:"
    mapM_ putStrLn numberedTasks
    putStrLn "Which one do you want to delete?"
    numberString <- getLine
    let number = read numberString
        newTodoItems = unlines $ delete (todoTasks !! number) todoTasks
    bracketOnError (openTempFile "." "temp")
        (\(tempName, tempHandle) -> do
            hClose tempHandle
            removeFile tempName)
        (\(tempName, tempHandle) -> do
            hPutStr tempHandle newTodoItems
            hClose tempHandle
            removeFile "todo.txt"
            renameFile tempName "todo.txt")

Instead of just using openTempFile normally, we use it with bracketOnError . Next, we write what we want to happen if an error occurs; that is, we want to close the temporary handle and remove the temporary file. Finally, we write what we want to do with the temporary file while things are going well, and these lines are the same as they were before. We write the new items, close the temporary handle, remove our current file, and rename the temporary file.

Command-Line Arguments

Dealing with command-line arguments is pretty much a necessity if you want to make a script or application that runs on a terminal. Luckily, Haskell’s standard library has a nice way of getting command-line arguments for a program.

In the previous section, we made one program for adding an item to our to-do list and one program for removing an item. A problem with them is that we just hardcoded the name of our to-do file. We decided that the file will be named todo.txt and that users will never have a need for managing several to-do lists.

image with no caption

One solution is to always ask the users which file they want to use as their to-do list. We used that approach when we wanted to know which item to delete. It works, but it’s not the ideal solution because it requires the users to run the program, wait for the program to ask them something, and then give the program some input. That’s called an interactive program.

The difficult bit with interactive command-line programs is this: What if you want to automate the execution of that program, as with a script? It’s harder to make a script that interacts with a program than a script that just calls one or more programs. That’s why we sometimes want users to tell a program what they want when they run the program, instead of having the program ask the user once it’s running. And what better way to have the users tell the program what they want it to do when they run it than via command-line arguments?

The System.Environment module has two cool I/O actions that are useful for getting command-line arguments: getArgs and getProgName . getArgs has a type of getArgs :: IO [String] and is an I/O action that will get the arguments that the program was run with and yield a list of those arguments. getProgName has a type of getProgName :: IO String and is an I/O action that yields the program name. Here’s a small program that demonstrates how these two work:

import System.Environment
import Data.List

main = do
   args <- getArgs
   progName <- getProgName
   putStrLn "The arguments are:"
   mapM putStrLn args
   putStrLn "The program name is:"
   putStrLn progName

First, we bind the command-line arguments to args and program name to progName . Next, we use putStrLn to print all the program’s arguments and then the name of the program itself. Let’s compile this as arg-test and try it out:

$ ./arg-test first second w00t "multi word arg"
The arguments are:
first
second
w00t
multi word arg
The program name is:
arg-test

More Fun with To-Do Lists

In the previous examples, we made one program for adding tasks and an entirely separate program for deleting them. Now we’re going to join that into a single program, and whether it adds or deletes items will depend on the command-line arguments we pass to it. We’ll also make it able to operate on different files, not just todo.txt .

We’ll call our program todo , and it will be able to do three different things:

  • View tasks

  • Add tasks

  • Delete tasks

To add a task to the todo.txt file, we enter it at the terminal:

$ ./todo add todo.txt "Find the magic sword of power"

To view the tasks, we enter the view command:

$ ./todo view todo.txt

To remove a task, we use its index:

$ ./todo remove todo.txt 2

A Multitasking Task List

We’ll start by making a function that takes a command in the form of a string, like "add" or "view" , and returns a function that takes a list of arguments and returns an I/O action that does what we want:

import System.Environment
import System.Directory
import System.IO
import Data.List
import Control.Exception

dispatch :: String -> [String] -> IO ()
dispatch "add" = add
dispatch "view" = view
dispatch "remove" = remove

We’ll define main like this:

main = do
    (command:argList) <- getArgs
    dispatch command argList

First, we get the arguments and bind them to (command:argList) . This means that the first argument will be bound to command , and the rest of the arguments will be bound to argList . In the next line of our main block, we apply the dispatch function to the command, which results in the add , view , or remove function. We then apply that function to argList .

Suppose we call our program like this:

$ ./todo add todo.txt "Find the magic sword of power"

command is "add" , and argList is ["todo.txt", "Find the magic sword of power"] . That way, the second pattern match of the dispatch function will succeed, and it will return the add function. Finally, we apply that to argList , which results in an I/O action that adds the item to our to-do list.

Now let’s implement the add , view , and remove functions. Let’s start with add :

add :: [String] -> IO ()
add [fileName, todoItem] = appendFile fileName (todoItem ++ "\n")

We might call our program like so:

./todo add todo.txt "Find the magic sword of power"

The "add" will be bound to command in the first pattern match in the main block, whereas ["todo.txt", "Find the magic sword of power"] will be passed to the function that we get from the dispatch function. So, because we’re not dealing with bad input right now, we just pattern match against a list with those two elements immediately and return an I/O action that appends that line to the end of the file, along with a newline character.

Next, let’s implement the list-viewing functionality. If we want to view the items in a file, we do ./todo view todo.txt . So in the first pattern match, command will be "view" , and argList will be ["todo.txt"] . Here’s the function in full:

view :: [String] -> IO ()
view [fileName] = do
    contents <- readFile fileName
    let todoTasks = lines contents
        numberedTasks = zipWith (\n line -> show n ++ " - " ++ line)
                        [0..] todoTasks
    putStr $ unlines numberedTasks

When we made our deletetodo program, which could only delete items from a to-do list, it had the ability to display the items in a to-do list, so this code is very similar to that part of the previous program.

Finally, we’re going to implement remove . It’s very similar to the program that only deleted the tasks, so if you don’t understand how deleting an item here works, review “ Deleting Items ” on page 181 . The main difference is that we’re not hardcoding the filename as todo.txt but instead getting it as an argument. We’re also getting the target task number as an argument, rather than prompting the user for it.

remove :: [String] -> IO ()
remove [fileName, numberString] = do
    contents <- readFile fileName
    let todoTasks = lines contents
        numberedTasks = zipWith (\n line -> show n ++ " - " ++ line)
                                    [0..] todoTasks
    putStrLn "These are your TO-DO items:"
    mapM_ putStrLn numberedTasks
    let number = read numberString
        newTodoItems = unlines $ delete (todoTasks !! number) todoTasks
    bracketOnError (openTempFile "." "temp")
        (\(tempName, tempHandle) -> do
            hClose tempHandle
            removeFile tempName)

        (\(tempName, tempHandle) -> do
            hPutStr tempHandle newTodoItems
            hClose tempHandle
            removeFile fileName
            renameFile tempName fileName)

We opened the file based on fileName and opened a temporary file, deleted the line with the index that the user wants to delete, wrote that to the temporary file, removed the original file, and renamed the temporary file back to fileName .

Here’s the whole program in all its glory:

import System.Environment
import System.Directory
import System.IO
import Data.List

dispatch :: String -> [String] -> IO ()
dispatch "add" = add
dispatch "view" = view
dispatch "remove" = remove

main = do
    (command:argList) <- getArgs
    dispatch command argList

add :: [String] -> IO ()
add [fileName, todoItem] = appendFile fileName (todoItem ++ "\n")

view :: [String] -> IO ()
view [fileName] = do
    contents <- readFile fileName
    let todoTasks = lines contents
        numberedTasks = zipWith (\n line -> show n ++ " - " ++ line)
                        [0..] todoTasks
    putStr $ unlines numberedTasks

remove :: [String] -> IO ()
remove [fileName, numberString] = do
    contents <- readFile fileName
    let todoTasks = lines contents
        numberedTasks = zipWith (\n line -> show n ++ " - " ++ line)
                                    [0..] todoTasks
    putStrLn "These are your TO-DO items:"
    mapM_ putStrLn numberedTasks
    let number = read numberString
        newTodoItems = unlines $ delete (todoTasks !! number) todoTasks
    bracketOnError (openTempFile "." "temp")
        (\(tempName, tempHandle) -> do
            hClose tempHandle
            removeFile tempName)
        (\(tempName, tempHandle) -> do
            hPutStr tempHandle newTodoItems
            hClose tempHandle
            removeFile "todo.txt"
            renameFile tempName "todo.txt")

To summarize our solution, we made a dispatch function that maps from commands to functions that take some command-line arguments in the form of a list and return an I/O action. We see what the command is, and based on that, we get the appropriate function from the dispatch function. We call that function with the rest of the command-line arguments to get back an I/O action that will do the appropriate thing, and then just perform that action. Using higher-order functions allows us to just tell the dispatch function to give us the appropriate function, and then tell that function to give us an I/O action for some command-line arguments.

Let’s try our app!

$ ./todo view todo.txt
0 - Iron the dishes
1 - Dust the dog
2 - Take salad out of the oven

$ ./todo add todo.txt "Pick up children from dry cleaners"

$ ./todo view todo.txt
0 - Iron the dishes
1 - Dust the dog
2 - Take salad out of the oven
3 - Pick up children from dry cleaners

$ ./todo remove todo.txt 2

$ ./todo view todo.txt
0 - Iron the dishes
1 - Dust the dog
2 - Pick up children from dry cleaners :

Another cool thing about using the dispatch function is that it’s easy to add functionality. Just add an extra pattern to dispatch and implement the corresponding function, and you’re laughing! As an exercise, you can try implementing a bump function that will take a file and a task number and return an I/O action that bumps that task to the top of the to-do list.

Dealing with Bad Input

We could extend this program to make it fail a bit more gracefully in the case of bad input, instead of printing out an ugly error message from Haskell. We can start by adding a catchall pattern at the end the dispatch function and making it return a function that ignores the argument list and tells us that such a command doesn’t exist:

dispatch :: String -> [String] -> IO ()
dispatch "add" = add
dispatch "view" = view
dispatch "remove" = remove
dispatch command = doesntExist command

doesntExist :: String -> [String] -> IO ()
doesntExist command _ =
    putStrLn $ "The " ++ command ++ " command doesn't exist"

We might also add catchall patterns to the add , view , and remove functions, so that the program tells users if they have supplied the wrong number of arguments to a given command. Here’s an example:

add :: [String] -> IO ()
add [fileName, todoItem] = appendFile fileName (todoItem ++ "\n")
add _ = putStrLn "The add command takes exactly two arguments"

If add is applied to a list that doesn’t have exactly two elements, the first pattern match will fail, but the second one will succeed, helpfully informing users of their erroneous ways. We can add a catchall pattern like this to view and remove as well.

Note that we haven’t covered all of the cases where our input is bad. For instance, suppose we run our program like this:

./todo

In this case, it will crash, because we use the (command:argList) pattern in our do block, but that doesn’t consider the possibility that there are no arguments at all! We also don’t check to see if the file we’re operating on exists before trying to open it. Adding these precautions isn’t hard, but it is a bit tedious, so making this program completely idiot-proof is left as an exercise to the reader.

Randomness

Many times while programming, you need to get some random data (well, pseudo -random data, since we all know that the only true source of randomness is a monkey on a unicycle with cheese in one hand and its butt in the other). For example, you may be making a game where a die needs to be thrown, or you need to generate some data to test your program. In this section, we’ll take a look at how to make Haskell generate seemingly random data and why we need external input to generate values that are random enough.

image with no caption

Most programming languages have functions that give you back some random number. Each time you call that function, you retrieve a different random number. How about Haskell? Well, remember that Haskell is a purely functional language. That means it has referential transparency. And that means a function, if given the same parameters twice, must produce the same result twice. That’s really cool, because it allows us to reason about programs, and it enables us to defer evaluation until we really need it. However, this makes it a bit tricky for getting random numbers.

Suppose we have a function like this:

randomNumber :: Int
randomNumber = 4

It’s not very useful as a random number function, because it will always return 4 . (Even though I can assure you that the 4 is completely random, because I used a die to determine it.)

How do other languages make seemingly random numbers? Well, they take some initial data, like the current time, and based on that, generate numbers that are seemingly random. In Haskell, we can generate random numbers by making a function that takes as its parameter some initial data, or randomness, and produces a random number. We use I/O to bring randomness into our program from outside.

Enter the System.Random module. It has all the functions that satisfy our need for randomness. Let’s just dive into one of the functions it exports: random . Here is its type signature:

random :: (RandomGen g, Random a) => g -> (a, g)

Note

If GHC complains that it can’t find the module System.Random, run cabal install --lib random in your command line to install it.

Whoa! We have some new type classes in this type declaration! The RandomGen type class is for types that can act as sources of randomness. The Random type class is for types whose values can be random. We can generate random Boolean values by randomly producing either True or False . We can also generate numbers that are random. Can a function take on a random value? I don’t think so! If we try to translate the type declaration of random to English, we get something like this: It takes a random generator (that’s our source of randomness) and returns a random value and a new random generator. Why does it also return a new generator as well as a random value? Well, you’ll see in a moment.

To use our random function, we need to get our hands on one of those random generators. The System.Random module exports a cool type, namely StdGen , which is an instance of the RandomGen type class. We can make a StdGen manually, or we can tell the system to give us one based on a multitude of (sort of) random stuff.

To manually make a random generator, use the mkStdGen function. It has a type of mkStdGen :: Int -> StdGen . It takes an integer, and based on that, gives us a random generator. Okay then, let’s try using random and mkStdGen in tandem to get a (hardly) random number.

ghci> random $ mkStdGen 100
(-1352021624,651872571 1655838864)

Great, a number that looks kind of random! The first component of the tuple is our number, and the second component is a textual representation of our new random generator. What happens if we call random with the same random generator again?

ghci> random $ mkStdGen 100
(-1352021624,651872571 1655838864)

Of course, we get the same result for the same parameters. So let’s try giving it a different random generator as a parameter:

ghci> random $ mkStdGen 949494
(539963926,466647808 1655838864)

Cool, it’s a different number! We can use the type annotation to get different types back from that function.

ghci> random (mkStdGen 949494) :: (Float, StdGen)
(0.7463806,466647808 1655838864)
ghci> random (mkStdGen 949494) :: (Bool, StdGen)
(False,1485872359 40692)
ghci> random (mkStdGen 949494) :: (Integer, StdGen)
(6642787099209953655,75809027 2103410263)

Great, a different number! We can use the type annotation to get different types back from that function.

ghci> random (mkStdGen 949488) :: (Float, StdGen)
(0.8938442,1597344447 1655838864)

ghci> random (mkStdGen 949488) :: (Bool, StdGen)
(False,1485632275 40692)
ghci> random (mkStdGen 949488) :: (Integer, StdGen)
(1691547873,1597344447 1655838864)

Tossing a Coin

Let’s make a function that simulates tossing a coin three times. If random didn’t return a new generator along with a random value, we would need to make this function take three random generators as a parameter and return coin tosses for each of them. But if one generator can make a random value of type Int (which can take on a load of different values), it should be able to make three coin tosses (which can have only eight different end results). So this is where random returning a new generator along with a value comes in handy.

We’ll represent a coin with a simple Bool : True is tails, and False is heads.

threeCoins :: StdGen -> (Bool, Bool, Bool)
threeCoins gen =
    let (firstCoin, newGen) = random gen
        (secondCoin, newGen') = random newGen
        (thirdCoin, newGen'') = random newGen'
    in  (firstCoin, secondCoin, thirdCoin)

We call random with the generator we got as a parameter to get a coin and a new generator. Then we call it again, only this time with our new generator, to get the second coin. We do the same for the third coin. Had we called it with the same generator every time, all the coins would have had the same value, so we would get only (False, False, False) or (True, True, True) as a result.

ghci> threeCoins (mkStdGen 21)
(True,True,True)
ghci> threeCoins (mkStdGen 22)
(True,False,True)
ghci> threeCoins (mkStdGen 943)
(True,False,True)
ghci> threeCoins (mkStdGen 944)
(True,True,True)

Notice that we didn’t need to call random gen :: (Bool, StdGen) . Since we already specified that we want Booleans in the type declaration of the function, Haskell can infer that we want a Boolean value in this case.

More Random Functions

What if we want to flip more coins? For that, there’s a function called randoms , which takes a generator and returns an infinite sequence of values based on that generator.

ghci> take 5 $ randoms (mkStdGen 11) :: [Int]
[-1807975507,545074951,-1015194702,-1622477312,-502893664]
ghci> take 5 $ randoms (mkStdGen 11) :: [Bool]
[True,True,True,True,False]
ghci> take 5 $ randoms (mkStdGen 11) :: [Float]
[7.904789e-2,0.62691015,0.26363158,0.12223756,0.38291094]

Why doesn’t randoms return a new generator as well as a list? We could implement the randoms function very easily like this:

randoms' :: (RandomGen g, Random a) => g -> [a]
randoms' gen = let (value, newGen) = random gen in value:randoms' newGen

This is a recursive definition. We get a random value and a new generator from the current generator, and then make a list that has the value as its head and random numbers based on the new generator as its tail. Because we need to be able to potentially generate an infinite amount of numbers, we can’t give the new random generator back.

We could make a function that generates a finite stream of numbers and a new generator like this:

finiteRandoms :: (RandomGen g, Random a) => Int -> g -> ([a], g)
finiteRandoms 0 gen = ([], gen)
finiteRandoms n gen =
    let (value, newGen) = random gen
        (restOfList, finalGen) = finiteRandoms (n-1) newGen
    in  (value:restOfList, finalGen)

Again, this is a recursive definition. We say that if we want zero numbers, we just return an empty list and the generator that was given to us. For any other number of random values, we first get one random number and a new generator. That will be the head. Then we say that the tail will be n - 1 numbers generated with the new generator. Then we return the head and the rest of the list joined and the final generator that we got from getting the n - 1 random numbers.

What if we want a random value in some sort of range? All the random integers so far were outrageously big or small. What if we want to throw a die? Well, we use randomR for that purpose. It has this type:

randomR :: (RandomGen g, Random a) :: (a, a) -> g -> (a, g)

This means that it’s kind of like random , but it takes as its first parameter a pair of values that set the lower and upper bounds, and the final value produced will be within those bounds.

ghci> randomR (1,6) (mkStdGen 359353)
(6,1494289578 40692)
ghci> randomR (1,6) (mkStdGen 35935335)
(3,1250031057 40692)

There’s also randomRs , which produces a stream of random values within our defined ranges. Check this out:

ghci> take 10 $ randomRs ('a','z') (mkStdGen 3) :: [Char]
"ndkxbvmomg"

It looks like a super secret password, doesn’t it?

Randomness and I/O

You may be wondering what this section has to do with I/O. We haven’t done anything concerning I/O so far. We’ve always made our random number generator manually by creating it with some arbitrary integer. The problem is that if we do that in our real programs, they will always return the same random numbers, which is no good for us. That’s why System.Random offers the getStdGen I/O action, which has a type of IO StdGen . It asks the system for some initial data and uses it to jump-start the global generator . getStdGen fetches that global random generator when you bind it to something.

Here’s a simple program that generates a random string:

import System.Random

main = do
    gen <- getStdGen
    putStrLn $ take 20 (randomRs ('a','z') gen)

Now let’s test it:

$ ./random_string
pybphhzzhuepknbykxhe
$ ./random_string
eiqgcxykivpudlsvvjpg
$ ./random_string
nzdceoconysdgcyqjruo
$ ./random_string
bakzhnnuzrkgvesqplrx

But you need to be careful. Just performing getStdGen twice will ask the system for the same global generator twice. Suppose we do this:

import System.Random

main = do
    gen <- getStdGen
    putStrLn $ take 20 (randomRs ('a','z') gen)
    gen2 <- getStdGen
    putStr $ take 20 (randomRs ('a','z') gen2)

We will get the same string printed out twice!

The best way to get two different strings is to use the newStdGen action, which splits our current random generator into two generators. It updates the global random generator with one of them and yields the other as its result.

import System.Random

main = do
    gen <- getStdGen
    putStrLn $ take 20 (randomRs ('a','z') gen)
    gen' <- newStdGen
    putStr $ take 20 (randomRs ('a','z') gen')

Not only do we get a new random generator when we bind newStdGen to something, but the global one gets updated as well. This means that if we do getStdGen again and bind it to something, we’ll get a generator that’s not the same as gen .

Here’s a little program that will make the user guess which number it’s thinking of:

import System.Random
import Control.Monad(when)

main = do
    gen <- getStdGen
    askForNumber gen

askForNumber :: StdGen -> IO ()
askForNumber gen = do
    let (randNumber, newGen) = randomR (1,10) gen :: (Int, StdGen)
    putStrLn "Which number in the range from 1 to 10 am I thinking of? "
    numberString <- getLine
    when (not $ null numberString) $ do
        let number = read numberString

        if randNumber == number
            then putStrLn "You are correct!"
            else putStrLn $ "Sorry, it was " ++ show randNumber
        askForNumber newGen

image with no caption

We make a function askForNumber , which takes a random number generator and returns an I/O action that will prompt you for a number, and then tell you if you guessed it right.

In askForNumber , we first generate a random number and a new generator based on the generator that we got as a parameter and call them randNumber and newGen . (For this example, let’s say that the number generated was 7.) Then we tell the user to guess which number we’re thinking of. We perform getLine and bind its result to numberString . When the user enters 7 , numberString becomes "7" . Next, we use when to check if the string the user entered is an empty string. If it isn’t, the action consisting of the do block that is passed to when is performed. We use read on numberString to convert it to a number, so number is now 7 .

Note

If the user enters some input that read can’t parse (like "haha" ), our program will crash with an ugly error message. If you don’t want your program to crash on erroneous input, use reads , which returns an empty list when it fails to read a string. When it succeeds, it returns a singleton list with a tuple that has your desired value as one component and a string with what it didn’t consume as the other. Try it!

We check if the number that we entered is equal to the one generated randomly and give the user the appropriate message. Then we perform askForNumber recursively, but this time with the new generator that we got. This gives us an I/O action that’s just like the one we performed, except that it depends on a different generator.

main consists of just getting a random generator from the system and calling askForNumber with it to get the initial action.

Here’s our program in action:

$ ./guess_the_number
Which number in the range from 1 to 10 am I thinking of?
4
Sorry, it was 3
Which number in the range from 1 to 10 am I thinking of?
10
You are correct!
Which number in the range from 1 to 10 am I thinking of?
2
Sorry, it was 4
Which number in the range from 1 to 10 am I thinking of?
5
Sorry, it was 10
Which number in the range from 1 to 10 am I thinking of?

Here’s another way to make this same program:

import System.Random
import Control.Monad(when)

main = do
    gen <- getStdGen
    let (randNumber, _) = randomR (1,10) gen :: (Int, StdGen)
    putStrLn "Which number in the range from 1 to 10 am I thinking of? "
    numberString <- getLine
    when (not $ null numberString) $ do
        let number = read numberString
        if randNumber == number
            then putStrLn "You are correct!"
            else putStrLn $ "Sorry, it was " ++ show randNumber
        newStdGen
        main

It’s very similar to the previous version, but instead of making a function that takes a generator and then calls itself recursively with the new updated generator, we do all the work in main . After telling the user whether he was correct in his guess, we update the global generator and then call main again. Both approaches are valid, but I like the first one more since it does less stuff in main and also provides a function I can reuse easily.

Bytestrings

Lists are certainly useful. So far, we’ve used them pretty much everywhere. There are a multitude of functions that operate on them, and Haskell’s laziness allows us to exchange the for and while loops of other languages for filtering and mapping over lists. Since evaluation will happen only when it really needs to, things like infinite lists (and even infinite lists of infinite lists!) are no problem for us. That’s why lists can also be used to represent streams, either when reading from the standard input or when reading from files. We can just open a file and read it as a string, even though it will be accessed only when the need arises.

image with no caption

However, processing files as strings has one drawback: It tends to be slow. Lists are really lazy. Remember that a list like [1,2,3,4] is syntactic sugar for 1:2:3:4:[] . When the first element of the list is forcibly evaluated (say by printing it), the rest of the list 2:3:4:[] is still just a promise of a list, and so on. We call that promise a thunk .

A thunk is basically a deferred computation. Haskell achieves its laziness by using thunks and computing them only when it must, instead of computing everything up front. So you can think of lists as promises that the next element will be delivered once it really has to be, and along with it, the promise of the element after it. It doesn’t take a big mental leap to conclude that processing a simple list of numbers as a series of thunks might not be the most efficient technique in the world.

That overhead doesn’t bother us most of the time, but it turns out to be a liability when reading big files and manipulating them. That’s why Haskell has bytestrings . Bytestrings are sort of like lists, only each element is one byte (or 8 bits) in size. The way they handle laziness is also different.

Strict and Lazy Bytestrings

Bytestrings come in two flavors: strict and lazy. Strict bytestrings reside in Data.ByteString , and they do away with the laziness completely. There are no thunks involved. A strict bytestring represents a series of bytes in an array. You can’t have things like infinite strict bytestrings. If you evaluate the first byte of a strict bytestring, you must evaluate the whole thing.

The other variety of bytestrings resides in Data.ByteString.Lazy . They’re lazy, but not quite as lazy as lists. Since there are as many thunks in a list as there are elements, they are kind of slow for some purposes. Lazy bytestrings take a different approach. They are stored in chunks (not to be confused with thunks!), and each chunk has a size of 64KB. So if you evaluate a byte in a lazy bytestring (by printing it, for example), the first 64KB will be evaluated. After that, it’s just a promise for the rest of the chunks. Lazy bytestrings are kind of like lists of strict bytestrings, with a size of 64KB. When you process a file with lazy bytestrings, it will be read chunk by chunk. This is cool because it won’t cause the memory usage to skyrocket, and the 64KB probably fits neatly into your CPU’s L2 cache.

If you look through the documentation for Data.ByteString.Lazy , you will see that it has a lot of functions with the same names as the ones from Data.List , but the type signatures have ByteString instead of [a] and Word8 instead of a . These functions are similar to the ones that work on lists. Because the names are the same, we’re going to do a qualified import in a script and then load that script into GHCi to play with bytestrings:

import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString as S

B has lazy bytestring types and functions, whereas S has strict ones. We’ll mostly be using the lazy versions.

The pack function has the type signature pack :: [Word8] -> ByteString . This means that it takes a list of bytes of type Word8 and returns a ByteString . You can think of it as taking a list, which is lazy, and making it less lazy, so that it’s lazy only at 64KB intervals.

The Word8 type is like Int , but it represents an unsigned 8-bit number. This means that it has a much smaller range of only 0 to 255. And just like Int , it’s in the Num type class. For instance, we know that the value 5 is polymorphic in that it can act like any numeric type, including Word8 .

Here’s how we pack lists of numbers into bytestrings:

ghci> B.pack [99,97,110]
"can"
ghci> B.pack [98..120]
"bcdefghijklmnopqrstuvwx"

We packed only a handful of values into a bytestring, so they fit inside one chunk. Empty is like [] for lists—they both represent an empty sequence.

As you can see, you don’t need to specify that your numbers are of type Word8 , because the type system can make numbers choose that type. If you try to use a big number like 336 as a Word8 , it will just wrap around to 80 .

When we need to examine a bytestring byte by byte, we need to unpack it. The unpack function is the inverse of pack . It takes a bytestring and turns it into a list of bytes.

Here’s an example:

ghci> let by = B.pack [98,111,114,116]
ghci> by
"bort"
ghci> B.unpack by
[98,111,114,116]

You can also go back and forth between strict and lazy bytestrings. The toChunks function takes a lazy bytestring and converts it to a list of strict ones. The fromChunks function takes a list of strict bytestrings and converts it to a lazy bytestring:

ghci> B.fromChunks [S.pack [40,41,42], S.pack [43,44,45], S.pack [46,47,48]]
"()*+,-./0"

This is good if you have a lot of small strict bytestrings and you want to process them efficiently without joining them into one big strict bytestring in memory first.

The bytestring version of : is called cons . It takes a byte and a bytestring and puts the byte at the beginning.

ghci> B.cons 85 $ B.pack [80,81,82,84]
"UPQRT"

The bytestring modules have a load of functions that are analogous to those in Data.List , including, but not limited to, head , tail , init , null , length , map , reverse , foldl , foldr , concat , takeWhile , filter , and so on. For a complete listing of bytestring functions, check out the documentation for the bytestring package at http://hackage.haskell.org/package/bytestring/ .

The bytestring modules also have functions that have the same name and behave the same as some functions found in System.IO , but Strings are replaced with ByteStrings . For instance, the readFile function in System.IO has this type:

readFile :: FilePath -> IO String

The readFile function from the bytestring modules has the following type:

readFile :: FilePath -> IO ByteString

Note

If you’re using strict bytestrings and you attempt to read a file, all of that file will be read into memory at once! With lazy bytestrings, the file will be read in neat chunks.

Copying Files with Bytestrings

Let’s make a program that takes two filenames as command-line arguments and copies the first file into the second file. Note that System.Directory already has a function called copyFile , but we’re going to implement our own file-copying function and program anyway. Here’s the code:

import System.Environment
import System.Directory
import System.IO
import Control.Exception
import qualified Data.ByteString.Lazy as B

main = do
    (fileName1:fileName2:_) <- getArgs
    copy fileName1 fileName2

copy source dest = do
    contents <- B.readFile source
    bracketOnError
        (openTempFile "." "temp")
        (\(tempName, tempHandle) -> do
            hClose tempHandle
            removeFile tempName)
        (\(tempName, tempHandle) -> do
            B.hPutStr tempHandle contents
            hClose tempHandle
            renameFile tempName dest)

To begin, in main , we just get the command-line arguments and call our copy function, which is where the magic happens. One way to do this would be to just read from one file and write to another. But if something goes wrong (such as we don’t have enough disk space to copy the file), we’ll be left with a messed-up file. So we’ll write to a temporary file first. Then if something goes wrong, we can just delete that file.

First, we use B.readFile to read the contents of our source file. Then we use bracketOnError to set up our error handling. We acquire the resource with openTempFile "." "temp" , which yields a tuple that consists of a temporary filename and a handle. Next, we say what we want to happen if an error occurs. If something goes wrong, we close the handle and remove the temporary file. Finally, we do the copying itself. We use B.hPutStr to write the contents to our temporary file. We close the temporary file and rename it to what we want it to be in the end.

Notice that we just used B.readFile and B.hPutStr instead of their regular variants. We didn’t need to use special bytestring functions for opening, closing, and renaming files. We just need to use the bytestring functions when reading and writing.

Let’s test it:

$ ./bytestringcopy bart.txt bort.txt

A program that doesn’t use bytestrings could look just like this. The only difference is that we used B.readFile and B.writeFile instead of readFile and writeFile .

Many times, you can convert a program that uses normal strings to a program that uses bytestrings just by doing the necessary imports and then putting the qualified module names in front of some functions. Sometimes, you need to convert functions that you wrote to work on strings so that they work on bytestrings, but that’s not hard.

Whenever you need better performance in a program that reads a lot of data into strings, give bytestrings a try. Chances are you’ll get some good performance boosts with very little effort on your part. I usually write programs using normal strings and then convert them to use bytestrings if the performance is not satisfactory.