Search

Search papers and lessons

Pure Function

Level 2 · 12 min read

A pure function returns the same output for the same inputs and changes nothing else, which makes its calls safe to cache, test, reorder and run in parallel.

On this page

  • Colour = topic mix
  • Discrete math
  • Programming languages
  • ReadReady to readNot yet

TL;DR

A pure function is a function whose result depends only on its arguments, and which does nothing else: it changes no variable outside itself, prints nothing, reads no hidden state and writes no file. Call it twice with the same inputs and you get the same output both times. Because of this, a call can be replaced by its result without changing what the program does, which makes code easier to test, cache, reorder and run in parallel.

Builds on: Function · Leads to: side effects (what purity rules out), higher-order functions, and the style of functional programming

Where it's used

Caching. A web service that computes a shipping cost from a weight and a postcode can store the answer and return it the next time the same weight and postcode arrive. The cache is safe only because the cost function is pure: nothing else could have changed the answer in between. The cache itself is usually a hash table keyed by the inputs. Storing results of pure calls this way is called memoization, a technique closely related to dynamic programming, and it is one of the most common speed-ups in software.

Parallel data processing. Frameworks such as Apache Spark run one function over millions of rows spread across many machines. If that function is pure, it does not matter which machine handles which row or in what order the rows are processed. Two calls share no state, so they need no locks and cannot cause a race condition with each other. This is the simplest case of data parallelism.

Testing. A pure function is tested with a table of inputs and expected outputs, the pattern behind unit testing. No mock database, clock or network connection is needed. Many teams keep their price, tax and discount formulas in pure functions and keep the database code separate, so the formulas can be checked quickly with plain test cases.

User interfaces. Some UI libraries, React among them, encourage components that are pure functions of their inputs (called props and state). The same data then produces the same screen, so the library can skip redrawing a part of the screen when its inputs have not changed.

How it works

Take two tiny functions that both look like they "add" something. One is pure and one is not.

def double(x):
    return 2 * x               # pure
 
total = 0
 
def add_to_total(x):
    global total
    total = total + x          # not pure: it changes a variable outside itself
    return total
  1. Call the pure function. We call double(4). The input is 4. The function computes 2 times 4, which is 8, and returns it. Check: 2 × 4 = 8.
  2. Call it again with the same input. We call double(4) a second time. It returns 8 again. Nothing was stored between the calls, so the answer can only come from the input. Check: both results are 8, and the input was 4 both times.
  3. Call the impure function once. In the code, global total tells Python that this function means the module-level variable total, not a new local one. total starts at 0. We call add_to_total(4). It sets total to 0 + 4, which is 4, and returns 4. Check: 0 + 4 = 4.
  4. Call it again with the same input. We call add_to_total(4) a second time. Now total is 4, so it becomes 4 + 4 = 8, and the function returns 8. The input was 4 both times but the output changed. The hidden variable total is the cause, and the update to it is a side effect on mutable state. Check: first answer 4, second answer 8, same input.
  5. Move the state out of the function. We write def add(t, x): return t + x. Now the caller keeps the state: add(0, 4) gives 4, and add(4, 4) always gives 8. The function is pure again, because its answer depends only on the two numbers passed in. Check: add(4, 4) = 8 on every call.

The diagram below shows the difference. A pure function is a box with inputs going in and one output coming out. An impure function also reads or writes something outside its box.

flowchart LR
  A["Input x"] --> P["Pure function: 2 times x"]
  P --> O1["Output depends only on x"]
  A --> I["Impure function"]
  H["Hidden variable total"] <--> I
  I --> O2["Output depends on call history"]

The math

Definition

Definition: Pure function

A function ff is pure when its output is determined entirely by its input, and evaluating ff changes nothing else in the program. In a programming language, the second condition means that ff does not read or write any state outside its own arguments and local variables.

An expression is referentially transparent when every occurrence of it can be replaced by its value without changing the meaning of the program. A pure function call is referentially transparent. This is why the two words are often used for the same idea.

Step 1 in symbols: same input, same output

For a pure function, equal inputs always give equal outputs:

x1=x2  ⟹  f(x1)=f(x2).x_1 = x_2 \implies f(x_1) = f(x_2).

In mathematics this holds for every function, which is why pure programming functions are the closest match to the mathematical idea of a Function.

Step 2 in symbols: the hidden variable

Write an impure function as g(x,s)g(x, s), where xx is the argument and ss is the hidden state. The output depends on both:

g(x,s1)≠g(x,s2)for some s1≠s2.g(x, s_1) \neq g(x, s_2) \quad \text{for some } s_1 \neq s_2.

Here the two calls use the same xx but different states s1s_1 and s2s_2, so the outputs can differ. This is exactly what happened with add_to_total in step 4 above.

Step 3 in symbols: moving the state into the arguments

The counter becomes a pure function by passing the state in and returning the new state:

add(t,x)=t+x.\mathrm{add}(t, x) = t + x.

The pair (t,x)(t, x) is the whole input. Calling add(4,4)\mathrm{add}(4, 4) gives 88 every time, so the result does not depend on any call before it.

Step 4 in symbols: replacing a call by its value

If f(4)=8f(4) = 8 holds for a pure ff, then

f(4)+f(4)=8+8=16f(4) + f(4) = 8 + 8 = 16

is the same program as writing 8 twice. For an impure function this substitution fails. In the example, the first call add_to_total(4) returned 4 and the second returned 8. Replacing each call by the value of the first call would give 4 + 4 = 8, but the real sum is 4 + 8 = 12.

Worked examples

Example
1. Is square pure?

Take def square(x): return x * x.

  1. Give it the input x=3x = 3. It computes 3×3=93 \times 3 = 9 and returns 9.
  2. Ask whether it reads anything outside its argument. It does not.
  3. Ask whether it changes anything outside itself. It does not.
  4. Call it again with 3. It returns 9 again.

Answer: square is pure. Its output depends only on its input, and it leaves nothing else changed.

Example
2. A discount with a log line

Take two versions of a discount function. Both compute the price after a discount rate rr as p(1−r)p (1 - r).

Version A: def discount(p, r): return p * (1 - r).

Version B: the same formula, but with a print of the result added before the return.

  1. Call version A with p=80p = 80 and r=0.25r = 0.25. Compute 1−0.25=0.751 - 0.25 = 0.75.
  2. Compute 80×0.75=6080 \times 0.75 = 60. Version A returns 60.
  3. Call version A again with the same values. It returns 60 again. Version A is pure.
  4. Call version B with the same values. It returns 60, and it also prints a line to the screen.
  5. The printed line is an effect outside the function. Version B changes what the program shows, so it is not pure, even though its return value matches version A.

Answer: version A is pure, version B is impure. The returned number is the same in both, but only version A is safe to cache or replay silently.

Example
3. A quote that records its history

A shop computes a quote for a cart, adding 20 percent tax. Here is the first version:

history = []
 
def quote(cart):
    subtotal = sum(cart)
    history.append(subtotal)     # records the call in a global list
    return subtotal * 1.2

Now suppose we want the function to be pure, so the shop can cache quotes.

  1. The subtotal of the cart [10, 25, 5] is 40. This is computed from the argument only.
  2. The tax-inclusive total is 40×1.2=4840 \times 1.2 = 48.
  3. The line history.append(...) changes the global list history. Each call adds a new entry, so the list grows.
  4. Two calls with the same cart return 48 both times, but the global list ends up longer after each call. The program's state has changed.
  5. To make the function pure, remove the history.append line from quote. The caller can then append the result to its own list if it wants a record.

Try it: a function quote(cart) that returns the tax-inclusive total for a cart whose subtotal is 40, and also sets a global variable last_quote to that total. Is it pure? Answer: no. For a subtotal of 40 it returns 48, but it writes to a variable outside itself. Removing the write makes it pure, and the caller stores the result in last_quote instead.

Common mistakes and tradeoffs

It is tempting to think that any function that only returns a value is pure. In fact the result can depend on hidden inputs. A function such as def age(birth_year): return now().year - birth_year returns a different number each year, even though the same birth_year is passed in, because now() reads the clock. Purity depends on everything the function reads, not only on the arguments it is written with.

It is tempting to think that a pure function may never change anything at all. In fact a function may create and change its own local variables freely, because the caller cannot see them. For example, def total(xs): s = 0; for x in xs: s += x; return s is pure, although it updates s many times. The rule concerns changes that escape the function.

It is tempting to think that logging always makes a function impure. In strict terms it does, because the log is an effect outside the function. In practice, teams often keep logging, metrics and I/O at the edges of a program and keep the core calculations pure. Decide where the boundary lies and keep it consistent.

When to use pure functions: whenever the result should depend only on the inputs. They are the right default for calculations, transformations of data, business rules and anything you want to test or cache.

When not to use them: work that must touch the outside world, such as reading a file, sending a network request, or updating a screen, cannot be pure. Some algorithms are also faster when they change data in place rather than building a copy, which is the tradeoff discussed in Immutability. Pure code can allocate more memory than the mutating version.

Alternatives: pass a time, a random number generator or a database connection in as an argument, so the function stays pure while the caller supplies the world. Many functional languages go further and mark effects in the type system, so that the compiler can tell which functions touch the outside world.

History

In the 1930s Alonzo Church developed the lambda calculus, a formal system in which functions take inputs and return outputs with no hidden state. It later became the theoretical base of functional languages.

In the late 1960s Christopher Strachey used the phrase "referential transparency" in his lecture notes on programming languages, borrowing the idea from the philosophy of logic. He used it to describe expressions whose value depends only on what they contain.

In 1977 John Backus argued in his Turing Award lecture that programming should move away from the "von Neumann style" of changing a store of named variables, and toward programs built from functions. His argument made pure functions a central goal of language design.

The first Haskell report was published in 1990. Haskell is pure by default. It keeps effects such as input and output in a separate, explicit part of the type system, expressed through monads. Its design showed that a whole language could be built on pure functions.

People were stuck on the same problem: when functions can change shared state, programs become hard to test and hard to run in parallel, because any call might affect any other. Pure functions removed that problem for the parts of a program that can be written that way, and the idea caught on as hardware and data sizes made parallelism and caching important.

Recap

  • A pure function's output depends only on its inputs.
  • It has no side effects: it changes nothing outside itself and reads no hidden state.
  • Because of this, a call can be replaced by its value, which is called referential transparency.
  • That makes pure functions safe to cache, easy to test, and safe to run in parallel.
  • Next, read side effects to see exactly what purity rules out, then higher-order functions, which are often written in a pure style.

Check yourself

QuestionIn your own words, what two conditions make a function pure?Show answer

The output depends only on the arguments (same inputs always give the same output), and calling the function changes nothing outside itself (no writes to shared variables, no printing, no file or network access).

QuestionLet f(x) = 3x + 1, which is pure. What is f(2) + f(2)?Show answer

f(2) = 3 × 2 + 1 = 7. So f(2) + f(2) = 7 + 7 = 14. Because f is pure, each call can be replaced by its value 7, and the sum is 14.

QuestionWhy can a system safely store the result of a pure function and reuse it later?Show answer

A pure function gives the same output for the same input, and nothing else in the program depends on the call having happened. So a stored result is always what a fresh call would return. If the function read a clock, a random number or a global variable, the stored result could be wrong later.

QuestionA function score(player) returns player.points × 2 and also sets player.last_scored to True. Is it pure? Explain.Show answer

No. It changes the argument object's field last_scored, which is visible to the caller after the call. That is a side effect. The function would be pure if it only returned player.points × 2, and the caller set last_scored itself when it needed to.

Sources