Pure function


In computer programming, a pure function is a function that has the following properties:
  1. Its return value is the same for the same arguments.
  2. Its evaluation has no side effects.
Thus a pure function is a computational analogue of a mathematical function. Some authors, particularly from the imperative language community, use the term "pure" for all functions that just have the above property 2.

Examples

Pure functions

The following examples of C++ functions are pure:
void f

Impure functions

The following C++ functions are impure as they lack the above property 1:
int f

int f

void f

The following C++ functions are impure as they lack the above property 2:
void f

void f

void f

void f

The following C++ functions are impure as they lack both the above properties 1 and 2:
int f

int f

I/O in pure functions

I/O is inherently impure: input operations undermine referential transparency, and output operations create side effects. Nevertheless, there is a sense in which function can perform input or output and still be pure, if the sequence of operations on the relevant I/O devices is modeled explicitly as both an argument and a result, and I/O operations are taken to fail when the input sequence does not describe the operations actually taken since the program began execution.
The second point ensures that the only sequence usable as an argument must change with each I/O action; the first allows different calls to an I/O-performing function to return different results on account of the sequence arguments having changed.
The I/O monad is a programming idiom typically used to perform I/O in pure functional languages.

Compiler optimizations

Functions that have just the above property 2 allow for compiler optimization techniques such as common subexpression elimination and loop optimization similar to arithmetic operators. A C++ example is the length method, returning the size of a string, which depends on the memory contents where the string points to, therefore lacking the above property 1. Nevertheless, in a single-threaded environment, the following C++ code

std::string s = "Hello, world!";
int a = ;
int l = 0;
for

can be optimized such that the value of s.length is computed only once, before the loop.
In Fortran, the pure keyword can be used to declare a function to be just side-effect free.

Unit Testing

Since pure functions have the same return value for the same arguments, they are well suited to unit testing.