Now that you have a basic application up and running, it’s time to make it do something useful. We’ll add several features to our program throughout this chapter, but for now let’s focus on a single feature: displaying the contents of a file to the screen. To do that we’ll need to:
- Know which file the user wants to view
- Read the contents of the file
- Write the contents of the file to the screen
We’ll take each of these requirements in order. Once we’re done you’ll have a program that works like a minimal version of the Unix cat command.
Reading a Filename from the Command Line
Before we can do anything with a file, like reading it, we need to know what file we’re working with. For a command line pager, the most convenient way to get a filename is to have the user pass it along as the first argument when they run our program.
If you run the program directly, you can pass command line arguments to a Haskell program the same way that you pass arguments to any other application: by listing them right after the name of the program you want to run:
| | user@host$ hcat filename.txt |
When you are actively working on a program, it’s more common to run the application with cabal run . This lets you easily ensure that the program gets recompiled when it needs to, so you don’t find yourself accidentally running an older version. There are few things more frustrating than spending time trying to figure out why a new feature isn’t working, or a bug didn’t get fixed, only to realize that you forgot to recompile the program.
Passing command line arguments to a program you are running with cabal run works almost exactly the same as passing command line arguments to any other program. The difference is that when you are running a program with cabal you need to handle both the arguments that you might want to pass to cabal and the arguments that you might want to pass to your program.
Cabal handles this by treating all arguments as arguments to the cabal process up until it encounters two dashes ( -- ). Everything after the two dashes are arguments to the program you are running:
| | user@host$ cabal run hcat -- filename.txt |
Here, cabal is getting two arguments: run and hcat . Next, we pass in -- to end the list of arguments to cabal and then add filename.txt which will be the first argument to the program we’re running.
We can pass in as many arguments as we’d like, but it won’t do us any good until we update our program to look at them, so let’s update HCat to read the arguments that have been passed into our program and print them out.
The System.Environment module from base comes with all of the functions that we need to get information from the environment, including the command line arguments that were passed in. Let’s add it to the import list:
| | import qualified System.Environment as Env |
This module gives us getArgs , which is an IO action that’ll give us a list of strings holding all the command line arguments that were passed in. Its type is:
| | getArgs :: IO [ String ] |
We can see this in action by getting the list of arguments and then printing them out:
| | runHCat :: IO () |
| | runHCat = Env .getArgs >>= print |
Let’s run through a couple of examples just to get a feel for how this works. We’ll start by passing in no arguments, and as you might expect we get back an empty list. In some languages, when you get the list of command line arguments, the first argument is always the name of the executable that was called, but getArgs doesn’t do that; you’ll only get the list of arguments that were passed to the program, not the name of the program. If we don’t pass any arguments, our program will print out an empty list:
| | user@host$ cabal run hcat |
| | [] |
The specifics of how arguments are handled is an implementation detail of your shell. Generally arguments are separated by spaces. Let’s pass in a couple of arguments so that we can see that the list that gets printed out does indeed match the argument list we’re providing:
| | user@host$ cabal run hcat -- foo 123 |
| | ["foo","123"] |
The getArgs function can handle arguments that contain spaces and special characters. The ways you have to send arguments with spaces and special characters will vary a bit depending on the shell that you’re using, but generally if you pass in escaped or quoted arguments they’ll be handled as you would expect.
| | user@host$ cabal run hcat -- foo 123 \"quoted\" "embedded space" |
| | ["foo","123","\"quoted\"","embedded space"] |
If you want to try testing this from ghci you might quickly run into a problem: how can you pass commands to the program from ghci ? The withArgs function function will help you with both of those problems.
withArgs takes a list of strings and an IO action, for example, our runHCat action that prints the arguments:
| | user@host$ cabal repl lib:hcat |
| | λ import qualified System.Environment as Env |
| | λ Env.withArgs ["foo", "123", "embedded spaces"] runHCat |
| | ["foo","123","embedded spaces"] |
Being able to quickly test some of our code in ghci even when we’re dealing with command line argument processing will make it easier to iterate on your code as you are working through some of the examples early on in this chapter.
Handling Command Line Arguments
Being able to read arguments from the command line is great, but printing them out to the screen doesn’t help us much. We need to handle the arguments that were passed in so we can do something useful with the filename.
Command line argument processing can turn into a complicated problem, and for most applications you would write it makes sense to turn to one of the several command line parsing libraries. These libraries often make use of features that you won’t learn about until later on in this book, and the process of building command line handling ourselves is instructive, so for this example we’ll handle the parsing manually.
For now the only thing we want our program to do is to accept the name of a file, read that file, and print its contents to the screen. To do that, we only need to accept a single argument: the name of the file that we want to print. Let’s start our implementation by writing a new function, handleArgs , that will look at our command line arguments and return the path to the file that we should open:
| | handleArgs :: IO FilePath |
| | handleArgs = |
| | head <$> Env .getArgs |
The very first thing you might notice in this example is that the type of our function is IO FilePath , not IO String . We can do this because FilePath is a type alias for String . Using FilePath in our type here lets us remind ourselves that we’re expecting the argument we get to be a path to some file, and not just an arbitrary string.
You might also notice that we’re again making use of the (<$>) function you learned about earlier in this book. Like before, we’re using this so we can apply a regular pure Haskell function, head in this case, to the value our IO action will compute.
The end result is that handleArgs is an IO action that should get the first element from the list of command line arguments that were passed into the program when it was started.
Let’s update runHCat to call handleArgs so that we can see it in action.
| | runHCat :: IO () |
| | runHCat = handleArgs >>= print |
With our new argument handling code in place, we expect that our program will print out the first, and only the first, argument that gets passed to it. Although we’re using the FilePath type, that’s just an alias for a regular String , so we can still test our program for now using some placeholder values:
| | user@host$ cabal run hcat -- foo |
| | "foo" |
| | user@host$ cabal run hcat -- foo bar baz |
| | "foo" |
This is looking good. Whether we pass a single argument or several arguments, we’re always printing out the first thing that was passed in. We do have a problem with our current program though:
| | user@host$ cabal run hcat |
| | hcat: Prelude.head: empty list |
If we run our program with no arguments, we get a runtime error. An error of some kind isn’t really a problem here—after all, there’s really no correct behavior for the program to do if we don’t give it a file as input. Unfortunately, the error that we’re generating isn’t at all helpful for the user. Let’s try to figure out the problem with our program and then try to make some changes to make our program more robust and able to provide better error messages.
The error that we’re seeing is a runtime exception that’s being raised because we’ve tried to call the head function on an empty list. You may recall from earlier in this book that this won’t work. The head function is partial and it’s not well defined for empty lists. That means instead of getting some well-defined error out when we call head , the whole program just blows up and we’re left showing our users an exception. Let’s revisit handleArgs and see if we can come up with a better approach.
The problem we should think about is the exception that’s being raised. We’re getting an error because we’re trying to pass an empty list to head . This makes perfect sense; if the list we’re getting is the list of arguments, and we don’t provide any arguments, then naturally the argument list will be empty.
Let’s think about the solution to our problem starting with the types. If we think just about the part of the function that’s working correctly, it’s a function from a non-empty list of strings to a FilePath . Unfortunately, we can’t ensure that the user will always enter something at the command line, so we need to expand the valid range of input values to account for potentially empty lists. We don’t actually have to change anything here since we’re already getting those empty lists—and that’s what’s causing our bug.
On the output side of our function, we can’t create a FilePath from an empty list, but we can create an error message. That means we need to change our return type. The values we are returning will be either an error message, or the path to the file. With this change, the type of our function will become:
| | handleArgs :: IO ( Either String FilePath ) |
Now we have a type for our function, and we need to write the code to make it happen. Let’s start by adding a helper function as a where binding. This will let us keep the code a bit more readable for now by keeping the part dealing with IO separate from the part of the code doing error handing. We will call our helper function parseArgs and it will handle the pure functional core of our function:
| | handleArgs :: IO ( Either String FilePath ) |
| | handleArgs = |
| | -- placeholder |
| | where |
| | parseArgs argumentList = |
| | case argumentList of |
| | [] -> Left "Error: No arguments provided!" |
| | (arg:args) -> Right arg |
This version of parseArgs will use pattern matching to detect if the argument list is empty. If so, we return an error message, and otherwise we return the front of the list.
The last thing we have to do is call parseArgs with the input list that we get when our program is running. We can call it with (<$>) , the same way we were previously calling head :
| | handleArgs :: IO ( Either String FilePath ) |
| | handleArgs = |
| | parseArgs <$> Env .getArgs |
| | where |
| | parseArgs argumentList = |
| | case argumentList of |
| | (arg:args) -> Right arg |
| | [] -> Left "no filename provided" |
We still have one last problem to think about. We will return an error message to our user if they don’t give us any files. If the user gives us more than one file path though, we’ll silently discard all but the first item. That’s not a crash, but it’s unexpected behavior that might not make a user very happy. Luckily, now that we have a version of our argument handler that can safely deal with the case where we don’t get any arguments, we also have a natural way to extend our program to also handle the case where we got more than one argument. See if you can update your version of the function to handle the case where we get more than one argument, and then check to see if it matches the example:
| | handleArgs :: IO ( Either String FilePath ) |
| | handleArgs = |
| | parseArgs <$> Env .getArgs |
| | where |
| | parseArgs argumentList = |
| | case argumentList of |
| | [fname] -> Right fname |
| | [] -> Left "no filename provided" |
| | _ -> Left "multiple files not supported" |
With these changes we no longer crash, and we can provide the user with helpful feedback if they give us some input that our program can’t handle. Let’s look at it in action:
| | user@host$ cabal run hcat |
| | Left "no filename provided" |
| | |
| | user@host$ cabal run hcat -- file1 file2 |
| | Left "multiple files not supported" |
| | |
| | user@host$ cabal run hcat -- file1 |
| | Right "file1" |
This version of our program is certainly an improvement over the earlier version. The program no longer crashes when we give it bad input, and the messages we get are helpful. We can still improve the quality of the output though. One problem with the current version of our program is that we’re printing out the Left and Right constructors from our Either value. The meaning of these values are clear to us since we built the program, but it might confuse a user. Let’s make one more change to the output so our messages are more meaningful to a casual user.
Just like with handleArgs we’ll start by adding a new helper. Instead of a pure function though, this helper will be a function that takes our result value and returns IO action to print an appropriate message to the screen:
| | runHCat :: IO () |
| | runHCat = |
| | -- placeholder, we'll fill this in shortly |
| | where |
| | displayMessage parsedArgument = |
| | case parsedArgument of |
| | Left errMessage -> |
| | putStrLn $ "Error: " <> errMessage |
| | Right filename -> |
| | putStrLn $ "Opening file: " <> filename |
In order to call displayMessage , we first need to parse our arguments, and then we need to pass the parsed argument to displayMessage and print out the appropriate value. That means we need to sequence the two IO actions using (>>=) .
The final version of our newly updated runHCat function will look like this:
| | runHCat :: IO () |
| | runHCat = |
| | handleArgs >>= displayMessage |
| | where |
| | displayMessage parsedArgument = |
| | case parsedArgument of |
| | Left errMessage -> |
| | putStrLn $ "Error: " <> errMessage |
| | Right filename -> |
| | putStrLn $ "Opening file: " <> filename |
Let’s see it in action by running through our list of examples:
| | user@host$ cabal run hcat -- file1 |
| | Opening file: file1 |
| | |
| | user@host$ cabal run hcat -- file1 file2 |
| | Error : multiple files not supported |
| | |
| | user@host$ cabal run hcat |
| | Error : no filename provided |
Reading the Contents of a File
Now that we’ve updated our program to allow us to get a file name from the command line, it’s time to start taking a look at how we can print the file to the screen. In the last chapter, you’ve already seen how we can use functions like readFile to get the contents of a file. We can apply what we’ve learned pretty trivially to get a working version of our application by reading the file that we get passed in and then printing it out.
| | runHCat :: IO () |
| | runHCat = |
| | handleArgs |
| | >>= \ fnameOrError -> |
| | case fnameOrError of |
| | Left err -> |
| | putStrLn $ "Error processing: " <> err |
| | Right fname -> |
| | readFile fname >>= putStrLn |
That’s it! If you build this you’ll see that program prints out the contents of the file, or an error message, just as we expected. There are still a couple of improvements that we can make to this program. In the rest of this section, we’ll look at some ways that we can improve our application, including making our code a bit more readable, handling IO errors, and using more efficient strings.
Dealing with IO Exceptions
Let’s start by looking at handling IO exceptions. If you try running your application and give it a path to a file that doesn’t exist, you might get something like this:
| | user@host$ cabal exec hcat -- /tmp/missing.file |
| | *** Exception: /tmp/missing.hs: |
| | openFile: does not exist (No such file or directory) |
It shouldn’t be surprising that we’d get some kind of error when we try to read a file that doesn’t exist. In this case, the error that we get is a particular type of exception called an IOError . We’ve seen other kinds of exceptions before in some of our examples earlier in this book, but until now we haven’t had a good way to deal with them. In this section, we’ll focus specifically on IOError type exceptions.
When we’re talking about IO errors there are two separate modules that we care about. System.IO.Error is where the IOError type is defined, along with several functions for creating, modifying, and handing IO errors. If you only care about IO errors, you can get by with just this module.
The Control.Exception module provides a much more general set of tools for working with all sorts of exceptions. The Exception type class is defined in this module, and we can use it for IO errors as well as exceptions defined by other libraries, exceptions raised in pure functions, or even exceptions we want to define ourselves.
In this section, we’ll focus on the exception handling tools provided by Control.Exception , but for now we’re going to limit ourselves to just looking at handling IO exceptions. We’ll also look at how to generate custom IO exceptions using the tools in System.IO.Error .
We’ll start by importing our modules:
| | import qualified Control.Exception as Exception |
| | import qualified System.IO.Error as IOError |
We’ll add some basic error handling to our runHCat . We’re not going to worry about recovering from our error, but instead of a nasty message. we’ll make the output friendlier and a bit nicer for the user to read.
The function that we want to use to catch an exception is, appropriately, called catch . Its type is catch :: Exception e => IO a -> (e -> IO a) -> IO a . The Exception type class is defined in Control.Exception . As you might expect, there is an instance for IOError provided for us. The catch function takes an IO action and an error handler. The error handler function tells catch what you want to do to recover from the error. It needs to take the error as input, and return some IO action that represents the recovered state.
Let’s take a look at how it works in practice:
| | runHCat :: IO () |
| | runHCat = Exception .catch |
| | ( handleArgs |
| | >>= \ arg -> |
| | case arg of |
| | Left err -> |
| | putStrLn $ "Error processing: " <> err |
| | Right fname -> |
| | readFile fname >>= putStrLn |
| | ) handleErr |
| | where |
| | handleErr :: IOError -> IO () |
| | handleErr e = putStrLn "I ran into an error:" >> print e |
In this example, we’ve taken our existing code and wrapped it in a call to catch . If any error, like a failure to open a file, happens during that IO action our handler, handleErr , will get called. Note that while we sometimes add type annotations purely for readability, in this example the annotation is required for handleErr so that the compiler knows what kind of Exception we’re catching.
Code like our previous example is common in production Haskell applications, but let’s look at some ways that we can refactor it to be a little nicer to read. We’ll start by adding a second helper function called handleIOError :
| | handleIOError :: IO () -> IO () |
| | handleIOError ioAction = Exception .catch ioAction handleErr |
Now we can pass our IO action into this handler function and have errors caught and handled automatically:
| | runHCat :: IO () |
| | runHCat = |
| | withErrorHandling $ |
| | handleArgs |
| | >>= \ arg -> |
| | case arg of |
| | Left err -> |
| | putStrLn $ "Error processing: " <> err |
| | Right fname -> |
| | readFile fname >>= putStrLn |
| | where |
| | withErrorHandling :: IO () -> IO () |
| | withErrorHandling ioAction = Exception .catch ioAction handleErr |
| | handleErr :: IOError -> IO () |
| | handleErr e = putStrLn "I ran into an error:" >> print e |
The way that we’ve refactored the code here allows us to easily add some context—in this case a context for error handling—to our function while still keeping the body of our function focused on the logic we care about. This sort of refactoring to add some context using a function like withSomeContext $ is a common technique for making programs more readable. We’ll see some more examples of this later on in this book.
We have one more refactoring opportunity that we can take to make the code a bit nicer to read. Our handleArgs function isn’t raising an exception. Instead, it’s returning an Either value to let us know if there’s been an error or not. Using Either is a great way to handle errors, but in our case it leaves us with a situation where we’re handling errors in two different ways. We could edit handleArgs to raise an exception, but instead, let’s look at another option that we could use even if we were using a function from a library that we don’t control. We’ll create a function to turn an Either into an IO Error.
We’ll call our example function eitherToErr and give it the type eitherToErr :: Show a => Either a b -> IO b . Handling our happy path where we have a Right value will be straightforward, so let’s add that as well:
| | eitherToErr :: Show a => Either a b -> IO b |
| | eitherToErr ( Right a) = return a |
If we have a Left value, we’ll need to construct an IO exception. To do that, we’ll use two functions from System.IO.Error . First, we need to add an IOError value. We can do that with the userError function, which creates one from a string. Once we have an error value, we need to throw it. When it comes to raising an exception, we have three separate options:
- ioError :: IOError -> IO a
- throwIO :: Exception e => e -> IO a
- throw :: Exception e => e -> a
The first of our functions, ioError , comes from the System.IO.Error module. It takes an IOError and returns an IO action. The type of IO action that it returns can be anything, since we’ll be raising an exception and never actually generating a value of that type.
The second of our functions, throwIO , is a bit more general than ioError . Instead of being limited to just IOError exceptions, throwIO can accept any type of exception, but it still returns an IO action.
The throw function from Control.Exception is the most general of our functions. It takes any kind of exception and raises it. Although we can use throw in place of throwIO and our program will still compile, the functions work a bit differently. The difference is tricky and we’ll gloss over the specifics for now, but in general if you’re working with IO it’s best to use throwIO , since it will behave the way you’d expect. Calls to throw may not always evaluate predictably when you’re dealing with IO actions.
Now that we know how to raise an exception, we can write the last part of our function. Since we want an IO error, we’ll call throwIO :
| | eitherToErr ( Left e) = |
| | Exception .throwIO . IOError .userError $ show e |
Putting this all together, we can use eitherToErr to make our program look a bit nicer. Notice in this final example we’ve also refactored our code to use the TypeApplications extension to eliminate the need for a separate handleErr function:
| | runHCat :: IO () |
| | runHCat = |
| | handleIOError $ |
| | handleArgs |
| | >>= eitherToErr |
| | >>= readFile |
| | >>= putStrLn |
| | where |
| | handleIOError :: IO () -> IO () |
| | handleIOError ioAction = |
| | Exception .catch ioAction $ |
| | \ e -> putStrLn "I ran into an error:" >> print @ IOError e |
| | |
| | eitherToErr :: Show a => Either a b -> IO b |
| | eitherToErr ( Right a) = return a |
| | eitherToErr ( Left e) = |
| | Exception .throwIO . IOError .userError $ show e |
Using this approach to handling exceptions, we can now write nice looking compact and expressive code while still handling potential errors and corner cases in our application.
Using Efficient Strings
The last change we’ll make to our basic application is a matter of efficiency. So far, we’ve been using functions from the System.IO module to read and write files using String values. This works for small applications without memory or performance constraints, but for real-world applications, strings can introduce unnecessary performance overhead. There are two common libraries that are used in many Haskell applications that make it easier and more efficient to work with strings.
The text [13] package gives us access to tools for representing and processing textual data. Working with Text is much more efficient than working with String values, and Text works natively with Unicode text data, which can be a source of errors when dealing with text represented as a String . In this chapter, we’ll be using two modules from the text package:
| | import qualified Data.Text as Text |
| | import qualified Data.Text.IO as TextIO |
The bytestring [14] package can help us deal with files more efficiently. Whereas the text package is focused on representing textual data, bytestring provides us with an efficient implementation of packed arrays of bytes. Byte arrays are the way that strings are represented in languages like C, and strict bytestrings can let us write Haskell applications with performance characteristics similar to C applications, while still having access to an API that gives us functions very similar to what we’d have when working with built-in String types.
The bytestring package provides a few different modules that we’ll use occasionally in this book. These are the ones that you’re most likely to see:
- Data.ByteString
- Data.ByteString.Lazy
- Data.ByteString.Char8
These modules all provide very similar interfaces over slightly different sorts of values, but with important differences. Data.ByteString.Lazy provides a lazily evaluated bytestring. These are useful when you’re not sure how much data you want to read off disk, or when you might not want all the data at once. This module provides the functions toStrict and fromStrict to convert back and forth between the standard strict ByteString values and the lazy ones. The bytestrings defined in Data.ByteString.Char8 are defined as a set of Char values instead of Word8 values. This means that you can easily convert back and forth between a String and a Data.ByteString.Char8.ByteString .
| ByteStrings and Unicode |
|---|
|
| It’s important to remember that ByteStrings only work with raw bytes and ASCII text. This makes Data.ByteString.Char8 dangerous because it gives you an interface that seems to work well with string data, but can be subtly incorrect when you need to deal with Unicode or other character encodings. In most cases, when dealing with text you should use the text package. You can encodeUtf8 and decodeUtf8 from Data.Text.Encoding to convert back and forth between ByteString and Text values. That said, Data.ByteString.Char8 can be useful when dealing with things like file formats that use ASCII text. |
For the rest of this chapter we’ll mostly be using Text values, with a couple of exceptions that we’ll note as we come across them. For the moment we’ll add Data.ByteString to our import list and we’ll get around to using it later on:
| | import qualified Data.ByteString as BS |
The functions that we get from text and bytestring typically look and act the same as their equivalent functions from System.IO except that they work with Text and ByteString values instead of String values. For example, instead of readFile :: FilePath -> IO String we can use TextIO.readFile :: FilePath -> IO Text.Text , and instead of putStrLn :: String -> IO () we can use BS.putStrLn :: BS.ByteString -> IO () . In fact, with just a couple of small changes we can update runHCat to be more efficient:
| | runHCat :: IO () |
| | runHCat = |
| | handleIOError $ |
| | handleArgs |
| | >>= eitherToErr |
| | >>= TextIO .readFile |
| | >>= TextIO .putStrLn |
| | where |
| | handleIOError :: IO () -> IO () |
| | handleIOError ioAction = |
| | Exception .catch ioAction $ |
| | \ e -> putStrLn "I ran into an error:" >> print @ IOError e |
We’ll continue to use bytestrings and text values throughout the rest of this book. Using these more efficent libraries for handling binary and text data can greatly improve the speed and memory requirements of any application that you build.