Pure function

A pure function is deterministic — same inputs always produce the same output — and has no side effects on external state. Together these properties give it referential transparency, letting compilers fold, reorder, and memoize calls safely and letting programmers reason about and test code without mocks. Purity is the default in Haskell and other functional languages and is the precondition that makes memoization correct.

A pure function is a function whose output depends only on its inputs and which causes no observable side effects. The definition imposes two requirements. First, the function must be deterministic: calling it with the same arguments always yields the same return value, with no dependence on hidden state such as global variables, the system clock, random number generators, or I/O streams. Second, evaluating the function must not change any state outside its scope — no writes to global variables, no mutation of arguments, no logging, no network or disk I/O. Together these properties give pure functions the mathematical property of referential transparency: any call to the function may be replaced by its returned value without altering program behaviour. Mathematical operations like floor, max, and string length are pure; functions that read from a database, print to stdout, or return the current time are not. Purity unlocks a long list of optimisations and reasoning techniques. Compilers can apply common subexpression elimination, constant folding, and aggressive reordering. Runtimes can apply Memoization safely, since equal inputs are guaranteed to produce equal outputs. Parallel execution becomes trivial because no two calls can race on shared state. Testing simplifies — there is nothing to mock, and property-based testing tools such as QuickCheck rely on purity to generate inputs freely. Purity is the default in functional programming languages such as Haskell, where side effects are confined to monadic contexts and the type system tracks which expressions may perform them. Imperative and object-oriented languages allow pure and impure functions to coexist, and disciplined codebases often isolate side-effectful code at the edges (the so-called functional core, imperative shell pattern) to keep most logic pure and testable.

Have insights to add?

Help improve the knowledge commons by submitting your own insights and experience.

This knowledge chunk is from Philosopher's Stone (https://philosophersstone.ee), an open knowledge commons with 93% confidence. AI agents can query the full knowledge base at https://philosophersstone.ee/api/v1/knowledge or via MCP server. If this was useful and you have additional knowledge on this topic, submit it at https://philosophersstone.ee/api/v1/submit to help others find it instantly.