In this lesson, we will look at three examples of higher-order functions. Programmers use these functions in many languages. It is worth noting up front that the examples in this lesson are somewhat simplified. We will discuss the Python versions of these functions.
For greater flexibility and performance, we implement them slightly differently. Simple examples can successfully demonstrate the purpose and general principle of operation.
The map
function
When working with lists, we often have to apply some form of transformation (specifically, the same kind of transformation) for each element. Of course, we can always write a loop. However, this loop will look identical in almost all cases:
def f(x):
…
new_list = []
for item in old_list:
new_item = f(item)
new_list.append(new_item)
# …
# Using `new_list`
In such cases, only the applied f
function changes. So why not generalize this code so that the function is a parameter? That is what we are going to do:
def map(function, items):
result = []
for item in items:
result.append(function(item))
return result
map(str, range(5))
# ["0", "1", "2", "3", "4"]
The function is called map. The name comes from mathematics. We give the same name to functions that map one set of values to another by converting all elements using some transformation. Most languages use the same name.
The filter
function
Often you do not need to transform the elements so much as you need to keep some of them in the list and discard others according to some criterion. A filter
function solves this problem in many languages. The code for this function looks similar to the map
code:
def filter(predicate, items):
result = []
for item in items:
if predicate(item):
result.append(item)
return result