Pure Function (Computer Science)
A function is considered a Pure Function if
- for identical arguments, it produces identical return values
- it is side effect free
In this context, a Pure Function is similiar to a mathematical function.
Referential Transparency
If a function is pure, it is referential transparent
Example
Pure Function
The following function
translates to JavaScript
const f = x => x * x;
The function conforms to the definition of a Pure Function:
- for each input it always returns .
- It is side effect free (i.e. it does not change the state of any other variable)
Impure Function
Whereas the following functions are considered impure:
function f (x) {
return this.x * x;
}
The method violates 1.
of the above definition for a Pure Function: It produces variants because of the non-local-variable
this.x
. The state of this.x
is unclear to f
, the result is nondeterministic.
function f (x) {
this.x = x;
}
The method violates 2.
of the above definition for a Pure Function: Although it always produces undefined
for the
given input x
, it is not side effect free since it changes the non-local variable this.x
.
see also