referential transparency


referential transparency

(programming)An expression E is referentially transparent ifany subexpression and its value (the result of evaluating it)can be interchanged without changing the value of E. This isnot the case if the value of an expression depends on globalstate which can change value. The most common example ofchanging global state is assignment to a global variable. Forexample, if y is a global variable in:

f(x){ return x+y; }

g(z)a = f

function g has the "side-effect" that it alters the value ofy. Since f's result depends on y, the two calls to f(1) willreturn different results even though the argument is the same.Thus f is not referentially transparent. Changing the orderof evaluation of the statements in g will change its result.

Pure functional languages achieve referential transparencyby forbidding assignment to global variables. Eachexpression is a constant or a function application whoseevaluation has no side-effect, it only returns a value andthat value depends only on the definition of the function andthe values of its arguments.

We could make f above referentially transparent by passing iny as an argument:

f(x, y) = x+y

Similarly, g would need to take y as an argument and returnits new value as part of the result:

g(z, y)a = f

Referentially transparent programs are more amenable toformal methods and easier to reason about because themeaning of an expression depends only on the meaning of itssubexpressions and not on the order of evaluation orside-effects of other expressions.

We can stretch the concept of referential transparency toinclude input and output if we consider the whole program tobe a function from its input to its output. The program as awhole is referentially transparent because it will alwaysproduce the same output when given the same input. This isstretching the concept because the program's input may includewhat the user types, the content of certain files or even thetime of day. If we do not consider global state like thecontents of files as input, then writing to a file and readingwhat was written behaves just like assignment to a globalvariable. However, if we must consider the state of theuniverse as an input rather than global state then anydeterministic system would be referentially transparent!

See also extensional equality, observational equivalence.