12.2. Writing Functional Programs - Advanced
12.2. Writing Functional Programs - Advanced
www.pmt.education
Specification:
www.pmt.education
Functional Programming
Resources to help you learn a functional programming language are available in the
extra resources.
www.pmt.education
Map
The map function takes a second function and applies it to a list of elements before
returning the new list.
Map Example 1
We have the following list:
However, we want to minus 2 from each element. To do this, we can use the map
function.
Map Example 2
We have the following list:
Map Example 3
There is a list of single fruit items.
www.pmt.education
:
We want to change the list so each element is plural. The easiest way of doing this is
adding an “s” on the end of each word.
Filter
The filter function returns the elements of the list which adhere to the condition given. It
is a filter IN rather than a filter OUT.
Filter Example 1
We have the following list:
Filter Example 2
We have the following list:
www.pmt.education
Fold
By folding a list, you can reduce the list to a single value.
Folding is also known as reducing. The fold function needs an
operator (+,- etc), a starting number and a list. The type of fold
- left or right - determines how the recursion will work. You will
only be asked questions on fold left, but it is a good idea to
have an understanding of fold right.
Fold Example 1
We have the following list:
What is happening?
www.pmt.education
In this case, the result would be the same for fold right, it would just be calculated
differently.
Fold Example 2
We have the following list:
We can use the fold function to reduce this list to a single number.
What happened?
www.pmt.education
Using fold right in this case, produces a very different answer.
www.pmt.education