ⓘ Referential transparency


ⓘ Referential transparency

Referential transparency is a feature of parts of computer programs. A part of a program is called "referentially transparent" if it can be replaced with the value it gives back without changing the programs behavior. A referentially transparent function must be pure - it must always give the same output if it takes the same input, and it must not have any side effects - parts of the program that perform an action other than giving a value back. The opposite of referential transparency is referential opacity.

In mathematics, all functions are referentially transparent, because a mathematical function can only take values in and spit a value out. In programming, this is not always true - a function might also find out what day of the year it is, or print a message to the screen. Because of this difference, some people use other names for functions in programming, like procedures.

Referential transparency lets programmers and compilers to think of code as a rewrite system - something that takes an expression and replaces it with something else. This can help with several tasks, such as:

  • Making the code run faster or in a way that uses up less memory.
  • Making an algorithm more simple.
  • Making it easier to change the code while still being sure that it does what its supposed to.
  • Proving that the program or code is correct - that it does exactly what its supposed to, no matter what.

There are several ways of doing the last task - the most well-known are memoization saving answers after the first time, common subexpression elimination figuring out if it is worth it to combine two parts of the code that are the same, lazy evaluation not finding the answer until the code really needs it, and parallelization working on multiple problems at the same time.