In the last section, as you worked with lists, you learned how the shape of a list was reflected in the way you worked with it using functions like (:) , head and tail . The idea that the shape of a data structure can be reflected in how we write code to use that data structure is a powerful one, and it turns out to have much more broad-reaching applicability than just lists.
Using pattern matching lets you write powerful expressions that match parts of a value based on its shape. You’ll learn several ways to use pattern matching in the remainder of this chapter. Let’s start by looking at how you can use pattern matching with functions, case statements, and let bindings.
In its simplest form, a pattern lets you replace a variable with a specific value. The pattern will match if the variable is equal to that value. It’s easier to understand with an example, so let’s use pattern matching to build a program that will give a special greeting to George:
| | customGreeting "George" = "Oh, hey George!" |
| | customGreeting name = "Hello, " <> name |
Notice that we have two implementations of the customGreeting function. The first one will be used if the name matches “George”, and otherwise we’ll fall through to our more general function. The matches happen top-to-bottom so if you instead have:
| | customGreeting name = "Hello, " <> name |
| | customGreeting "George" = "Oh, hey George!" |
Then you’d never get the custom greeting, since you will always hit the general case before matching on the more specific "George" case.
Of course you’re not limited to just pattern matching on strings. You can pattern match on most values, like numbers, booleans, even tuples and lists. Let’s look at a few more examples:
| | matchNumber 0 = "zero" |
| | matchNumber n = show n |
| | |
| | matchList [1,2,3] = "one, two, three" |
| | matchList list = show list |
| | |
| | matchTuple ( "hello" , "world" ) = "greetings" |
| | matchTuple tuple = show tuple |
| | |
| | matchBool True = "yep" |
| | matchBool bool = "this must be false" |
Although all of these examples follow a general pattern where we match on a special case first, and otherwise fall back to a catch-all case, this isn’t the only way that we can use pattern matching. We can match on several different cases. In the following example, we’ll create several different patterns as we try to match different parts of a tuple.
| | matchTuple ( "hello" , "world" ) = "Hello there, you great big world" |
| | matchTuple ( "hello" , name) = "Oh, hi there, " <> name |
| | matchTuple (salutation, "George" ) = "Oh! " <> salutation <> " George!" |
| | matchTuple n = show n |
Notice that the final pattern in all of these examples is a variable that can match any remaining values that haven’t already been matched. If we leave out the final function in the next example, we’ll end up with a partial function. As you learned earlier in this chapter, a partial function is one that doesn’t handle all of the possible input values it could get, and a total function is one that does handle all possible inputs. In this case, our partial function is caused by an incomplete pattern match. In other words, the compiler can’t find a pattern that matches the input to our function. Try entering it yourself and running it for several different variations.
| | λ partialFunc 0 = "I only work for zero!" |
| | λ partialFunc 0 |
| | "I only work for zero!" |
| | λ partialFunc 1 |
| | "*** Exception: <interactive>:75:1-39: Non-exhaustive |
| | patterns in function partialFunc |
You don’t need a wildcard value for a pattern if you’ve explicitly matched all the possible values a variable could have. For example, if we pattern match on a boolean value, we can provide cases for True and False to create a total function:
| | matchBool True = "True story!" |
| | matchBool False = "Sorry, this is just not True" |
At the end of this section, you’ll learn some ways to ask the compiler to help you catch potential bugs caused by incomplete patterns.
Destructuring Lists
Throughout this chapter you’ve been learning about how to construct lists, but taking elements out of a list has been somewhat inconvenient. Up until now, if you wanted to write a function that used elements from a list, you would often end up writing the same boilerplate code that would
- Check to see if the current list is empty (and if so return some base value),
- Use the head function to get the first element of the list,
- Use the tail function to get the rest of the list,
- Possibly do some computation with the head of the list, and
- Make a recursive call with the tail of the list.
With pattern matching, this becomes much easier. Let’s look at an example:
| | addValues [] = 0 |
| | addValues (first:rest) = first + (addValues rest) |
In this example, we’re pattern matching over lists in two different ways. In the first case, we pattern match to quickly identify our base case where we have an empty list, and return 0. If we don’t have an empty list, we use pattern matching to extract the head and tail of the list, which in this case we’re calling first and rest .
You can also use pattern matching outside of the parameters of a function. One useful place to use pattern matching is in let bindings. Imagine that you have a function, fancyNumbers , which given some number, n, gives you back the nth Fibonacci number and the nth prime number:
| | λ fancyNumbers n = (zip fibs primes) !! n |
| | λ fancyNumbers 27 |
| | (317811,103) |
If you wanted to write a function that works with this data, you can use pattern matching on the tuple within a let expression to help make your code a bit easier to read. Let’s look at an example:
| | printFancy n = |
| | let (fib, prime) = fancyNumbers n |
| | fib' = show fib |
| | prime' = show prime |
| | in "The fibonacci number is: " <> fib' <> " and the prime is: " <> prime' |
In some cases you want to pattern match, but also get the original value that hasn’t been deconstructed. You can do that by adding a variable before your pattern followed by an @ symbol. As an example, try copying in the following function that will accept a pair and replace the first or second elements if they match some special case, and otherwise will return the original pair:
| | modifyPair p@(a,b) |
| | | a == "Hello" = "this is a salutation" |
| | | b == "George" = "this is a message for George" |
| | | otherwise = "I don't know what " <> show p <> " means" |
| | λ modifyPair ( "Hello" , "George" ) |
| | "this is a salutation" |
| | λ modifyPair ( "What's going on" , "George" ) |
| | "this is a message for George" |
| | λ modifyPair ( "this is" , "a message" ) |
| | "I don't know what ( \" this is \" , \" a message \" ) means" |
Matching the entire element along with a pattern is particularly useful when you have a large number of items you are matching out of a complex data structure.
A special pattern that you can use is the wildcard pattern. A wildcard pattern will match any value, like a variable would, but without binding the value to a variable in your function. It’s a useful way of saying, “a value should be here, but I don’t care about it.” One place this is useful is if you want to get specific elements out of a tuple. To use a wildcard pattern, use an underscore instead of a value or variable name. The fst and snd functions in Prelude give you the first and second elements of a two-element tuple. Let’s use the wildcard pattern to implement versions of these functions that work for a triple:
| | module Tuples where |
| | import Prelude hiding ( fst , snd ) |
| | |
| | fst (x, _ , _ ) = x |
| | snd ( _ , x, _ ) = x |
| | thrd ( _ , _ , x) = x |
| | λ map ($ (1,2,3)) [fst, snd, thrd] |
| | [1,2,3] |
In some cases, you might want to both ignore a particular value, as well as communicate to other developers working in your codebase what that value should be. In those cases, it’s common to use a variable name that starts with an underscore prefix:
| | printHead [] = "empty!" |
| | printHead lst@(hd:_tail) = |
| | "the head of " <> (show lst) <> " is " <> show hd |
In this version of the function, we are using the name _tail to communicate to any future developer reading the code that the value is the tail of a list, and also that it’s not a value we are going to be using.
You’ve seen that patterns allow you to branch at the function level: by using patterns for your function arguments you can create different implementations of your function for different inputs. Haskell offers another way to do this within a single function, using case statements. A case statement allows you to pattern match on a value inside of your function. You can combine pattern matching with guards to create expressive branching conditionals based on the values in your function.
In the simple case, a case statement looks much like a switch statement in other languages. Let’s look at an example program that will tell us some of our friend’s favorite foods using a case statement:
| | favoriteFood person = |
| | case person of |
| | "Ren" -> "Tofu" |
| | "Rebecca" -> "Falafel" |
| | "George" -> "Banana" |
| | name -> "I Don't Know what " <> name <> " likes!" |
You can also combine case statements with guards. To illustrate this, let’s look at a different example. Copy the next example into a new file so you can try running it in ghci :
| | handleNums l = |
| | case l of |
| | [] -> "An empty list" |
| | [x] | x == 0 -> "a list called: [0]" |
| | | x == 1 -> "a singular list of [1]" |
| | | even x -> "a singleton list containing an even number" |
| | | otherwise -> "the list contains " <> (show x) |
| | _list -> "the list has more than 1 element" |
Mixing case statements with guards can sometimes allow you to write terse code when you are dealing with complex business logic, but be careful to not use so many clauses in one place that it makes your code less readable.
Getting Warned About Incomplete Patterns
Before we move on from pattern matching, let’s take a moment to look again at the problem of non-exhaustive patterns. Since we first introduced the idea of non-exhaustive patterns earlier in the section, we’ve been careful to avoid them in all of the examples. It’s a good idea to avoid non-exhaustive patterns whenever you can, and it’s rare for there to be a situation where you can’t avoid them.
There are two situations where you might find yourself tempted to have an incomplete pattern: when you are confident that the patterns you are omitting won’t happen, and when you are still actively working on some code and haven’t yet had an opportunity to implement the missing code.
When you are confident that your incomplete pattern isn’t really incomplete, it can be tempting to leave it in. Once you learn how to create your own types and work with modules you’ll be better equipped to manage this situation. For now, an alternative is to use the error function. As you might guess, error causes your program to fail with a runtime error. Let’s revisit our original partial function example and look at how we can use error :
| | module Main where |
| | |
| | partialFunction 0 = "I only work for 0" |
| | partialFunction impossibleValue = error $ |
| | "I only work with 0 but I was called with " <> show impossibleValue |
| | |
| | main = putStrLn $ partialFunction 3 |
If you compile and run this program, you’ll see that it still crashes, but the output looks a bit different:
| | user@host$ ghc Main.hs |
| | user@host$ ./Main |
| | Main: I only work with 0 but I was called with 3 |
| | CallStack (from HasCallStack): |
| | error, called at Main.hs:5:3 in main:Main |
In this example, we haven’t prevented our program from crashing, but we have at least been explicit about the fact that we expect to crash, and we’ve gotten some useful information. The fact that your error can be explicit and carry an error message often makes error a better choice than an incomplete pattern for impossible cases.
Being explicit about intentionally incomplete patterns is one thing, but often times we have incomplete pattern matches on accident. This can be because we’re actively working on the code and haven’t written a match yet, or we overlooked a potential value. It’s even possible that your code was complete when you originally wrote it, but someone else made some changes and introduced some additional values, and now, once-working code has some incomplete patterns lurking around waiting to cause trouble. These sorts of errors can lurk in code for a long time until they finally manifest themselves as a runtime error. Thankfully, the compiler can help us track them down before we ship errors to our users. All we need to do is enable the warnings.
In most projects, you’ll enable or disable warnings at the project level. You’ll learn how to customize the options that are used when building an entire project when you learn about cabal projects . For the kind of small projects you’ll be building over the next few chapters, you can also enable and disable warnings directly from the command line when you build your programs with ghc or load them into ghci . To start, let’s recreate the incomplete pattern we had earlier by removing the explicit error case from our partial function:
| | module Main where |
| | |
| | partialFunction 0 = "I only work for 0" |
| | main = putStrLn $ partialFunction 0 |
If we compile this without passing in any additional flags, we won’t get a warning:
| | user@host$ ghc Main.hs |
| | [1 of 1] Compiling Main ( Main.hs, Main.o ) |
| | Linking Main ... |
| | user@host$ ./Main |
| | I only work for 0 |
One way that we can get warnings about non-exhaustive patterns is to ask for them explicitly by passing in the -Wincomplete-patterns option to ghc before the name of the file we’re compiling:
| | user@host$ ghc - Wincomplete -patterns Main .hs |
| | [1 of 1] Compiling Main ( Main .hs, Main .o ) |
| | |
| | Main .hs:3:1: warning: [- Wincomplete -patterns] |
| | Pattern match(es) are non-exhaustive |
| | In an equation for ‘ partialFunction ’ : |
| | Patterns not matched: p where p is not one of {0} |
| | | |
| | 3 | partialFunction 0 = "I only work for 0" |
| | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| | Linking Main ... |
| | user@host$ ./ Main |
| | I only work for 0 |
When we turn this flag on, the compiler helpfully points out exactly where we’ve used a non-exhaustive pattern. Warnings don’t stop the program from compiling though, and you’ll notice if you follow along with this example that you still end up with an application that you can run.
Next, let’s try running our program in ghci . We’ll start by launching ghci normally without any arguments:
| | user@host$ ghci |
When we load our file, we don’t get any warnings:
| | λ :load Main .hs |
| | [1 of 1] Compiling Main ( Main .hs, interpreted ) |
| | Ok , one module loaded. |
One option that we have is to pass -Wincomplete-patterns to ghci on the command line when we start it:
| | ghci -Wincomplete-patterns |
Now when we load our file in ghci we’ll see the same warnings that we saw when we compiled the program:
| | λ :load Main .hs |
| | [1 of 1] Compiling Main ( Main .hs, interpreted ) |
| | |
| | Main .hs:3:1: warning: [- Wincomplete -patterns] |
| | Pattern match(es) are non-exhaustive |
| | In an equation for ‘ partialFunction ’ : |
| | Patterns not matched: p where p is not one of {0} |
| | | |
| | 3 | partialFunction 0 = "I only work for 0" |
| | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| | Ok , one module loaded. |
If you like to keep a long-running ghci session going, you might want to toggle warnings on and off as you are developing without having to restart the program. You can do that with the :set command. For example, we can temporarily disable the warning by passing in -Wno-incomplete-patterns . If we do that, and reload the file, you’ll see we stop getting warnings about the incomplete pattern:
| | λ :set - Wno -incomplete-patterns |
| | λ :load Main .hs |
| | [1 of 1] Compiling Main ( Main .hs, interpreted ) |
| | Ok , one module loaded. |
We can also turn them back on with :set :
| | λ :set - Wincomplete -patterns |
| | λ :load Main .hs |
| | [1 of 1] Compiling Main ( Main .hs, interpreted ) |
| | |
| | Main .hs:3:1: warning: [- Wincomplete -patterns] |
| | Pattern match(es) are non-exhaustive |
| | In an equation for ‘ partialFunction ’ : |
| | Patterns not matched: p where p is not one of {0} |
| | | |
| | 3 | partialFunction 0 = "I only work for 0" |
| | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| | Ok , one module loaded. |
GHC supports quite a lot of different warnings that can be individually enabled and disabled. The pattern we just used holds for all of them. You can enable a warning with -Wwarning-name and disable it with -Wno-warning-name . If you want to enable all warnings about things that might be problems with your program, you can also use -Wall . We won’t cover -Wall for now, since it will warn us about some things that we haven’t learned how to fix yet.