Haskell/Lists III

Folds
Like, a fold is a higher order function that takes a function and a list. However, instead of applying the function element by element, the fold uses it to combine the list elements into a result value.

Let's look at a few concrete examples. could be implemented as:

and  as:

, which takes a list of lists and joins (concatenates) them into one:

All these examples show a pattern of recursion known as a fold. Think of the name referring to a list getting "folded up" into a single value or to a function being "folded between" the elements of the list.

Prelude defines four  functions: ,  ,   and.

foldr
The right-associative  folds up a list from the right to left. As it proceeds, foldr uses the given function to combine each of the elements with the running value called the accumulator. When calling foldr, the initial value of the accumulator is set as an argument.

The first argument to  is a function with two arguments. The second argument is the value for the accumulator (which often starts at a neutral "zero" value). The third argument is the list to be folded.

In,   is  , and   is. In,   is   and   is. In many cases (like all of our examples so far), the function passed to a fold will be one that takes two arguments of the same type, but this is not necessarily the case (as we can see from the  part of the type signature — if the types had to be the same, the first two letters in the type signature would have matched).

Remember, a list in Haskell written as  is an alternative (syntactic sugar) style for.

Now,  in the   definition simply replaces each cons  in the   list with the function   while replacing the empty list at the end with  :

Note how the parentheses nest around the right end of the list.

An elegant visualisation is given by picturing the list data structure as a tree: :                        f  / \                       / \ a  :       foldr f acc   a   f    / \    ->     / \ b  :                     b   f      / \                       / \ c []                     c   acc

We can see here that  will return the list completely unchanged. That sort of function that has no effect is called an identity function. You should start building a habit of looking for identity functions in different cases, and we'll discuss them more later when we learn about monoids.

foldl
The left-associative  processes the list in the opposite direction, starting at the left side with the first element.

So, parentheses in the resulting expression accumulate around the left end of the list:

The corresponding trees look like: :                           f  / \                          / \ a  :       foldl f acc      f   c    / \    ->    / \ b  :                    f   b       / \                  / \ c []                acc a

Because all folds include both left and right elements, beginners can get confused by the names. You could think of foldr as short for fold-right-to-left and foldl as fold-left-to-right. The names refer to where the fold starts.

Are foldl and foldr opposites?
You may notice that in some cases  and   do not appear to be opposites. Let's examine one such case, involving subtraction as the combining operation. Will we get  or   for each of the equalities below?

Thinking of  as going from right to left might lead us to suppose that the second equality would be true, as the rightmost elements show up before the leftmost ones. That, however, is not what we actually see:

This happens because the difference between  and   lies in the way the resulting expression is associated, and not in the left-to-right order of the elements of the list. Here is the expansion of the expressions above, with explicit parentheses:

Also note how the initial accumulator ( in this example) is always found in the innermost parentheses.

For the sake of contrast, here is a simulated imperative style that does change the order of the elements in the list:

Now we get  in both cases from our initial example, because both are folding from the left:

foldr1 and foldl1
As previously noted, the type declaration for  makes it quite possible for the list elements and result to be of different types. For example, "read" is a function that takes a string and converts it into some type (the type system is smart enough to figure out which one). In this case we convert it into a float.

There is also a variant called  ("fold - R - one") which dispenses with an explicit "zero" for an accumulator by taking the last element of the list instead:

And  as well:

Note: Just like for foldl, the Data.List library includes foldl1' as a strict version of foldl1.

With foldl1 and foldr1, all the types have to be the same, and an empty list is an error. These variants are useful when there is no obvious candidate for the initial accumulator value and we are sure that the list is not going to be empty. When in doubt, stick with foldr or foldl'.

folds and laziness
One reason that right-associative folds are more natural in Haskell than left-associative ones is that right folds can operate on infinite lists. A fold that returns an infinite list is perfectly usable in a larger context that doesn't need to access the entire infinite result. In that case, foldr can move along as much as needed and the compiler will know when to stop. However, a left fold necessarily calls itself recursively until it reaches the end of the input list (because the recursive call is not made in an argument to f). Needless to say, no end will be reached if an input list to foldl is infinite.

As a toy example, consider a function  that takes a list of integers and produces a list such that wherever the number n occurs in the input list, it is replicated n times in the output list. To create our echoes function, we will use the prelude function  in which   is a list of length n with x the value of every element.

We can write echoes as a foldr quite handily:

(Note: This definition is compact thanks to the syntax. The , meant to look like a lambda (λ), works as an unnamed function for cases where we won't use the function again anywhere else. Thus, we provide the definition of our one-time function in situ. In this case,   and   are the arguments, and the right-hand side of the definition is what comes after the  .)

We could have instead used a foldl:

but only the foldr version works on infinite lists. What would happen if you just evaluate ? Try it! (If you try this in GHCi or a terminal, remember you can stop an evaluation with Ctrl-c, but you have to be quick and keep an eye on the system monitor or your memory will be consumed in no time and your system will hang.)

As a final example,  itself can be implemented as a fold:

Folding takes some time to get used to, but it is a fundamental pattern in functional programming and eventually becomes very natural. Any time you want to traverse a list and build up a result from its members, you likely want a fold.

Scans
A "scan" is like a cross between a  and a fold. Folding a list accumulates a single return value, whereas mapping puts each item through a function returning a separate result for each item. A scan does both: it accumulates a value like a fold, but instead of returning only a final value it returns a list of all the intermediate values.

Prelude contains four scan functions:

accumulates the list from the left, and the second argument becomes the first item in the resulting list. So,.

uses the first item of the list as a zero parameter. It is what you would typically use if the input and output items are the same type. Notice the difference in the type signatures between  and. .

These two functions are the counterparts of  and   that accumulate the totals from the right.

filter
A common operation performed on lists is filtering — generating a new list composed only of elements of the first list that meet a certain condition. A simple example: making a list of only even numbers from a list of integers.

This definition is somewhat verbose and specific. Prelude provides a concise and general  function with type signature:

So, a  function tests an elements for some condition, we then feed in a list to be filtered, and we get back the filtered list.

To write  using , we need to state the condition as an auxiliary  function, like this one:

And then retainEven becomes simply:

We used ns instead of xs to indicate that we know these are numbers and not just anything, but we can ignore that and use a more terse point-free definition:

This is like what we demonstrated before for  and the folds. Like, those take another function as argument; and using them point-free emphasizes this "functions-of-functions" aspect.

List comprehensions
List comprehensions are syntactic sugar for some common list operations, such as filtering. For instance, instead of using the Prelude, we could write   like this:

This compact syntax may look intimidating, but it is simple to break down. One interpretation is:


 * (Starting from the middle) Take the list es and draw (the "<-") each of its elements as a value n.
 * (After the comma) For each drawn n test the boolean condition.
 * (Before the vertical bar) If (and only if) the boolean condition is satisfied, append n to the new list being created (note the square brackets around the whole expression).

Thus, if  is [1,2,3,4], then we would get back the list [2,4]. 1 and 3 were not drawn because.

The power of list comprehensions comes from being easily extensible. Firstly, we can use as many tests as we wish (even zero!). Multiple conditions are written as a comma-separated list of expressions (which should evaluate to a Boolean, of course). For a simple example, suppose we want to modify  so that only numbers larger than 100 are retained:

Furthermore, we are not limited to using  as the element to be appended when generating a new list. Instead, we could place any expression before the vertical bar (if it is compatible with the type of the list, of course). For instance, if we wanted to subtract one from every even number, all it would take is:

In effect, that means the list comprehension syntax incorporates the functionalities of  and.

To further sweeten things, the left arrow notation in list comprehensions can be combined with pattern matching. For example, suppose we had a list of  tuples, and we would like to construct a list with the first element of every tuple whose second element is even. Using list comprehensions, we might write it as follows:

Patterns can make it much more readable:

As in other cases, arbitrary expressions may be used before the. If we wanted a list with the double of those first elements:

Not counting spaces, that function code is shorter than its descriptive name!

There are even more possible tricks:

This comprehension draws from two lists, and generates all possible  pairs with the first element drawn from   and the second from. In the final list of pairs, the first elements will be those generated with the first element of the first list (here, ), then those with the second element of the first list, and so on. In this example, the full list is (linebreaks added for clarity):

Prelude> [(x, y) | x <- [1..4], y <- [5..8]] [(1,5),(1,6),(1,7),(1,8), (2,5),(2,6),(2,7),(2,8), (3,5),(3,6),(3,7),(3,8), (4,5),(4,6),(4,7),(4,8)]

We could easily add a condition to restrict the combinations that go into the final list:

This list only has the pairs with the sum of elements larger than 8; starting with, then   and so forth.