» 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. Es decir, el resultado sólo depende de los argumentos que recibe la función, no de un estado global que pueda variar durante la ejecución del programa ni de canales I/O.
- has no side-effects: it does not modify mutable objects neither emit info through the I/O channels.
- 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 función 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.