Thunks, Streams, Recursion, Co-Recursion! There’s been a lot to learn in this chapter! Before we move on, let’s take a look at one more example to help reinforce the concepts you’ve learned in this chapter. The Fibonacci series is a sequence of numbers that frequently makes an appearance in programming texts because it has the valuable property of having a simple recursive definition. In this section, you’ll build an infinite stream of Fibonacci numbers, and then look at several different ways that you can refactor the code to be more efficient.

Let’s start by defining the Fibonacci sequence. It’s a sequence of integers starting with [0,1] . You can calculate each number in the series by adding up the two numbers that came before it. For example, the third Fibonacci number can be calculated by adding the first two: fibonacci 3 = fibonacci 2 + fibonacci 1 = 1 + 0 = 1 .

You might already recognize that this definition looks a lot like a recursive program. Let’s create a new module, Fibs , and add a new function, fib , that will take an index and return back that number in the Fibonacci sequence:

​  ​ module ​ ​ Fibs ​ ​ where ​
​  
​  fib n
​  | n == 0 = 0
​  | n == 1 = 1
​  | otherwise = (fib $ n - 1) + (fib $ n - 2)

Load this program into ghci , and you can see that it works to give you a valid Fibonacci number. Trying numbers larger than around 20 to 30, depending on the speed of your particular computer, you will see that there’s a noticeable delay to calculate the Fibonacci number. Later in this section you’ll learn how to implement a more efficient algorithm, but for now this slowness is very useful because it will show you how laziness allows you to avoid calculating a value until you need it.

Now that you have a function that can find any given Fibonacci number, it’s easy to create a function that will return a stream of Fibonacci numbers. Let’s write a new function, fibs , that represents a list of all of the Fibonacci numbers:

​  fibs = map fib [0..]

This function creates a list of all of the Fibonacci numbers by mapping a function that finds the nth Fibonacci number of an infinite list of all natural numbers. Thanks to laziness, only the specific Fibonacci numbers that you request from the list will ever be calculated. As an example, let’s write a program to get a list of all of the Fibonacci numbers that are less than 100. We can use the takeWhile function to help us. The takeWhile function will return elements of a list so long as the predicate we pass in is True . Since takeWhile stops as soon as it encounters a non-matching element, we can use it on infinite lists, like our infinite list of Fibonacci numbers.

​  ​ module ​ ​ Fibs ​ ​ where ​
​  
​  fib n
​  | n == 0 = 0
​  | n == 1 = 1
​  | otherwise = (fib $ n - 1) + (fib $ n - 2)
​  
​  fibs = map fib [0..]
​  
​  smallFibs =
​  takeWhile (< 100) fibs

As you can see, generating an infinite list of Fibonacci numbers this way works. Unfortunately, it’s also extremely inefficient. We’re doing a lot of re-work here, and our program will get much slower as we want to work with more and larger Fibonacci numbers. Thankfully, we can use laziness to our advantage and approach this problem in a different, and much more efficient way.

Creating Lazy Streams

You’ve already implemented a lazy stream of numbers that increment by one at each step. We can use the same general approach to create the Fibonacci series, but there’s an additional challenge. We can’t simply add one to each number, instead we need to calculate the next number using the two previous values.

When we created an infinite list of numbers, we had the user tell us what number we should start generating at. Let’s continue with that approach for now, and ask the user to give us two numbers that start the sequence they want us to generate:

​  ​ module ​ ​ Fibs ​ ​ where ​
​  
​  fibs firstFib secondFib =
​  ​ let ​ nextFib = firstFib + secondFib
​  ​ in ​ firstFib : fibs secondFib nextFib

Let’s walk through a couple of steps of generating this stream to get a feel for what’s happening. We’ll start at the beginning of the sequence, passing in the first two numbers, zero and one:

​  fibs 0 1 =
​  ​ let ​ nextFib = 0 + 1
​  ​ in ​ 0 : fibs 1 nextFib

Next, let’s simplify the code and replace nextFib with the result of evaluating the arithmetic:

​  fibs 0 1 =
​  0 : fibs 1 1

We can expand our call to fibs again to see the next step of the algorithm:

​  fibs 0 1 =
​  0 : (​ let ​ nextFib = 1 + 1
​  ​ in ​ 1 : fibs 1 nextFib)

Once again, let’s do the arithmetic and compute nextFib :

​  fibs 0 1 =
​  0 : 1 : fibs 1 2

After a few steps through this program you might be getting a feel for the steps we’re taking to calculate each new number, but there are some extra moving parts coming from the additional number we’re tracking. Let’s look at a picture to help us see what’s going on:

images/fibs.png

As you can see, our Fibonacci stream is following the pattern of the other streaming lists that you’ve created. At each step we’re creating a new head with the next computed value, and the tail is a thunk that tells us how to compute the next list. Unfortunately, there are a couple of minor problems with the approach that we’re taking. First, it’s inconvenient to ask the user to pass in the first two numbers in the sequence. A user who wants to know what the first two numbers of the series are would be pretty irritated if they realized our API required them to tell us the first two numbers before we could return the list back to them. Second, our algorithm is requiring us to calculate a couple of steps ahead. Instead of looking at the two previous numbers in the list to generate the next one, we’re effectively generating the list two numbers ahead. For the Fibonacci series, where this extra work only means that we’re doing some extra addition, the consequences are pretty minor. If we were doing a more heavy-weight computation though, it could have a noticeable impact. In any case, we’d like to build this the right way and avoid doing unnecessary work.

We can address both of these concerns with one refactor. Let’s take a look at the code, and then we’ll step through this version to see how it compares to the previous implementation:

​  fibs = 0 : 1 : helper fibs (tail fibs)
​  ​ where ​
​  helper (a:as) (b:bs) =
​  a + b : helper as bs

This version of our algorithm goes all in on taking advantage of thunks and laziness to help us write a stream that avoids doing any rework, but at first the implementation might seem a little mind twisting. Let’s step through a few iterations of it to get a better idea of what’s happening.

We start out with fibs having two values that we’re hard-coding, followed by a tail that’s being generated thanks to a helper function. The implementation of helper by itself might not be too confusing now that you’re familiar with generating streams. The fact that helper is being called with references to fibs , however, and understanding how that works, can be a challenge.

Let’s start by replacing the references to fibs with their values in the first step of the program:

​  fibs = 0 : 1 : helper (0 : 1 : <thunk>) (tail $ 0 : 1 : <thunk>)
​  ​ where ​
​  helper (a:<thunk>) (b:<thunk>) =
​  a + b : helper <thunk> <thunk>

You can see right away that the two recursive references to fibs that we’re passing into helper are benefiting from the fact that we’ve provided a couple of starting values. That means that we have two values to work with before we need to start doing any actual recursion. Luckily for us, two is exactly how many values we need in order to generate the next element of the list.

Let’s simplify a bit by removing the explicit call to tail and replacing the values of a and b in helper with their actual values:

​  fibs = 0 : 1 : helper (0 : 1 : <thunk>) (1 : <thunk>)
​  ​ where ​
​  helper (0 : 1 : <thunk>) (1 : <thunk>) =
​  0 + 1 : helper (1 : <thunk>) <thunk>

When we replace the parameters we passed into helper with their actual values, we’re able to generate a new list, its head is the new value we just calculated, and the tail is a thunk that will make another call to helper .

Next, let’s substitute the value we just calculated for our call to helper back up into the body of fibs . You will notice that the parameters to helper are still the thunks, but we’ve consumed the first element from each of the lists. The second argument is now an entirely evaluated thunk:

​  fibs = 0 : 1 : 1 : helper (1 : <thunk>) <thunk>

So, we need to evaluate the thunk before we can move on. What value should it have? Let’s rewind for a minute. The value we originally passed in was:

​  tail fibs

The value of fibs is a list with two hardcoded values, and a tail defined by our call to helper :

​  tail fibs = tail $ 0 : 1 : helper fibs (tail fibs)
​  = 1 : helper fibs (tail fibs)

We’ve already taken one step through our program, so the value of our thunk is now whatever is returned by our call to helper:

​  helper fibs (tail fibs) = 1 : helper (1 : <thunk>) <thunk>

We don’t need to evaluate the tail of the list yet, so we can simplify this a bit further:

​  helper fibs (tail fibs) = 1 : <thunk>

So, we’ve evaluated the thunk and gotten back a list whose tail is another thunk. Let’s replace the unevaluated thunk in our call with this newly evaluated one. That will give us:

​  fibs = 0 : 1 : 1 : helper (1 : <thunk>) (1 : <thunk>)
​  ​ where ​
​  helper (1 : <thunk>) (1 : <thunk>) =
​  1 + 1 : helper <thunk> <thunk>

Now we have two unevaluated thunks. Let’s replace our call to helper with the value we just calculated, and then we’ll look at how to evaluate these two new thunks:

​  fibs = 0 : 1 : 1 : 2 : helper <thunk> <thunk>

Just like we did in the last step, we need to evaluate our thunks. Remember that the thunks here aren’t referring to the original definition of fibs anymore. Instead, they are referring to the current lists that we’ve been stepping through. Those lists are actually two different points in the same list. The first argument is one step behind the second, which is itself always one step behind the next element that we’re about to generate from our call to helper .

One way to think of this is our function has two head values that are “chasing” our helper. Each time we take a step forward, they all move one element further into the list. The first thunk, which was originally defined as fibs , is always one step behind the second thunk, which we defined with tail fibs .

An image can also help us visualize what’s happening. Each time we evaluate the thunks that we’re passing into helper they take one more step into the list that we’re generating as we go. This means that the list and the two references are all moving in lockstep, with the thunks always one and two steps behind the next value that helper is returning as shown in the image .

images/fibs2.png

If you’re feeling a little bit overwhelmed after working through this section, it’s okay! Take a deep breath! Understanding the way that lazy evaluation works, and especially how it interacts with techniques like recursive, co-recursive, and mutually recursive functions can be a lot to take in. You may need to revisit this section a few times, or even work ahead and come back to this section later to give it time to fully sink in.