Throughout this chapter you’ve learned how to express computations with Haskell, and you’ve written several small working programs without thinking too much about how the computer will actually run the programs that you’ve written. If you have experience writing programs in other languages, you might have an intuition about how applications are executed, but Haskell’s execution model is a bit different than what you might have run into in other languages, because it’s a lazy language. More specifically, Haskell uses a form of laziness known as call by need . This means that when you define an expression in Haskell it won’t be evaluated until the value is actually needed. The expressions that haven’t been evaluated yet are called “thunks.” When you’re writing Haskell programs, you build up layers of thunks representing some work that might need to be evaluated at some point.
Laziness is particularly interesting when we’re dealing with lists, because one of the consequences of the way that Haskell uses laziness is that it’s easy for us to create and work with lists of elements that are very expensive to compute, or even infinitely long lists.
To understand how this works, let’s take another look at Haskell lists, but this time we’ll look a little bit more deeply at what the values actually look like. You’ll learn much more about the inner workings of how Haskell stores values later on in this book , but for now we’re going to keep the discussion somewhat abstract.
You know that a Haskell list is either an empty list, or a non-empty list, which is made up of a pair of values: the head of the list, and the tail. The head of a non-empty list is the value at the front of the list. The tail is another list (which may or may not be empty). Thunks add another dimension that we need to consider. The tail of a non-empty list might not be a list whose value has been computed. Most of the time, the tail of a list is actually a thunk that will be computed. The list that we get back when we compute that thunk may, in turn, be another non-empty list whose tail is yet another thunk. In fact, each time we evaluate a thunk to get a list, the result might be that we create a brand new thunk that represents incrementally more of the list that we’re trying to create.
Let’s take a look at this in practice with an example:
| | numbersStartingAt n = |
| | n : numbersStartingAt (n + 1) |
This function generates a type of list called a stream or, occasionally, a generator . These functions work by taking advantage of lazy evaluation to make a list whose tail is a thunk. When we evaluate the thunk, it computes a new list whose head is the next step of the iteration, and whose tail is another thunk that will compute another step, and so on. We can visualize it in code:
| | numbersStartingAt 0 = |
| | 0 : <thunk> |
If we’re only ever looking at the first element of a call to numbersStartingAt then the thunk will never be evaluated, and we are only carrying around the first number. If we do evaluate the thunk, then we’ll end up computing one more step in the stream by calling numbersStartingAt again:
| | 0 : numbersStartingAt 1 |
Which will give us:
| | 0 : 1 : <thunk> |
We can keep this pattern up forever. Every time we evaluate the thunk, we get one more element in the list, and the tail will always be a freshly generated thunk that will give us the next value when we need it.
This technique looks a lot like recursion , but it’s not quite the same thing. Unlike recursive functions that we’ve written so far, streams don’t count down to a base case. Instead, they start with a seed value and work their way up, potentially forever. The technical term for these kinds of functions is co-recursive , but more often than not, in a casual setting people will simply use the term “recursion” for this type of function. Since precisely defining the difference is outside of the scope of the book, we won’t be overly rigorous and will also just use the term “recursion” here.
Generating infinite lists this way ends up having several useful applications. One example is it can help you avoid tricky modulo arithmetic. Instead of calculating the boundaries of an array, you can use the cycle function from Prelude to create an infinitely repeating list. Let’s look at an example of this by writing a function to convert radians to degrees. Our function will always return a number of degrees between 0 and 359 (we’ll only consider integer numbers of degrees), and instead of using modulo, we’ll index into a repeating list:
| | radsToDegrees :: Float -> Int |
| | radsToDegrees radians = |
| | let degrees = cycle [0..359] |
| | converted = truncate $ (radians * 360) / (2 * pi) |
| | in degrees !! converted |
For practice, let’s write our own version of cycle . Our version will be really cool, and we don’t want it to conflict with the existing function already named cycle , so let’s call ours epicCycle :
| | epicCycle inputList = |
| | cycleHelper inputList |
| | where |
| | cycleHelper [] = epicCycle inputList |
| | cycleHelper (x:xs) = x : cycleHelper xs |
You’ll notice that we’re using a helper function in a where clause in this function. While you won’t always need a helper function like this when you’re creating streams, they are extremely common for this sort of problem. If you find yourself trying to create a stream and getting stuck on how to build it, think about whether you might need a auxiliary helper function.
Our helper function steps through each element of the input list, and adds it to the output list. The first trip through the elements of our list, our cyclic list will be the same as the list we started with. When we get to the end of the input, for a normal finite list we’d just return the empty list and exit. For our infinitely repeating stream, instead, we call epicCycle again, with the same list we just finished with.
Laziness in Haskell is pervasive. We don’t have to go out of our way to manually construct lists like this to get an infinite list. We can use other normal list functions to construct and work with infinite lists as well. For example, we can write an even shorter and cooler version of our function, a moreEpicCycle , that uses (<>) :
| | moreEpicCycle inputList = |
| | inputList <> moreEpicCycle inputList |
This version of our function works just like the previous version. We create a new infinitely repeating list by taking the original list and appending a new infinitely repeating version of it.
Folds and Infinite Lists
One of the most surprising consequences of the way that lazy evaluation works in Haskell is that, in some cases, you can get a value back when you use a fold on an infinite list. That can seem very counterintuitive at first, so let’s look at an example to prove to ourselves that it does, in fact, work. Then we’ll look at how it works.
In this example, we’ll write a function that will find the first element of a list that satisfies our predicate function and return it, even if the list is infinite. You’ll learn how to deal with optional values in a couple of chapters , but for now we’ll return our result in a list. If we found what we’re looking for, we’ll return it in a single item list. If we didn’t find it, we’ll return an empty list:
| | module InfiniteFind where |
| | |
| | findFirst predicate = |
| | foldr findHelper [] |
| | where |
| | findHelper listElement maybeFound |
| | | predicate listElement = [listElement] |
| | | otherwise = maybeFound |
If you load this up into ghci you can see that we can find numbers in many different sorts of both finite and infinite lists:
| | λ findFirst (> 5) [1..100] |
| | [6] |
| | |
| | λ findFirst (> 10) [1..] |
| | [11] |
| | |
| | λ findFirst (> 50) (cycle [1..100]) |
| | [51] |
Our function will also successfully return an empty list if we’re looking for something that doesn’t exist inside of a finite list:
| | λ findFirst (> 100) [1..10] |
| | [] |
Unfortunately, if we’re looking for something that doesn’t exist in an infinite list, the program will never stop looking. You can press Control-C to cancel something in ghci if you try this example:
| | λ findFirst (> 10) (cycle [1..5]) |
| | Interrupted . |
It makes sense that if we’re looking for a value in an infinite list, and the value isn’t in the list, then we’ll keep looking forever. Our program will simply keep looking at one element after another. What makes less sense is how we can successfully return a value if we do find one, when there’s still an infinite amount of list left to go.
There are two important factors that let this work. First, this only works with foldr . We can’t use foldl on an infinite list. Second, this only works if the function we’re folding with is “sufficiently lazy.” In other words, we need to be very careful about when we evaluate the thunk that is passed in as the second argument to our helper function. To understand why this works, let’s pretend to be the compiler and walk through an example. We’ll start our definition of foldr from earlier:
| | foldr func carryValue lst = |
| | if null lst |
| | then carryValue |
| | else func (head lst) $ foldr func carryValue (tail lst) |
We’ll start by putting this definition inline into findFirst :
| | findFirst predicate carryValue lst = |
| | if null lst |
| | then carryValue |
| | else findHelper (head lst) $ findFirst predicate carryValue (tail lst) |
| | where |
| | findHelper listElement maybeFound |
| | | predicate listElement = [listElement] |
| | | otherwise = maybeFound |
We know that if we don’t find what we’re looking for, then we’ll always return an empty list. We can use this knowledge to simplify our code a little bit by removing carryValue and replacing it with an empty list:
| | findFirst predicate lst = |
| | if null lst |
| | then [] |
| | else findHelper (head lst) $ findFirst predicate (tail lst) |
| | where |
| | findHelper listElement maybeFound |
| | | predicate listElement = [listElement] |
| | | otherwise = maybeFound |
Next, let’s also move the definition of findHelper into the body of our function. We’ll refactor it a little bit, using an if expression rather than guards, so that we can make the code syntactically valid:
| | findFirst predicate lst = |
| | if null lst |
| | then [] |
| | else |
| | if predicate (head lst) |
| | then [head lst] |
| | else findFirst predicate (tail lst) |
Finally, we’re interested in understanding how we can fold over an infinite list, so we can entirely remove the test to see if we’ve reached the end of our list. We can also use pattern matching so that we don’t have to keep typing head and tail . We wouldn’t want to do this in real-world code, since it means our function would crash if we gave it an empty list, or even any finite list that doesn’t have a matching element.
| | findFirst predicate (x:xs) = |
| | if predicate x |
| | then [x] |
| | else findFirst predicate xs |
This simplified version of our function is a good starting place to see what happens when we call it with a real value. Let’s try running through it manually, looking for the first number greater than two in our list. We could call it with an infinite list:
| | findFirst (> 2) [1..] |
Let’s replace this infinite list with something a little bit more explicit:
| | findFirst (> 2) (1 : <thunk>) |
This won’t compile or run, but it’ll help us visualize what’s happening. When we replace our variables in the body of our function we’ll end up with this:
| | findFirst (> 2) (1 : <thunk>) = |
| | if (> 2) 1 |
| | then [1] |
| | else findFirst (> 2) <thunk> |
Our value is not greater than two, so the first branch of our expression doesn’t get evaluated. Instead, we go to our second branch, where we call findFirst again, and this time we pass in our unevaluated thunk.
In the next step, we’re pattern matching on our thunk. That means we need to actually evaluate it, so we’ll compute the value. As you’ve seen from earlier examples, infinite lists like the one we’re using tend to generate themselves one step at a time, so when we evaluate the thunk we’ll get the next number at the head of our list, and the tail will be yet another unevaluated thunk:
| | findFirst (> 2) (1 : <thunk>) = |
| | if (> 2) 1 |
| | then [1] |
| | else findFirst (> 2) (2 : <thunk>) |
If we replace the recursive call with the body of our function again, we’ll get this:
| | findFirst (> 2) (1 : <thunk>) = |
| | if (> 2) 1 |
| | then [1] |
| | else |
| | if (> 2) 2 |
| | then [2] |
| | else findFirst (>2) (3 : <thunk>) |
The first branch of our if expression is still false (two is equal to, but not greater than, two), so we follow the second branch again. Let’s expand the call one last time:
| | findFirst (> 2) (1 : <thunk>) = |
| | if (> 2) 1 |
| | then [1] |
| | else |
| | if (> 2) 2 |
| | then [2] |
| | else |
| | if (> 2) 3 |
| | then [3] |
| | else findFirst (> 2) <thunk> |
Finally, in this case, our predicate is true. Three is greater than two. That means we will return the value from our first branch, [3] . It also means we’ll never evaluate the second branch, and never evaluate the thunk. Since we never evaluate any more of the thunk, we don’t need to concern ourselves with the fact that we could keep evaluating it forever and not come to the end of it. As long as we’re not trying to find the end, it doesn’t matter that it might be infinite in theory.