11.7. Functional Referential Transparency

  • Value of a variable in a functional program never changes once defined

  • This eliminates any chances of side effects

  • Any variable can be replaced with its actual value at any point of execution [2]

Any variable can be replaced with its actual value at any point of execution [2]. This is known as referential transparency. It ensures that the same language expression gives the same output. [1]

Variables, once defined in a functional programming language, aren't allowed to change the value that they hold. However, we can create a new variable. The immutable nature of variables helps preserve the state throughout the program. Assignment statements are discouraged in functional programming. For storing additional values in a program developed using the functional paradigm, new variables must be defined. The state of a variable in such a program is constant at any moment in time. [1]

Referential transparency eliminates the slightest chances of any undesired effects, as any variable can be replaced with its actual value at any point during the program execution. [1]

Bad:

>>> a = 1
>>> a += 2

Good:

>>> a = 1
>>> b = a + 2

11.7.1. Use Case - 0x01

>>> def add(a,b):
...     return a + b
>>>
>>>
>>> x = 1
>>> y = 2
>>>
>>> add(x,y)
3
>>> add(1,y)
3
>>> add(x,2)
3
>>> add(1,2)
3

11.7.2. References