Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 57 ยท Laziness and purity

Purity and Referential Transparency

Understand pure functions, referential transparency and equational reasoning in Haskell, and why purity makes code easier to test, refactor and optimise.

A pure function has two properties: for the same arguments it always returns the same result, and it does nothing else. It does not print, read a file, change a global variable or ask what time it is. Everything it does is visible in its return value.

Haskell takes this seriously. Ordinary functions are pure, and the type system keeps effects separate: a function that can perform input or output says so in its type with IO. This lesson explains what that buys you, namely referential transparency, equational reasoning, easy testing and freedom for the compiler.

Haskell is read-only on this site. The runnable examples are JavaScript stand-ins, which make the contrast between pure and impure code easy to see.

What counts as a side effect

A function is impure if it depends on or changes something outside its arguments:

  • reading or writing files, the network or the terminal,
  • reading the clock or a random number generator,
  • mutating a variable or object that other code can see,
  • throwing an exception in the middle of an expression (in Haskell, error is considered a bug, not a normal control-flow tool).

Here is a pure function and its signature:

HASKELL
discount :: Double -> Double -> Double
discount rate price = price * (1 - rate)

Nothing in the type mentions IO, so discount 0.1 50 can only compute 45.0. The type is a guarantee. Compare the signature of something impure:

HASKELL
readPrice :: FilePath -> IO Double

The IO tag says "running this may touch the outside world". You will see how it works in IO Basics. The important point is that the effect shows up in the type, so the compiler stops you from sneaking it into a pure function.

Pure function checklist

Same input Same output, every time.
No effects No printing, files, clocks or mutation.
Honest type IO in the type means effects may happen.
1 / 2

Referential transparency

An expression is referentially transparent if you can replace it with its value anywhere in the program without changing what the program does. For pure code this always holds. If square 4 is 16, then these two programs are identical:

HASKELL
area1 = square 4 + square 4
area2 = 16 + 16
area3 = let s = square 4 in s + s    -- also identical

The third form computes square 4 once and shares it, which the compiler may do on its own because it knows the answer cannot change. In an impure language this move is unsafe. If next() returned a different number each call, next() + next() would not equal let n = next() in n + n.

This property is also why Haskell can be lazy (see Lazy Evaluation): it does not matter when a pure expression is evaluated, or even whether it is evaluated twice, since the value is always the same.

Equational reasoning

Because replacement is always allowed, you can reason about programs the way you do in algebra: substitute equals for equals. Definitions really are equations:

HASKELL
double :: Int -> Int
double x = x + x

quadruple :: Int -> Int
quadruple x = double (double x)

To check quadruple 3, rewrite step by step:

HASKELL
quadruple 3
= double (double 3)
= double (3 + 3)
= double 6
= 6 + 6
= 12

Each line follows from a definition. You can do the same to prove general statements. A tiny proof that map distributes over ++:

HASKELL
map f (xs ++ ys) = map f xs ++ map f ys

holds by induction on xs, using the definitions of map and ++. Or consider a refactoring: is length (map f xs) the same as length xs? Yes, since map does not change the number of elements. Such laws let you simplify code, and GHC itself applies rewrite rules like map f (map g xs) = map (f . g) xs when optimising (a technique called fusion).

Compare this with the wrong move in impure code. With [a, b] = [counter++, counter++], there is no equation that tells you what a and b are without running through the whole history of the program.

Equational reasoning is exact only when evaluation terminates. A thunk that loops forever or throws (undefined) is a value called bottom, and laws may hold only "up to bottom". In day-to-day code you rarely need this subtlety.

Why purity helps testing

A pure function needs no setup and no teardown. You supply inputs and check the output:

HASKELL
discount 0.1 50 == 45.0

There are no mocks for the clock, no temporary files and no hidden state from a previous test. Tests are deterministic, fast and can run in parallel. This is also what makes property-based testing natural: you can generate thousands of random inputs and check a law such as reverse (reverse xs) == xs (see Testing: HUnit, Hspec and QuickCheck).

A common architecture follows from this: keep a large pure core that makes all decisions, and wrap it in a thin impure shell that reads input, calls the core and prints the result. The Haskell projects later in the course (Text Adventure Engine for example) use this layout.

HASKELL
-- pure core
summarize :: [Int] -> String
summarize xs = "total: " ++ show (sum xs)

-- impure shell
main :: IO ()
main = do
  contents <- getContents
  putStrLn (summarize (map read (lines contents)))

Only main can fail because of the outside world. summarize can be tested on its own.

Why purity helps the compiler

Since pure calls have no effects, GHC may:

  • share common subexpressions and inline functions freely,
  • reorder or delay computations (laziness depends on this),
  • skip work whose result is unused,
  • fuse pipelines like sum (map f xs) into one loop that builds no intermediate list,
  • parallelise evaluation with confidence that there is no hidden shared state.

None of this changes your program's answer, which is the point.

"But programs must do things"

A program with no effects would be useless, so how does Haskell do I/O? The answer is not to hide effects but to represent them as values. An IO Int is a description of an action that, when run by the runtime, produces an Int. Describing is pure; running happens at the program's edge, from main. Functions that build and combine descriptions (>>=, do blocks) are pure too. The mechanism is the topic of the monad lessons (Monads); for now it is enough to see why getLine is not a String but an IO String.

There are escape hatches such as unsafePerformIO and Debug.Trace.trace. They break the promises above, so they belong in library internals and debugging sessions only.

Pure and impure side by side

JavaScript does not enforce purity, but you can still write pure functions and see the benefits. The first example shows why replacement fails for an impure function.

JS Referential transparency broken and kept (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second example is the pure-core, impure-shell design. The "core" takes the current time as an argument, so tests do not need a clock.

JS A pure core you can test (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The shell is the only part that changes between runs. In Haskell the compiler enforces this split through IO in the type; in JavaScript it is a discipline you keep yourself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is true of a pure function?

    A pure function's entire effect is its return value, which depends only on its arguments.
  2. 2. What does referential transparency let you do?

    Because the expression always means the same value, substituting it is always safe.
  3. 3. What does the type readPrice :: FilePath -> IO Double tell you?

    IO in the result type marks an action that may interact with the outside world.
  4. 4. Why does purity make testing easier?

    There is no hidden state or environment to arrange, so tests are deterministic and cheap.

Summary

  • A pure function depends only on its arguments and has no side effects; Haskell types show effects with IO.
  • Referential transparency means an expression can be replaced by its value anywhere.
  • That allows equational reasoning: substitute definitions step by step to check and refactor code.
  • Pure code is easy to test, including with property-based tests.
  • The compiler can share, reorder, skip, fuse and parallelise pure computations.
  • Good designs keep a pure core and a thin impure shell around it.

Next: Functors.