Skip to the workspace
Pebellslearn by building
Programming Paradigms  ›  Lesson

Functional Programming and Pure Functions

Functional Programming 15 minFunctional programming builds programs from pure functions that return new values instead of changing shared state.

software design architecture / Functional Programming and Pure Functions

Explore each scene at your own pace.

01 · The rule

The rule

Functional Programming and Pure Functions

A Shelfwise test for add_tax passes in the morning and fails in the evening. The code has not changed. The reason: add_tax quietly reads the current region from a global setting and writes the new total into the cart. Functional programming is a way of writing code where that kind of surprise cannot happen.

The rule

Same input, same output, and nothing else touched.

That describes a pure function:

  1. Same input, same output. Its result depends only on its arguments, not on the clock, a global or a database.
  2. Nothing else touched. It has no side effects: it does not change its arguments, write files, print, or save.
# Impure: hidden input and two side effects
def add_tax(cart):
    cart.total = cart.total * (1 + TAX_RATES[current_region()])
    save(cart)

# Pure: everything it needs comes in, one value goes out
def with_tax(total, rate):
    return total * (1 + rate)

Functional programming builds programs mostly out of pure functions, plus two more habits:

  • Immutable data. Instead of changing a value, make a new one: new_lines = lines + [line] rather than lines.append(line).
  • Functions as values. Pass functions to other functions. sorted(books, key=lambda b: b.price) hands sorted a small function that says how to compare.

A program still has to save orders and send emails, so side effects do not vanish. They move to the edges: a thin layer of impure code gathers inputs, calls pure functions to do the thinking, then writes the results out.

The payoff is testing and reasoning. A pure function needs no setup and no mocks: call it, compare the answer. It can never break because of what ran before it.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.