Functional Programming: Pure Functions and Immutable Data

A programming paradigm is a style of organising computation. In the imperative paradigm you write commands that change memory step by step. In the functional programming paradigm you build a program from functions that compute values from their inputs, and you avoid changing data once it exists. Languages designed around this idea include Haskell, OCaml, F#, Elixir and Clojure, and the same style is common in Python, JavaScript, Java and C#. This lesson covers pure functions, referential transparency, immutable data and recursion as a way to express repetition.

Pure functions and side effects

A pure function is one whose result depends only on its arguments and whose evaluation has no side effects. A side effect is an observable interaction beyond returning a value, such as reassigning a global variable, modifying an argument in place or printing. Reading the clock also makes a function impure because its result depends on external state. Other I/O likewise interacts with the environment. For inputs on which it returns a value, a pure function obeys this rule:


x=y  ⟹  f(x)=f(y),and evaluating f(x) changes nothing elsex = y \;\Longrightarrow\; f(x) = f(y), \quad \text{and evaluating } f(x) \text{ changes nothing else}


The two Python functions below compute the same area, but only the first is pure.


Python
def area(w, h):          # pure
    return w * h

log = []
def area_logged(w, h):   # impure: appends to a global list
    log.append((w, h))
    return w * h


Two diagrams compare a pure square function that maps 3 to 9 with an impure function that maps 3 to 13 while reading and changing a shared variable named total.


Referential transparency

An expression has referential transparency when replacing it by its value does not change the program's observable behaviour. A pure call that returns a value supports this substitution, letting you reason about code as you simplify algebra: substitute equals for equals.


Example: with the pure area, the expression area(4, 5) + area(4, 5) may be rewritten as 2 * area(4, 5), and both give 40. With area_logged the same rewrite still returns 40 but leaves one entry in log instead of two, so the behaviour of the program has changed.


Purity supports optimisations such as memoization, removing unused computations and evaluating independent calls in parallel. Such transformations must preserve observable behaviour, including termination, under the language's evaluation rules. In an eager program, removing an unused pure call that never returns could make a previously nonterminating program finish. Transformations involving impure calls can also be safe when their observable effects and termination behaviour are preserved. Testing pure functions is simpler because you can supply inputs and check outputs without preparing hidden state.



Immutable data and recursion

Functional programs treat data as immutable: once a value is built it is never modified. To update a list you build a new one. In Haskell, ys = 0 : xs creates a list whose head is 0 and whose tail is the existing xs; xs itself is unchanged. The lists share structure, so the existing tail need not be copied.


Recursion expresses a computation through self-reference: a function calls itself directly or indirectly. It is a common way to express repetition in pure functional code, and its inputs need not become smaller. In the factorial example below, recursive calls make progress toward a reachable base case that stops the recursion. Loops do not inherently require a mutable counter; for example, iteration can traverse a collection without an explicitly changing counter. The functional emphasis is on computing successive values without mutating existing data.


For a non-negative integer, factorial can be defined as follows:


haskell
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)


By substitution, factorial 3 becomes 3 * factorial 2, then 3 * 2 * factorial 1, then 3 * 2 * 1 * factorial 0, which is 3 * 2 * 1 * 1 = 6. Each call has its own n; no variable is reassigned. For any non-negative integer input, subtracting 1 on each recursive call eventually reaches the base case factorial 0 = 1.


Aspect

Typical imperative style

Typical pure functional style

Basic unit

Statement that changes state

Expression that produces a value

Variables

Reassigned over time

Bound once to a value

Repetition

Loops, often with state updates

Recursion or collection operations

Updating data

Modify in place

Build a new value

Effects such as I/O

Interleaved with computation

Kept at the edges or tracked by types



What to remember

  • A pure function's result depends only on its arguments, and calling it has no side effects.
  • Referential transparency supports substitution; optimisations must also preserve evaluation and termination behaviour.
  • Functional programs build new values instead of modifying existing ones.
  • Recursion uses self-reference; the factorial example terminates by progressing toward a reachable base case. Loops do not inherently require mutable counters.

Example: Tracing and purifying a digit-sum function

A checksum routine adds the decimal digits of a non-negative account number. The Haskell version is:


haskell
sumDigits :: Int -> Int
sumDigits 0 = 0
sumDigits n = (n `mod` 10) + sumDigits (n `div` 10)


A Python port adds a global counter for profiling:


Python
calls = 0

def sum_digits(n):
    global calls
    calls += 1
    if n == 0:
        return 0
    return n % 10 + sum_digits(n // 10)


A proposed replacement for the profiling version returns the count alongside the sum:


haskell
sumCount :: Int -> (Int, Int)
sumCount 0 = (0, 1)
sumCount n = (n `mod` 10 + s, c + 1)
  where (s, c) = sumCount (n `div` 10)


a) Evaluate sumDigits 4729 by substitution, and count how many times sumDigits is called in total.


Each recursive step keeps the last digit with mod 10 and drops it with div 10:

  • sumDigits 4729 keeps 9 and calls sumDigits on 4729 div 10, which is ________.
  • sumDigits 472 keeps 2 and calls sumDigits on ________.
  • sumDigits 47 keeps 7 and calls sumDigits on ________.
  • sumDigits 4 keeps 4 and calls sumDigits 0, the base case, which returns ________.

Because sumDigits is pure, each call can be replaced by its definition, and the pieces add up:


sumDigits 4729=9+2+7+4+0=22\text{sumDigits } 4729 = 9 + 2 + 7 + 4 + 0 = 22


The calls were on 4729, 472, 47, 4 and 0: one per digit plus the base case. The digit sum is 22, computed with 5 calls.


b) Starting from calls = 0, the program runs x = sum_digits(58) and then y = sum_digits(58). Find x, y and the value of calls afterwards, and decide whether sum_digits is pure.


One evaluation of sum_digits(58) runs the function on 58, 5 and 0, so calls rises by ________. It returns 8+5+0=138 + 5 + 0 = 13, so x=13x = 13 and y=13y = 13.


After both lines, calls is 3+3=63 + 3 = 6.


The function is not pure. Its return value depends only on n, but every call also writes to the global calls. Test referential transparency: replacing the second line with y = x gives the same y, yet leaves calls at 3 instead of 6, so the program now behaves differently. A call that cannot be replaced by its value is not pure.


c) Evaluate sumCount 58, and explain why sumCount is pure while still reporting the call count.


Work from the base case outward. sumCount 0 returns (0,1)(0, 1). For sumCount 5, the where clause binds (s,c)=(0,1)(s, c) = (0, 1), so the result is (5 + 0, 1 + 1) = (5, ________).


For sumCount 58, the where clause binds (s,c)=(5,2)(s, c) = (5, 2), so


sumCount 58=(8+5, 2+1)=(13, 3)\text{sumCount } 58 = (8 + 5,\ 2 + 1) = (13,\ 3)


The function is pure: its result depends only on n, and it changes no variable outside itself. The count travels in the return value instead of a global, so calling sumCount 58 twice gives (13,3)(13, 3) both times, and a caller who wants a running total adds the counts explicitly, 3+3=63 + 3 = 6, matching part b without any hidden state.

Match each term from the functional programming paradigm with the description that defines it. Each description is used exactly once.

Match each term
A.

Values that are never modified after creation, so an update builds a new value

B.

The property that an expression can be swapped for its value without altering program behaviour

C.

Any observable change a call makes beyond returning a value, such as printing or updating a global

D.

A function definition that refers to the function itself, directly or indirectly

E.

Returns a result fixed by its arguments alone and changes nothing outside itself

F.

The input for which a recursive definition returns directly without calling itself

Recursion

Base case

Pure function

Side effect

Immutable data

Referential transparency

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

The functional languages below each added an idea that later languages built on. Arrange them in the order in which they first appeared, earliest first.

  1. 1.

    Lisp, John McCarthy's list-processing language built on recursive functions

  2. 2.

    Clojure, a Lisp dialect for the Java Virtual Machine with immutable collections by default

  3. 3.

    ML, the meta-language of the LCF theorem prover, with polymorphic type inference

  4. 4.

    Miranda, David Turner's lazy and purely functional language

  5. 5.

    Haskell, a lazy, purely functional language designed by a committee to unify research languages

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A code review examines the following Python functions. Assume ordinary numeric arguments and built-in Python lists. Select every statement that is true about whether a function is pure.


Python
import random

def clamp(x, lo, hi):
    return max(lo, min(x, hi))

def with_item(stack, item):
    return stack + [item]

def push(stack, item):
    stack.append(item)
    return stack

def roll():
    return random.randint(1, 6)
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice