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 program's 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:
- Proving that the program or code is correct—that it does exactly what it's supposed to, no matter what.
- Making an algorithm more simple.
- Making it easier to change the code while still being sure that it does what it's supposed to.
- Making the code run faster or in a way that uses up less memory.
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).
References[change | change source]
- "Referential transparency - HaskellWiki". wiki.haskell.org. Retrieved 2019-05-22.
- "What is referential transparency?". LispCast. 2019-04-18. Retrieved 2019-05-22.
- "r/programming - Functional Programming Went Mainstream Years Ago". reddit. Retrieved 2019-05-22.
- "terminology - What is the difference between a "function" and a "procedure"?". Stack Overflow. Retrieved 2019-05-22.