Jump to content

Referential transparency

From Simple English Wikipedia, the free encyclopedia

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.[1][2] The opposite of referential transparency is referential opacity.[3]

In mathematics, most functions are referentially transparent, because a mathematical function can only take values in and spit a value out. There are some exceptions, due to some historically convenient functions, which can help highlight the notion of referential transparency. For example, means "apply the function twice", or . If making statements that apply to functions , then means this, regardless of the function. For specific functions (usually trig functions like sine, cosine, etc), mathematicians use the square notation to mean "square the output". For example, means which is not the same as . This is an example of referential opacity because when happens to be sine does not mean the same thing as , so substituting sine in for f changes the meaning of the statement.

In programming, 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.[4]

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]
  1. "Referential transparency - HaskellWiki". wiki.haskell.org. Retrieved 2019-05-22.
  2. "What is referential transparency?". LispCast. 2019-04-18. Retrieved 2019-05-22.
  3. "r/programming - Functional Programming Went Mainstream Years Ago". reddit. Retrieved 2019-05-22.
  4. "terminology - What is the difference between a "function" and a "procedure"?". Stack Overflow. Retrieved 2019-05-22.