Pure function

» Glossary » Pure function

A function is considered to be pure if it has the following properties:

  • deterministic: provided with the same arguments, it returns always the same results. The output is only dependant on the input — there is no global state or I/O values that can change with time the result of the operation.
  • has no side-effects: it does not modify mutable objects neither emit info through the I/O channels.

Examples:

  • a function sin(x), that returns the sin of a given number, it is considered a pure function.
  • printf() or any other function that emits data by I/O, is impure.
  • a function inc(x), that increments the value of x with a global variable is also impure for two reasons: it modifies the state of a mutable element, and the result depends on a global variable that can change through the program execution. Functions that receive parameters by reference are, in general, impures, as they allow for the modification of the mutable elements.

Pure functions are a fundamental concept in functional programming. Its value is derived from better code readability, optimisation, and testability.

Related: