Another Example
As an example, let's use two functions, one which is referentially opaque, and the other which is referentially transparent:
globalValue = 0; integer function rq(integer x) begin globalValue = globalValue + 1; return x + globalValue; end integer function rt(integer x) begin return x + 1; endThe function rt
is referentially transparent, which means that rt(x) = rt(y)
if x = y
. For instance, rt(6) = 6 + 1 = 7, rt(4) = 4 + 1 = 5
, and so on. However, we can't say any such thing for rq
because it uses a global variable which it modifies.
The referential opacity of rq
makes reasoning about programs more difficult. For example, say we wish to reason about the following statement:
One may be tempted to simplify this statement to:
integer p = rq(x) + rq(y) * (0); integer p = rq(x) + 0; integer p = rq(x);However, this will not work for rq
because each occurrence of rq(x)
evaluates to a different value. Remember, that the return value of rq
is based on a global value which isn't passed in and which gets modified on each call to rq
. This means that mathematical identities such as no longer hold.
Such mathematical identities will hold for referentially transparent functions such as rt
.
However, a more sophisticated analysis can be used to simplify the statement to:
integer a = globalValue; integer p = x + a + 1 + (y + a + 2) * (x + a + 3 - (x + a + 4)); globalValue = globalValue + 4; integer a = globalValue; integer p = x + a + 1 + (y + a + 2) * (x + a + 3 - x - a - 4)); globalValue = globalValue + 4; integer a = globalValue; integer p = x + a + 1 + (y + a + 2) * -1; globalValue = globalValue + 4; integer a = globalValue; integer p = x + a + 1 - y - a - 2; globalValue = globalValue + 4; integer p = x - y - 1; globalValue = globalValue + 4;This takes more steps and requires a degree of insight into the code infeasible for compiler optimization.
Therefore, referential transparency allows us to reason about our code which will lead to more robust programs, the possibility of finding bugs that we couldn't hope to find by testing, and the possibility of seeing opportunities for optimization.
Read more about this topic: Referential Transparency (computer Science)
Famous quotes containing the word example:
“Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.”
—Marcel Proust (18711922)