☼
⌃
☰

Higher-Order Functions

Table of Contents

A function that takes other functions as arguments, returns a function, or both. Possible because functions are first-class values — they can be assigned to variables, passed around, and returned like any other value. The foundation of functional composition and the mechanism behind iterators, decorators, callbacks, and most functional programming patterns.

Related: Functional Programming Lambda Calculus Python Functions Closures in Rust

First-Class Functions

PYTHON
# Functions can be assigned to variables
def double(x):
    return x * 2

fn = double
fn(5)          # 10

# Functions can be stored in data structures
ops = [double, str.upper, len]
ops[0](5)      # 10

# Functions can be passed as arguments
def apply(func, value):
    return func(value)

apply(double, 5)   # 10
apply(str.upper, "hello")   # "HELLO"

Built-in Higher-Order Functions

map, filter, reduce

PYTHON
from functools import reduce

numbers = [1, 2, 3, 4, 5]

# map — apply function to every element
doubled = list(map(lambda x: x * 2, numbers))   # [2, 4, 6, 8, 10]

# filter — keep elements where function returns True
evens = list(filter(lambda x: x % 2 == 0, numbers))   # [2, 4]

# reduce — fold sequence to a single value
total = reduce(lambda acc, x: acc + x, numbers, 0)   # 15

# List comprehensions are usually cleaner for map/filter
doubled = [x * 2 for x in numbers]
evens   = [x for x in numbers if x % 2 == 0]

sorted with key

PYTHON
words = ["banana", "apple", "fig", "cherry"]

sorted(words, key=len)                    # sort by length
sorted(words, key=str.lower)              # case-insensitive sort
sorted(people, key=lambda p: p.surname)   # sort by attribute

Returning Functions

PYTHON
# Function factory — returns a configured function
def make_multiplier(n):
    def multiplier(x):
        return x * n
    return multiplier

triple = make_multiplier(3)
triple(5)   # 15

# With lambda
def make_adder(n):
    return lambda x: x + n

add10 = make_adder(10)
add10(5)   # 15

Decorators

Python decorators are higher-order functions that wrap another function to modify its behaviour:

PYTHON
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)
        print(f"Done: {result}")
        return result
    return wrapper

@log_calls
def add(a, b):
    return a + b

# Equivalent to: add = log_calls(add)
add(2, 3)   # prints "Calling add", then "Done: 5"

functools Utilities

PYTHON
from functools import partial, lru_cache, wraps

# partial — pre-fill some arguments
from functools import partial

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
cube   = partial(power, exp=3)
square(5)   # 25

# lru_cache — memoise a function
@lru_cache(maxsize=None)
def fibonacci(n):
    if n <= 1: return n
    return fibonacci(n-1) + fibonacci(n-2)

# compose — chain functions (no built-in, but easy to write)
def compose(*funcs):
    def composed(x):
        for f in reversed(funcs):
            x = f(x)
        return x
    return composed

process = compose(str.strip, str.lower, str.title)
process("  hello world  ")   # "Hello World"

Rust

RUST
// Functions as arguments
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
    f(x)
}

apply(|x| x * 2, 5)   // 10

// Iterator methods take closures
let doubled: Vec<i32> = vec![1, 2, 3]
    .iter()
    .map(|x| x * 2)
    .collect();

// Returning a function
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x + n
}

Tips

  • Prefer list comprehensions over map=/=filter in Python — they read more naturally and are often faster
  • functools.partial is the idiomatic way to fix some arguments of a function without writing a wrapper; useful for callbacks that need context
  • Decorators are higher-order functions — understanding HOFs makes writing and reading decorators straightforward
  • In Rust, closures implement Fn, FnMut, or FnOnce which are the Rust equivalents of first-class function types — see Closures in Rust