In this chapter, we’ll take a look at the syntax that enables you to write Haskell functions in a readable and sensible manner. We’ll look at how to quickly deconstruct values, avoid big if else chains, and store the results of intermediate computations so that you can reuse them multiple times.

Pattern Matching

Pattern matching is used to specify patterns to which some data should conform and to deconstruct the data according to those patterns.

image with no caption

When defining functions in Haskell, you can create separate function bodies for different patterns. This leads to simple, readable code. You can pattern match on pretty much any data type—numbers, characters, lists, tuples, and so on. For example, let’s write a simple function that checks if the number we pass to it is a 7:

lucky :: Int -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry, you're out of luck, pal!"

When you call lucky , the patterns will be checked from top to bottom. When the passed argument conforms to a specified pattern, the corresponding function body will be used. The only way a number can conform to the first pattern here is if it is a 7. In that case, the function body "LUCKY NUMBER SEVEN!" is used. If it’s not a 7, it falls through to the second pattern, which matches anything and binds it to x .

When we use a name that starts with a lowercase letter (like x , y , or myNumber ) in our pattern instead of an actual value (like 7 ), it will act as a catchall pattern. That pattern will always match the supplied value, and we will be able to refer to that value by the name that we used for the pattern.

The sample function could have also been easily implemented by using an if expression. However, what if we wanted to write a function that takes a number and prints it out as a word if it’s between 1 and 5; otherwise, it prints "Not between 1 and 5" ? Without pattern matching, we would need to make a pretty convoluted if/then/else tree. However, pattern matching makes this a simple function to write:

sayMe :: Int -> String
sayMe 1 = "One!"
sayMe 2 = "Two!"
sayMe 3 = "Three!"
sayMe 4 = "Four!"
sayMe 5 = "Five!"
sayMe x = "Not between 1 and 5"

Note that if we moved the last pattern ( sayMe x ) to the top, the function would always print "Not between 1 and 5" , because the numbers wouldn’t have a chance to fall through and be checked for any other patterns.

Remember the factorial function we implemented in the previous chapter? We defined the factorial of a number n as product [1..n] . We can also define a factorial function recursively . A function is defined recursively if it calls itself inside its own definition. The factorial function is usually defined this way in mathematics. We start by saying that the factorial of 0 is 1. Then we state that the factorial of any positive integer is that integer multiplied by the factorial of its predecessor. Here’s how that looks translated into Haskell terms:

factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)

This is the first time we’ve defined a function recursively. Recursion is important in Haskell, and we’ll take a closer look at it in Chapter 4 .

Pattern matching can also fail. For instance, we can define a function like this:

charName :: Char -> String
charName 'a' = "Albert"
charName 'b' = "Broseph"
charName 'c' = "Cecil"

This function seems to work fine at first. However, if we try to call it with an input that it didn’t expect, we get an error:

ghci> charName 'a'
"Albert"
ghci> charName 'b'
"Broseph"
ghci> charName 'h'
"*** Exception: tut.hs:(53,0)-(55,21): Non-exhaustive patterns in function charName

It complains that we have “non-exhaustive patterns,” and rightfully so. When making patterns, we should always include a catchall pattern at the end so our program doesn’t crash if we get some unexpected input.

Pattern Matching with Tuples

Pattern matching can also be used on tuples. What if we wanted to write a function that takes two vectors in 2D space (represented as pairs) and adds them together? (To add two vectors, we add their x components separately and their y components separately.) Here’s how we might have done this if we didn’t know about pattern matching:

addVectors :: (Double, Double) -> (Double, Double) -> (Double, Double)
addVectors a b = (fst a + fst b, snd a + snd b)

Well, that works, but there’s a better way to do it. Let’s modify the function so that it uses pattern matching:

addVectors :: (Double, Double) -> (Double, Double) -> (Double, Double)
addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)

This is much better. It makes it clear that the parameters are tuples, and increases readability by giving names to the tuple components right away. Note that this is already a catchall pattern. The type of addVectors is the same in both cases, so we are guaranteed to get two pairs as parameters:

ghci> :t addVectors
addVectors :: (Double, Double) -> (Double, Double) -> (Double, Double)

fst and snd extract the components of pairs. But what about triples? Well, there are no provided functions to extract the third component in a triple, but we can make our own:

first :: (a, b, c) -> a
first (x, _, _) = x

second :: (a, b, c) -> b
second (_, y, _) = y

third :: (a, b, c) -> c
third (_, _, z) = z

The _ character means the same thing it does in list comprehensions. We really don’t care about that part, so we just use a _ to represent a generic variable.

Pattern Matching with Lists and List Comprehensions

You can also use pattern matching in list comprehensions, like this:

ghci> let xs = [(1,3),(4,3),(2,4),(5,3),(5,6),(3,1)]
ghci> [a+b | (a, b) <- xs]
[4,7,6,8,11,4]

If a pattern match fails, the list comprehension will just move on to the next element, and the element that failed won’t be included in the resulting list.

Regular lists can also be used in pattern matching. You can match with the empty list [] or any pattern that involves : and the empty list. (Remember that [1,2,3] is just syntactic sugar for 1:2:3:[] .) A pattern like x:xs will bind the head of the list to x and the rest of it to xs . If the list has only a single element, then xs will simply be the empty list.

Note

Haskell programmers use the x:xs pattern often, especially with recursive functions. However, patterns that include the : character will match only against lists of length one or more.

Now that we’ve looked at how to pattern match against lists, let’s make our own implementation of the head function:

head' :: [a] -> a
head' [] = error "Can't call head on an empty list, dummy!"
head' (x:_) = x

After loading the function, we can test it, like this:

ghci> head' [4,5,6]
4
ghci> head' "Hello"
'H'

Notice that if we want to bind something to several variables (even if one of them is just _ ), we must surround them in parentheses so Haskell can properly parse them.

Also notice the use of the error function. This function takes a string as an argument and generates a runtime error using that string. It essentially crashes your program, so it’s not good to use it too much. (But calling head on an empty list just doesn’t make sense!)

As another example, let’s write a simple function that takes a list and prints its elements out in a wordy, inconvenient format:

tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
tell (x:[]) = "The list has one element: " ++ show x
tell (x:y:[]) = "The list has two elements: " ++ show x ++ " and " ++ show y
tell (x:y:_) = "This list is long. The first two elements are: " ++ show x
               ++ " and " ++ show y

Note that (x:[]) and (x:y:[]) could be rewritten as [x] and [x,y] . However, we can’t rewrite (x:y:_) using square brackets, because it matches any list of length 2 or more.

Here are some examples of using this function:

ghci> tell [1]
"The list has one element: 1"
ghci> tell [True,False]
"The list has two elements: True and False"
ghci> tell [1,2,3,4]
"This list is long. The first two elements are: 1 and 2"
ghci> tell []
"The list is empty"

The tell function is safe to use because it can match to the empty list, a singleton list, a list with two elements, and a list with more than two elements. It knows how to handle lists of any length, and so it will always return a useful value.

How about if instead we defined a function that only knows how to handle lists with three elements? Here’s an example of such a function:

badAdd :: (Num a) => [a] -> a
badAdd (x:y:z:[]) = x + y + z

Here’s what happens when we give it a list that it doesn’t expect:

ghci> badAdd [100,20]
*** Exception: examples.hs:8:0-25: Non-exhaustive patterns in function badAdd

Yikes! Not cool! If this happened inside a compiled program instead of in GHCi, the program would crash.

One final thing to note about pattern matching with lists: You can’t use the ++ operator in pattern matches. (Remember that the ++ operator joins two lists into one.) For instance, if you tried to pattern match against (xs ++ ys) , Haskell wouldn’t be able to tell what would be in the xs list and what would be in the ys list. Though it seems logical to match stuff against (xs ++ [x,y,z]) , or even just (xs ++ [x]) , because of the nature of lists, you can’t.

As-patterns

There’s also a special type of pattern called an as-pattern . As-patterns allow you to break up an item according to a pattern, while still keeping a reference to the entire original item. To create an as-pattern, precede a regular pattern with a name and an @ character.

For instance, we can create the following as-pattern: xs@(x:y:ys) . This pattern will match exactly the same lists that x:y:ys would, but you can easily access the entire original list using xs , instead of needing to type out x:y:ys every time. Here’s an example of a simple function that uses an as-pattern:

firstLetter :: String -> String
firstLetter "" = "Empty string, whoops!"
firstLetter all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]

After loading the function, we can test it as follows:

ghci> firstLetter "Dracula"
"The first letter of Dracula is D"

Guards, Guards!

We use patterns to check if the values passed to our functions are constructed in a certain way. We use guards when we want our function to check if some property of those passed values is true or false. That sounds a lot like an if expression, and it is very similar. However, guards are a lot more readable when you have several conditions, and they play nicely with patterns.

Let’s dive in and write a function that uses guards. This function will tell you different things depending on your body mass index (BMI). Your BMI is calculated by dividing your weight (in kilograms) by your height (in meters) squared. If your BMI is less than 18.5, you’re considered underweight. If it’s anywhere from 18.5 to 25, you’re considered normal. A BMI of 25 to 30 is overweight, and more than 30 is obese. (Note that this function won’t actually calculate your BMI; it just takes it as an argument and then tells you something.) Here’s the function:

image with no caption

bmiTell :: => Double -> String
bmiTell bm
    | bmi <= 18.5 = "You're underweight, eat more!"
    | bmi <= 25.0 = "Looking good!"
    | bmi <= 30.0 = "You're overweight. Let's work out together!"
    | otherwise   = "You're obese. Go see a doctor."

A guard is indicated by a pipe character ( | ), followed by a Boolean expression, followed by the function body that will be used if that expression evaluates to True . If the expression evaluates to False , the function drops through to the next guard, and the process repeats. Guards must be indented by at least one space. (I like to indent them by four spaces so that the code is more readable.)

For instance, if we call this function with a BMI of 24.3, it will first check if that’s less than or equal to 18.5. Because it isn’t, it falls through to the next guard. The check is carried out with the second guard, and because 24.3 is less than 25.0, the second string is returned.

Guards are very reminiscent of a big if/else tree in imperative languages, though they’re far more readable. While big if/else trees are usually frowned upon, sometimes a problem is defined in such a discrete way that you can’t get around them. Guards are a very nice alternative in these cases.

Many times, the last guard in a function is otherwise , which catches everything. If all the guards in a function evaluate to False , and we haven’t provided an otherwise catchall guard, evaluation falls through to the next pattern. (This is how patterns and guards play nicely together.) If no suitable guards or patterns are found, an error is thrown.

Of course, we can also use guards with functions that take multiple parameters. Let’s modify bmiTell so that it takes a height and weight, and calculates the BMI for us:

bmiTell :: Double -> Double -> String
bmiTell weight height
    | weight / height ^ 2 <= 18.5 = "You're underweight, eat more!"
    | weight / height ^ 2 <= 25.0 = "Looking good!"
    | weight / height ^ 2 <= 30.0 = "You're overweight! Let's work out together!"
    | otherwise                   = "You're obese. Go see a doctor."

Now, let’s try it out:

ghci> bmiTell 85 1.90
"Looking good!"

Nice, Haskell says I look good.

Note

A common newbie mistake is to put an equal sign ( = ) after the function name and parameters, before the first guard. This will cause a syntax error.

As another simple example, let’s implement our own max function to compare two items and return the larger one:

max' :: (Ord a) => a -> a -> a max' a b
    | a <= b    = b
    | otherwise = a

We can also implement our own compare function using guards:

myCompare :: (Ord a) => a -> a -> Ordering
a `myCompare` b
    | a == b    = EQ
    | a <= b     = LT
    | otherwise = GT
ghci> 3 `myCompare` 2
GT

Note

Not only can we call functions as infix with backticks, we can also define them using backticks. Sometimes this makes them easier to read.

where?!

When programming, we usually want to avoid calculating the same value over and over again. It’s much easier to calculate something only once and store the result. In imperative programming languages, you would solve this problem by storing the result of a computation in a variable. In this section, you’ll learn how to use Haskell’s where keyword to store the results of intermediate computations, which provides similar functionality.

In the previous section, we defined a BMI calculator function like this:

bmiTell :: Double -> Double -> String
bmiTell weight height
    | weight / height ^ 2 <= 18.5 = "You're underweight, eat more!"
    | weight / height ^ 2 <= 25.0 = "Looking good!"
    | weight / height ^ 2 <= 30.0 = "You're overweight. Let's work out together!"
    | otherwise                   = "You're obese. Go see a doctor"

Notice that we repeat the BMI calculation three times in this code. We can avoid this by using the where keyword to bind that value to a variable and then using that variable in place of the BMI calculation, like this:

bmiTell :: Double -> Double -> String
bmiTell weight height
    | bmi <= 18.5 = "You're underweight, eat more!"
    | bmi <= 25.0 = "Looking good!"
    | bmi <= 30.0 = "You're overweight. Let's work out together!"
    | otherwise   = "You're obese. Go see a doctor."
    where bmi = weight / height ^ 2

We put the where keyword after the guards and then use it to define one or more variables or functions. These names are visible across all the guards. If we decide that we want to calculate BMI a bit differently, we need to change it only once. This technique also improves readability by giving names to things, and it can even make our programs faster, since our values are calculated just once.

If we wanted to, we could even go a bit overboard and write our function like this:

bmiTell :: Double -> Double -> String
bmiTell weight height
    | bmi <= skinny = "You're underweight, eat more!"
    | bmi <= normal = "Looking good!"
    | bmi <= fat    = "You're overweight. Let's work out together!"
    | otherwise     = "You're obese. Go see a doctor."
    where bmi = weight / height ^ 2
          skinny = 18.5
          normal = 25.0
          fat = 30.0

Note

Notice that all the variable names are aligned in a single column. If you don’t align them like this, Haskell will get confused, and it won’t know that they’re all part of the same block.

where’s Scope

The variables we define in the where section of a function are visible only to that function, so we don’t need to worry about them polluting the namespace of other functions. If we want to use a variable like this in several different functions, we must define it globally.

Also, where bindings are not shared across function bodies of different patterns. For instance, suppose we want to write a function that takes a name and greets the person nicely if it recognizes that name, but not so nicely if it doesn’t. We might define it like this:

greet :: String -> String greet "Juan" = niceGreeting ++ " Juan!"
greet "Fernando" = niceGreeting ++ " Fernando!"
greet name = badGreeting ++ " " ++ name
    where niceGreeting = "Hello! So very nice to see you,"
          badGreeting = "Oh! Pfft. It's you."

This function won’t work as written. Because where bindings aren’t shared across function bodies of different patterns, only the last function body sees the greetings defined by the where binding. To make this function work correctly, badGreeting and niceGreeting must be defined globally, like this:

badGreeting :: String
badGreeting = "Oh! Pfft. It's you."

niceGreeting :: String
niceGreeting = "Hello! So very nice to see you,"

greet :: String -> String
greet "Juan" = niceGreeting ++ " Juan!"
greet "Fernando" = niceGreeting ++ " Fernando!"
greet name = badGreeting ++ " " ++ name

Pattern Matching with where

You can also use where bindings to pattern match. We could have written the where section of our BMI function like this:

...
    where bmi = weight / height ^ 2
          (skinny, normal, fat) = (18.5, 25.0, 30.0)

As an example of this technique, let’s write a function that gets a first name and last name, and returns the initials:

initials :: String -> String -> String
initials firstname lastname = [f] ++ ". " ++ [l] ++ "."
    where (f:_) = firstname
          (l:_) = lastname

We could have also done this pattern matching directly in the function’s parameters (it would have been shorter and more readable), but this example shows that it’s possible to do it in the where bindings as well.

Functions in where Blocks

Just as we’ve defined constants in where blocks, we can also define functions. Staying true to our healthy programming theme, let’s make a function that takes a list of weight/height pairs and returns a list of BMIs:

calcBmis :: [(Double, Double)] -> [Double]
calcBmis xs = [bmi w h | (w, h) <- xs]
    where bmi weight height = weight / height ^ 2

And that’s all there is to it! The reason we needed to introduce bmi as a function in this example is that we can’t just calculate one BMI from the function’s parameters. We need to examine the list passed to the function, and there’s a different BMI for every pair in there.

let It Be

let expressions are very similar to where bindings. where allows you bind to variables at the end of a function, and those variables are visible to the entire function, including all its guards. let expressions, on the other hand, allow you to bind to variables anywhere and are expressions themselves. However, they’re very local, and they don’t span across guards. Just like any Haskell construct that’s used to bind values to names, let expressions can be used in pattern matching.

image with no caption

Now let’s see let in action. The following function returns a cylinder’s surface area, based on its height and radius:

cylinder :: Double -> Double -> Double
cylinder r h =
    let sideArea = 2 * pi * r * h
        topArea = pi * r ^ 2
    in  sideArea + 2 * topArea

let expressions take the form of let <bindings> in <expression> . The variables that you define with let are visible within the entire let expression.

Yes, we could have also defined this with a where binding. So what’s the difference between the two? At first, it seems that the only difference is that let puts the bindings first and the expression later, whereas it’s the other way around with where .

Really, the main difference between the two is that let expressions are . . . well . . . expressions, whereas where bindings aren’t. If something is an expression, then it has a value. "boo!" is an expression, as are 3 + 5 and head [1,2,3] . This means that you can use let expressions almost anywhere in your code, like this:

ghci> 4 * (let a = 9 in a + 1) + 2
42

Here are a few other useful ways to use let expressions:

  • They can be used to introduce functions in a local scope:

    ghci> [let square x = x * x in (square 5, square 3, square 2)]
    [(25,9,4)]
  • They can be separated with semicolons, which is helpful when you want to bind several variables inline and can’t align them in columns:

    ghci> (let a = 100; b = 200; c = 300 in a*b*c,
     let foo="Hey "; bar = "there!" in foo ++ bar)
    (6000000,"Hey there!")
  • Pattern matching with let expressions can be very useful for quickly dismantling a tuple into components and binding those components to names, like this:

    ghci> (let (a, b, c) = (1, 2, 3) in a+b+c) * 100
    600

    Here, we use a let expression with a pattern match to deconstruct the triple (1,2,3) . We call its first component a , its second component b , and its third component c . The in a+b+c part says that the whole let expression will have the value of a+b+c . Finally, we multiply that value by 100 .

  • You can use let expressions inside list comprehensions. We’ll take a closer look at this next.

If let expressions are so cool, why not use them all the time? Well, since let expressions are expressions, and are fairly local in their scope, they can’t be used across guards. Also, some people prefer where bindings because their variables are defined after the function they’re being used in, rather than before. This allows the function body to be closer to its name and type declaration, which can make for more readable code.

let in List Comprehensions

Let’s rewrite our previous example of calculating lists of weight/height pairs, but we’ll use a let expression inside a list comprehension instead of defining an auxiliary function with where :

calcBmis :: [(Double, Double)] -> [Double]
calcBmis xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2]

Each time the list comprehension takes a tuple from the original list and binds its components to w and h , the let expression binds w / h ^ 2 to the name bmi . Then we just present bmi as the output of the list comprehension.

We include a let inside a list comprehension much as we would use a predicate, but instead of filtering the list, it only binds values to names. The names defined in this let are visible to the output (the part before the | ) and everything in the list comprehension that comes after the let . So, using this technique, we could make our function return only the BMIs of fat people, like this:

calcBmis :: [(Double, Double)] -> [Double]
calcBmis xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2, bmi > 25.0]

The (w, h) <- xs part of the list comprehension is called the generator . We can’t refer to the bmi variable in the generator, because that is defined prior to the let binding.

let in GHCi

The in part of the binding can also be omitted when defining functions and constants directly in GHCi. If we do that, then the names will be visible throughout the entire interactive session:

ghci> let zoot x y z = x * y + z
ghci> zoot 3 9 2
29
ghci> let boot x y z = x * y + z in boot 3 4 2
14
ghci> boot
<interactive>:1:0: Not in scope: `boot'

Because we omitted the in part in our first line, GHCi knows that we’re not using zoot in that line, so it remembers it for the rest of the session. However, in the second let expression, we included the in part and called boot immediately with some parameters. A let expression that doesn’t leave out the in part is an expression in itself and represents a value, so GHCi just printed that value.

case Expressions

case expressions allow you to execute blocks of code for specific values of a particular variable. Essentially, they are a way to use pattern matching almost anywhere in your code. Many languages (like C, C++, and Java) have some kind of case statement, so you may already be familiar with the concept.

image with no caption

Haskell takes that concept and one-ups it. As the name implies, case expressions are expressions, much like if else expressions and let expressions. Not only can we evaluate expressions based on the possible cases of the value of a variable, we can also do pattern matching.

This is very similar to performing pattern matching on parameters in function definitions, where you take a value, pattern match it, and evaluate pieces of code based on that value. In fact, that kind of pattern matching is just syntactic sugar for case expressions. For example, the following two pieces of code do the same thing and are interchangeable:

head' :: [a] -> a
head' [] = error "No head for empty lists!"
head' (x:_) = x
head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists!"
                      (x:_) -> x

Here’s the syntax for a case expression:

case expression of pattern -> result
                   pattern -> result
                   pattern -> result
                   ...

This is pretty simple. The first pattern that matches the expression is used. If it falls through the whole case expression and no suitable pattern is found, a runtime error occurs.

Pattern matching on function parameters can be done only when defining functions, but case expressions can be used anywhere. For instance, you can use them to perform pattern matching in the middle of an expression, like this:

describeList :: [a] -> String
describeList ls = "The list is " ++ case ls of [] -> "empty."
                                               [x] -> "a singleton list."
                                               xs -> "a longer list."

Here, the case expression works like this: ls is first checked against the pattern of an empty list. If ls is empty, the whole case expression then assumes the value of "empty" . If ls is not an empty list, then it’s checked against the pattern of a list with a single element. If the pattern match succeeds, the case expression then has the value of "a singleton list" . If neither of those two patterns match, then the catchall pattern, xs , applies. Finally, the result of the case expression is joined together with the string "The list is" . Each case expression represents a value. That’s why we were able to use ++ between the string "The list is" and our case expression.

Because pattern matching in function definitions is the same as using case expressions, we could have also defined the describeList function like this:

describeList :: [a] -> String
describeList ls = "The list is " ++ what ls
    where what [] = "empty."
          what [x] = "a singleton list."
          what xs = "a longer list."

This function acts just like the one in the previous example, although we used a different syntactic construct to define it. The function what gets called with ls , and then the usual pattern-matching action takes place. Once this function returns a string, it’s joined with "The list is" .