In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, a pure function is a
function
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-oriente ...
that has the following properties:
# the function
return values
Return may refer to:
In business, economics, and finance
* Return on investment (ROI), the financial gain after an expense.
* Rate of return, the financial term for the profit or loss derived from an investment
* Tax return, a blank document or t ...
are
identical for identical
arguments
An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialectic ...
(no variation with local
static variable
In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
s,
non-local variables, mutable
reference arguments or
input streams), and
# the function has no
side effects (no mutation of local static variables, non-local variables, mutable reference arguments or input/output streams).
Thus a pure function is a computational analogue of a
mathematical function
In mathematics, a function from a set to a set assigns to each element of exactly one element of .; the words map, mapping, transformation, correspondence, and operator are often used synonymously. The set is called the domain of the functi ...
. Some authors, particularly from the imperative language community, use the term "pure" for all functions that just have the above property 2
(discussed
below).
Examples
Pure functions
The following examples of
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
functions are pure:
Impure functions
The following C++ functions are impure as they lack the above property 1:
The following C++ functions are impure as they lack the above property 2:
The following C++ functions are impure as they lack both the above properties 1 and 2:
I/O in pure functions
I/O is inherently impure: input operations undermine
referential transparency
In computer science, referential transparency and referential opacity are properties of parts of computer programs. An expression is called ''referentially transparent'' if it can be replaced with its corresponding value (and vice-versa) withou ...
, 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
In compiler theory, loop optimization is the process of increasing execution speed and reducing the overheads associated with loops. It plays an important role in improving cache performance and making effective use of parallel processing capabi ...
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 0= ;
int l = 0;
for (int i = 0; i < 10; ++i)
can be optimized such that the value of
s.length()
is computed only once, before the loop.
Some programming languages allow for declaring a pure property to a function:
* In
Fortran and D, the
pure
keyword can be used to declare a function to be just side-effect free (i.e. have just the above property 2). The compiler may be able to deduce property 1 on top of the declaration.
* In the
GCC, the
pure
attribute specifies property 2, while the
const
attribute specifies a truly pure function with both properties.
* Languages offering
compile-time function execution may require functions to be pure, sometimes with the addition of some other constraints. Examples include
constexpr
of C++ (both properties).
constexpr attribute in C++
/ref>
Unit testing
Since pure functions have identical return values
Return may refer to:
In business, economics, and finance
* Return on investment (ROI), the financial gain after an expense.
* Rate of return, the financial term for the profit or loss derived from an investment
* Tax return, a blank document or t ...
for identical arguments
An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialectic ...
, they are well suited to unit testing
In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures&md ...
.
See also
* Compile-time function execution: the evaluation of pure functions at compile time
* Deterministic algorithm
In computer science, a deterministic algorithm is an algorithm that, given a particular input, will always produce the same output, with the underlying machine always passing through the same sequence of states. Deterministic algorithms are by far ...
* Purely functional data structure
In computer science, a purely functional data structure is a data structure that can be implemented in a purely functional language. The main difference between an arbitrary data structure and a purely functional one is that the latter is (strong ...
* Lambda calculus
* Side effect (computer science)
* Pure procedure
* Idempotence
Idempotence (, ) is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. The concept of idempotence arises in a number of pl ...
* pure
Pure may refer to:
Computing
* A pure function
* A pure virtual function
* PureSystems, a family of computer systems introduced by IBM in 2012
* Pure Software, a company founded in 1991 by Reed Hastings to support the Purify tool
* Pure-FTPd, F ...
keyword in Fortran annotating pure functions
* constexpr keyword in C++ annotating pure functions usable at compile-time
References
{{Reflist
Functional programming
Subroutines