In this chapter, we’ll take a look at recursion. We’ll learn why it’s important in Haskell programming and how we can find very concise and elegant solutions to problems by thinking recursively.

Recursion is a way of defining functions in which a function is applied inside its own definition. In other words, the function calls itself. If you still don’t know what recursion is, read this sentence. (Haha! Just kidding!)

image with no caption

Kidding aside, the strategy of a recursively defined function is to break down the problem at hand into smaller problems of the same kind and then try to solve those subproblems, breaking them down further if necessary. Eventually we reach the base case (or base cases) of the problem, which can’t be broken down any more and whose solutions need to be explicitly (non-recursively) defined by the programmer.

Definitions in mathematics are often recursive. For instance, we can specify the Fibonacci sequence recursively as follows: We define the first two Fibonacci numbers directly by saying that F (0) = 0 and F (1) = 1, meaning that the zeroth and first Fibonacci numbers are 0 and 1, respectively. These are our base cases.

Then we specify that for any natural number other than 0 or 1, the corresponding Fibonacci number is the sum of the previous two Fibonacci numbers. In other words, F(n) = F ( n -1) + F ( n -2). For example, F (3) is F (2) + F (1), which in turn breaks down as ( F (1) + F (0)) + F (1). Because we’ve now come down to nothing but nonrecursively defined Fibonacci numbers, we can safely say that the value of F (3) is 2.

Recursion is important in Haskell because, unlike with imperative languages, you do computations in Haskell by declaring what something is rather than specifying how you compute it. That’s why Haskell isn’t about issuing your computer a sequence of steps to execute, but rather about directly defining what the desired result is, often in a recursive manner.

Maximum Awesome

Let’s take a look at an existing Haskell function and see how we can write the function ourselves if we shift our brains into the “R” gear (for “recursion”).

The maximum function takes a list of things that can be put in order (i.e., instances of the Ord type class) and returns the largest of them. It can be expressed very elegantly using recursion.

Before we discuss a recursive solution, think about how you might implement the maximum function imperatively. You’d probably set up a variable to hold the current maximum value, then you’d loop through every element of the list. If the current element is bigger than the current maximum value, you’d replace the maximum value with that element. The maximum value that remains at the end of the loop would be the final result.

Now let’s see how we’d define it recursively. First, we need to define a base case: We say that the maximum of a singleton list is equal to the only element in it. But what if the list has more than one element? Well, then we check which is bigger: the first element (the head) or the maximum of the rest of the list (the tail). Here’s the code for our recursive maximum' function:

maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list!"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)

As you can see here, pattern matching is really useful for defining recursive functions. Being able to match and deconstruct values makes it easy to break down the maximum-finding problem into the relevant cases and recursive subproblems.

The first pattern says that if the list is empty, the program should crash. This makes sense, because we just can’t say what the maximum of an empty list is. The second pattern says that if maximum' is passed a singleton list, it should just return that list’s only element.

Our third pattern represents the meat of the recursion. The list is split into a head and a tail. We call the head x and the tail xs . Then, we make use of our old friend, the max function. The max function takes two things and returns whichever of them is larger. If x is larger than the largest element in xs , our function will return x , otherwise it will return the largest element in xs . But how does our maximum' find the largest element in xs ? Simple—by calling itself, recursively!

image with no caption

Let’s work through this code with a specific example, just in case you’re having trouble visualizing how maximum' works. If we call maximum' on [2,5,1] , the first two patterns don’t match the function call. However, the third pattern does, so the list value is split into 2 and [5,1] , and maximum' is called with [5,1] .

For this new call to maximum' , [5,1] matches the third pattern, and once again the input list is split—this time into 5 and [1] —and maximum' is recursively called on [1] . This is a singleton list, so the newest call now matches one of our base cases and returns 1 as a result.

Now, we go up a level, comparing 5 to 1 with the use of the max function. 1 was the result of our last recursive call. Since 5 is larger, we now know that the maximum of [5,1] is 5 .

Finally, comparing 2 to the maximum of [5,1] , which we now know is 5 , we obtain the answer to the original problem. Since 5 is greater than 2 , we can now say that 5 is the maximum of [2,5,1] .

A Few More Recursive Functions

Now that we’ve seen how to think recursively, let’s implement a few more functions this way. Like maximum , these functions already exist in Haskell, but we’re going to write our own versions to exercise the recursive muscle fibers in the recursive muscles of our recursive muscle groups. Let’s get buff!

replicate

First off, we’ll implement replicate . Remember that replicate takes an Int and a value, and returns a list that has several repetitions of that value (namely, however many the Int specifies). For instance, replicate 3 5 returns a list of three fives: [5,5,5] .

Let’s think about the base cases. We immediately know what to return if we’re asked to replicate something zero or fewer times. If we try to replicate something zero times, we should get an empty list. And we declare that the result should be the same for negative numbers, because replicating an item fewer than zero times doesn’t make sense.

In general, a list with n repetitions of x is a list with x as its head and a tail consisting of x replicated n-1 times. We get the following code:

replicate' :: Int -> a -> [a]
replicate' n x
    | n <= 0    = []
    | otherwise = x : replicate' (n-1) x

We used guards here instead of patterns because we’re testing for a Boolean condition.

take

Next up, we’ll implement take . This function returns a specified number of elements from a specified list. For instance, take 3 [5,4,3,2,1] will return [5,4,3] . If we try to take zero or fewer elements from a list, we should get an empty list, and if we try to take anything at all from an empty list, we should get an empty list. Notice that those are our two base cases. Now let’s write the function:

take' :: Int -> [a] -> [a]
take' n _
    | n <= 0   = []
take' _ []     = []
take' n (x:xs) = x : take' (n-1) xs

Notice that in the first pattern, which specifies that we get an empty list if we try to take zero or fewer elements from a list, we use the _ placeholder to match the list value, because we don’t really care what it is in this case. Also notice that we use a guard, but without an otherwise part. That means that if n turns out to be more than 0, the matching will fall through to the next pattern.

image with no caption

The second pattern indicates that if we try to take any number of things at all from an empty list, we get an empty list.

The third pattern breaks the list into a head and a tail. We call the head x and the tail xs . Then we state that taking n elements from a list is the same as creating a list that has x as its first element and n-1 elements from xs as its remaining elements.

reverse

The reverse function takes a list and returns a list with the same elements, but in the reverse order. Once again, the empty list is the base case, since trying to reverse an empty list just results in the empty list. What about the rest of the function? Well, if we split the original list into its head and tail, the reversed list that we want is the reverse of the tail, with the head stuck at the end:

reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]

repeat

The repeat function takes an element and returns an infinite list composed of that element. A recursive implementation of repeat is really easy:

repeat' :: a -> [a]
repeat' x = x:repeat' x

Calling repeat 3 will give us a list that starts with 3 as the head and has an infinite amount of 3 s as the tail. So calling repeat 3 evaluates to 3:repeat 3 , which evaluates to 3:(3:repeat 3) , which evaluates to 3:(3:(3:repeat 3)) , and so on. repeat 3 will never finish evaluating. However, take 5 (repeat 3) will give us a list of five 3 s. Essentially, it’s like calling replicate 5 3 .

This is a nice example of how we can successfully use recursion that doesn’t have a base case to make infinite lists—we just have to be sure to chop them off somewhere along the way.

zip

zip is another function for working with lists that we’ve met in Chapter 1 . It takes two lists and zips them together. For instance, calling zip [1,2,3] [7,8] returns [(1,7),(2,8)] (the function truncates the longer list to match the length of the shorter one).

Zipping something with an empty list just returns an empty list, which gives us our base case. However, zip takes two lists as parameters, so there are actually two base cases:

zip' :: [a] -> [b] -> [(a,b)]
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x,y):zip' xs ys

The first two patterns are our base cases: If the first or second list is empty, we return an empty list. The third pattern says that zipping two lists together is equivalent to pairing up their heads, then appending their zipped tails to that.

For example, if we call zip' with [1,2,3] and ['a','b'] , the function will form (1,'a') as the first element of the result, then zip together [2,3] and [b] to obtain the rest of the result. After one more recursive call, the function will try to zip [3] with [] , which matches one of the base case patterns. The final result is then computed directly as (1,'a'):((2,'b'):[]) , which is just [(1,'a'),(2,'b')] .

elem

Let’s implement one more standard library function: elem . This function takes a value and a list, and checks whether the value is a member of the list. Once again, the empty list is a base case—an empty list contains no values, so it certainly can’t have the one we’re looking for. In general, the value we’re looking for might be at the head of the list if we’re lucky; otherwise, we have to check whether it’s in the tail. Here’s the code:

elem' :: (Eq a) => a -> [a] -> Bool
elem' a [] = False
elem' a (x:xs)
    | a == x    = True
    | otherwise = a `elem'` xs

Quick, Sort!

The problem of sorting a list containing elements that can be put in order (like numbers) naturally lends itself to a recursive solution. There are many approaches to recursively sorting lists, but we’ll look at one of the coolest ones: quicksort . First we’ll go over how the algorithm works, and then we’ll implement it in Haskell.

image with no caption

The Algorithm

The quicksort algorithm works like this. You have a list that you want to sort, say [5,1,9,4,6,7,3] . You select the first element, which is 5 , and put all the other list elements that are less than or equal to 5 on its left side. Then you take the ones that are greater than 5 and put them on its right side. If you did this, you’d have a list that looks like this: [1,4,3,5,9,6,7] . In this example, 5 is called the pivot , because we chose to compare the other elements to it and move them to its left and right sides. The only reason we chose the first element as the pivot is because it will be easy to snag using pattern matching. But really, any element can be the pivot.

Now, we recursively sort all the elements that are on the left and right sides of the pivot by calling the same function on them. The final result is a completely sorted list!

image with no caption

The above diagram illustrates how quicksort works on our example. When we want to sort [5,1,9,4,6,7,3] , we decide that the first element is our pivot. Then we sandwich it in between [1,4,3] and [9,6,7] . Once we’ve done that, we sort [1,4,3] and [9,6,7] by using the same approach.

To sort [1,4,3] , we choose the first element, 1 , as the pivot and we make a list of elements that are less than or equal to 1 . That turns out to be the empty list, [] , because 1 is the smallest element in [1,4,3] . The elements larger than 1 go to its right, so that’s [4,3] . Again, [4,3] is sorted in the same way. It too will eventually be broken up into empty lists and put back together.

The algorithm then returns to the right side of 1 , which has the empty list on its left side. Suddenly, we have [1,3,4] , which is sorted. This is kept on the left side of the 5 .

Once the elements on the right side of the 5 are sorted in the same way, we will have a completely sorted list: [1,3,4,5,6,7,9] .

The Code

Now that we’re familiar with the quicksort algorithm, let’s dive into its implementation in Haskell:

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
    let smallerOrEqual = [a | a <- xs, a <= x]
        larger = [a | a <- xs, a > x]
    in  quicksort smallerOrEqual ++ [x] ++ quicksort larger

The type signature of our function is quicksort :: (Ord a) => [a] -> [a] , and the empty list is the base case, as we just saw.

Remember, we’ll put all the elements less than or equal to x (our pivot) to its left. To retrieve those elements, we use the list comprehension [a | a <- xs, a <= x] . This list comprehension will draw from xs (all the elements that aren’t our pivot) and keep only those that satisfy the condition a <= x , meaning those elements that are less than or equal to x . We then get the list of elements larger than x in a similar fashion.

We use let bindings to give the two lists handy names: smallerOrEqual and larger . Finally, we use the list concatenation operator ( ++ ) and a recursive application of our quicksort function to express that we want our final list to be made of a sorted smallerOrEqual list, followed by our pivot, followed by a sorted larger list.

Let’s give our function a test drive to see if it behaves correctly:

ghci> quicksort [10,2,5,3,1,6,7,4,2,3,4,8,9]
[1,2,2,3,3,4,4,5,6,7,8,9,10]
ghci> quicksort "the quick brown fox jumps over the lazy dog"
"        abcdeeefghhijklmnoooopqrrsttuuvwxyz"

Now that’s what I’m talking about!

Thinking Recursively

We’ve used recursion quite a bit in this chapter, and as you’ve probably noticed, there’s a pattern to it. You start by defining a base case: simple, nonrecursive solution that holds when the input is trivial. For example, the result of sorting an empty list is the empty list, because—well, what else could it be?

Then, you break your problem down into one or many subproblems and recursively solve those by applying the same function to them. You then build up your final solution from those solved subproblems. For instance, when sorting, we broke our list into two lists, plus a pivot. We sorted each of those lists separately by applying the same function to them. When we got the results, we joined them into one big sorted list.

image with no caption

The best way to approach recursion is to identify base cases and think about how you can break the problem at hand into something similar, but smaller. If you’ve correctly chosen the base cases and subproblems, you don’t even have to think about the details of how everything will happen. You can just trust that the solutions of the subproblems are correct, and then you can just build up your final solutions from those smaller solutions.