Examples and Counterexamples
If all functions involved in the expression are pure functions, then the expression is referentially transparent. Also, some impure functions can be included in the expression if their values are discarded and their side effects are insignificant.
Consider a function that returns the input from some source. In pseudocode, a call to this function might be GetInput(Source)
where Source
might identify a particular disc file, the keyboard, etc. Even with identical values of Source
, the successive return values will be different. Therefore, function GetInput
is neither deterministic nor referentially transparent.
A more subtle example is that of a function that uses a global variable (or a dynamically scoped variable, or a lexical closure) to help it compute its results. Since this variable is not passed as a parameter but can be altered, the results of subsequent calls to the function can differ even if the parameters are identical. In pure functional programming, destructive assignment is not allowed; thus, a function that uses global (or dynamically scoped) variables may or may not be referentially transparent, depending on whether the global variables are immutable.
Arithmetic operations are referentially transparent: 5*5
can be replaced by 25
, for instance. In fact, all functions in the mathematical sense are referentially transparent: sin(x)
is transparent, since it will always give the same result for each particular x
.
Assignments are not transparent. For instance, the C expression x = x + 1
changes the value assigned to the variable x
. Assuming x
initially has value 10
, two consecutive evaluations of the expression yield, respectively, 11
and 12
. Clearly, replacing x = x + 1
with either 11
or 12
gives a program with different meaning, and so the expression is not referentially transparent. However, calling a function such as int plusone(int x) {return x+1;}
is transparent, as it will not implicitly change the input x and thus has no such side effects.
today
is not transparent, as if you evaluate it and replace it by its value (say, "Jan 1, 2001"), you don't get the same result as you will if you run it tomorrow. This is because it depends on a state (the time).
Read more about this topic: Referential Transparency (computer Science)
Famous quotes containing the word examples:
“It is hardly to be believed how spiritual reflections when mixed with a little physics can hold peoples attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.”
—G.C. (Georg Christoph)