Referential transparency

from Wikipedia, the free encyclopedia

The referential transparency states that the value of an expression in a source depends only on its environment and not from the date of evaluation. This is an important property of the declarative programming paradigm .

In mathematics, one and the same variable always has the same value at different points in its scope. This does not apply in imperative programming languages , since the program semantics (e.g. the end result) depends on an implicit state (e.g. the memory content).

x = x + 1

In the usual mathematical interpretation, this line describes a false statement, which means that there is no x that makes the equation true. In many imperative programming languages, such as C ++ and Java , which are based on the C syntax , the equal sign is the assignment operator . There the line represents a valid instruction : Depending on what stands for x in the memory cell , a value is calculated on the right-hand side and the result is assigned to the left-hand side. Such side effects make the mathematical proof of correctness ("Does the program really deliver what it should?") Considerably more difficult .

In declarative programming, however, the principle of referential transparency applies and, as a consequence, the principle of substitution . After that, an expression can always be replaced by another of the same value without affecting the program semantics. The goal of such a program transformations is the replacement of complex by easy to be calculated expressions.

However, the principle of referential transparency also poses problems. It is not possible to simply read out a character entered with the keyboard; such a function - as getcharin C - is not allowed. Each time the return value would depend on what the user entered. This would cause communication problems with the environment.

So z. For example, in the functional programming language Haskell, actions that can interact with the environment are IOdescribed as values ​​of the data type . Using special operators, complex descriptions can be constructed from elementary action descriptions. Each Haskell program defines a variable main, the value of which is an action description of the entire program. Actions can be performed by mainembedding their description in the value of .