Blog

Introduction to Higher Order Functions

June 18, 2022·1 min read

A higher order function (HOF) takes one or more functions as arguments, returns a function as a result, or both. They're supported across Python, C++, JavaScript, and most modern languages.

The three essential HOFs built into most languages are map, reduce, and filter.

1. map

map(function, iterable) applies a function to each item in an iterable.

import math

list_of_nums = [1, 5, 10, -5, 8, -4, 3]

def my_function(x):
    if x < 0:
        return 0
    else:
        return math.pow(x, 2)

result = list(map(my_function, list_of_nums))
# [1, 25, 100, 0, 64, 0, 9]

2. reduce

reduce(function, iterable) accumulates values from left to right. The function must take two arguments. Available in Python's functools module.

import functools

list_of_nums = list(range(1, 101))
total = functools.reduce(lambda x, y: x + y, list_of_nums)
# 5050

This computes ((((1+2)+3)+4)+5)...+100).

3. filter

filter(function, iterable) keeps items where the function returns True.

list_of_chars = ['A', 'B', 'c', 'D', 'e', 'F']
filtered = list(filter(lambda x: x.isupper(), list_of_chars))
# ['A', 'B', 'D', 'F']

Code available on GitHub.