Higher order functions are functions which take in other functions as input, or return a function as output. takeWhile and dropWhile which I covered in the page on Prelude functions are examples of higher order functions. But the three most useful higher order functions are map, fold and filter.

**1 - map**

map is the easiest to understand of the three. It takes in two inputs - a function, and a list. It then applies this function to every element in the list.
You can basically do the same thing with a list comprehension however.

map function list does exactly the same thing as [function x | x <- list]

Why do we use it then? Mainly because map is easier to understand and more compact in writing.

**2 - fold**

fold takes in a function and *folds* it in between the elements of a list. It's a bit hard to understand at first - try this example.

Let's add up the first 5 numbers with fold. The command for this is

1 | 2 | 3 | 4 | 5 |

And now we

+ | 1 | + | 2 | + | 3 | + | 4 | + | 5 |

Note that there's nothing before the first (+). That's because we can specify a starting point. So that's the second input foldl asks for - a starting point. In this case, we said zero, so we'll put it in there.

0 | + | 1 | + | 2 | + | 3 | + | 4 | + | 5 |

And all this gives us the final result

We can also go through the list from right to left, rather than left to right. That's why we use foldl and foldr. In the example with (+) we get exactly the same result since (0 + 1 + 2 + 3 + 4 + 5) is exactly the same as (0 + 5 + 4 + 3 + 2 + 1) However, there are cases where folding from the left gives us different results to folding from the right. It all depends on what function you're folding. For example,

**3 - filter**

filter is easy. It takes in a 'test' and a list, and it chucks out any elements of the list which don't satisfy that test.

Go get some practice!

Back to Supp. Notes