~ / track D / fp foundations

Purity vs side effects

Basic

A pure function depends only on its inputs and only produces a return value — same input, same output, no observable trace left in the world. A side effect is anything else: printing, reading a file, mutating state, calling the network, asking for the current time. You can't avoid effects (a program that does nothing is not useful), but you can push them to the edges and keep the core pure.

Minimal example

square is pure — call it as many times as you like with 5, you always get 25, and nothing else happens:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

println returns nil but leaves a mark on the world (the printed line). It's the same function call, but the output panel shows the effect separately from the value:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

Practical example

Keeping the calculation pure and the effect separate makes both easier to test and to reuse. Here total is pure; only the outer form does the printing:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

Notice: you can read the body of total and reason about it without thinking about printing at all. That's the win.

Exercise

Split the following effectful function into a pure discount (no printing) and a thin caller that prints the result. Verify the pure function returns the same value twice.

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate
 status: new