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.
1 - map
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
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.