programmingconcepts

§ 4.2 · Paradigms

Functional programming

A style that builds programs from pure functions, avoids changing data in place, and passes functions around like values.

Functional programming is a style that builds programs out of pure functions: functions whose result depends only on their inputs and that change nothing else. Data is treated as immutable, so steps produce new values instead of editing old ones, and functions are passed to other functions. Map, filter and reduce are its everyday tools.

Core idea
Pure functions
Data
Immutable: build new, don't edit
Everyday tools
map, filter, reduce
Languages
Haskell, Elixir, Clojure, F#
Requires
Functions

Pure functions

A function is pure when:

  1. Its result depends only on its arguments, so the same inputs always give the same output.
  2. 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

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

  1. Side effects inside map. A map that also writes to a database is a loop pretending to be pure. Use a plain loop when the point is the side effect.
  2. Unreadable chains. Ten chained steps with nested lambdas is harder to read than a loop. Name the steps.
  3. 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?

Check yourself

You want the total price of all items in a cart. Which tool combines a list into one value?

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.

Newsletter

One new concept each week, by email.

Signup opens soon.