Pure functions
A function is pure when:
- Its result depends only on its arguments, so the same inputs always give the same output.
- It has no side effects: it doesn’t change a variable outside itself, write a file, or print.
add(2, 3) is pure. A function that reads the clock, or appends to a global list, isn’t. Pure functions are easy to test, because there’s no setup, and easy to reason about, because you can read them alone.
Real programs need side effects; saving a file is the whole point sometimes. Functional style pushes them to the edges, keeping the core logic pure.
Immutability
Instead of changing data in place, make a new version. sorted(scores) returns a new list; scores.sort() changes the old one. When nothing changes in place, a value you’re holding can’t be altered behind your back by other code, or by another thread.
Map, filter, reduce
Three higher-order functions, functions that take other functions, cover most loops over a collection:
| Function | Does | Example |
|---|---|---|
filter |
Keeps the items a test says yes to | Keep the even numbers |
map |
Transforms every item | Square each one |
reduce (or fold) |
Combines all items into one value | Add them up |
The example chains all three to add up the squares of the even numbers:
from functools import reduce
def sum_of_even_squares(numbers):
# Each step is a function passed to another function. Nothing is
# changed in place: every step builds a new sequence from the last.
evens = filter(lambda n: n % 2 == 0, numbers) # keep some
squares = map(lambda n: n * n, evens) # transform each
return reduce(lambda total, n: total + n, squares, 0) # combine into one// Each step is a function passed to another function. Nothing is
// changed in place: every step builds a new array from the last.
function sumOfEvenSquares(numbers) {
return numbers
.filter((n) => n % 2 === 0) // keep some
.map((n) => n * n) // transform each
.reduce((total, n) => total + n, 0); // combine into one
}// Go has no built-in map or filter, but generic functions can take
// other functions as arguments, which is all they need.
func Filter[T any](xs []T, keep func(T) bool) []T {
var out []T
for _, x := range xs {
if keep(x) {
out = append(out, x)
}
}
return out
}
func Map[T, U any](xs []T, f func(T) U) []U {
out := make([]U, 0, len(xs))
for _, x := range xs {
out = append(out, f(x))
}
return out
}
func Reduce[T, A any](xs []T, start A, f func(A, T) A) A {
acc := start
for _, x := range xs {
acc = f(acc, x)
}
return acc
}
func sumOfEvenSquares(numbers []int) int {
evens := Filter(numbers, func(n int) bool { return n%2 == 0 }) // keep some
squares := Map(evens, func(n int) int { return n * n }) // transform each
return Reduce(squares, 0, func(total, n int) int { return total + n }) // combine into one
}// Each step is a closure passed to an iterator method. Nothing is changed
// in place, and nothing runs until fold asks for the values.
fn sum_of_even_squares(numbers: &[i64]) -> i64 {
numbers
.iter()
.filter(|&&n| n % 2 == 0) // keep some
.map(|&n| n * n) // transform each
.fold(0, |total, n| total + n) // combine into one
}Python’s more common style is a comprehension, sum(n * n for n in numbers if n % 2 == 0), which is the same pipeline in one line. Go has no built-in map or filter, but generic functions that take functions as arguments are all it takes to write them. Rust’s iterators are lazy: nothing runs until fold asks for values, and the whole chain compiles to a single loop.
The small functions passed in, like n => n * n, often capture variables from around them. That’s a closure.
Common mistakes
- Side effects inside
map. Amapthat also writes to a database is a loop pretending to be pure. Use a plain loop when the point is the side effect. - Unreadable chains. Ten chained steps with nested lambdas is harder to read than a loop. Name the steps.
- Copying huge data every step. Building a new list each step costs memory. Lazy iterators, generators and persistent data structures avoid most of it.
Check yourself
Check yourself
Which function is pure?
The larger of two numbers depends only on the inputs and changes nothing. The clock gives different results each call, and appending changes outside state.
Check yourself
You want the total price of all items in a cart. Which tool combines a list into one value?
reduce folds a list into a single value, here by adding each price to a running total. map would give a list of prices, and filter a shorter list of items.
Sources
- John Hughes, “Why Functional Programming Matters,” The Computer Journal 32, no. 2 (1989): 98–107.
- Harold Abelson and Gerald Jay Sussman, Structure and Interpretation of Computer Programs, 2nd edition (1996), chapters 1–3.
Finished this page?
Your list