What is Referential Transparency?

Referential Transparency is an easy method to verify the purity of a function. If the Function is referentially transparent, it is pure.
Let's start with the definition.

A function is said to be referentially transparent if we can replace it with its corresponding value without changing the program's behavior.

Let's try to understand it with the help of some examples. SQRT(x) is a function. The below diagram shows a small table of input and output for different values.

What is a referentially transparent function
Fig.2-Input and output of referentially transparent function.

Now assume you are using SQRT in your program.
Can you replace SQRT(4) with 2?
Can you replace SQRT(16) with 4?
You can easily replace all references to SQRT with its corresponding output value as long as the input value is also matching. You can do this replacement without changing the behavior of your program. Hence, SQRT is referentially transparent. So, the SQRT is a pure function because we can change its references with the output value as long as input value is same. Let's take another example.

Scala Function - Test referential transparency

The first line of the below code defines a free variable. The next four lines define a function named testRT. The last two lines make a call to the testRT with a constant input.

The output of the first function call is 15 and the second function call is 20. Can I replace all references of testRT(5) with 15 or 20? Your answer would be an obvious No. So, testRT does not qualify for referential transparency. It is not a pure function. You can double check the testRT function using the purity principles. The the purity rules are listed below.

  1. The Input solely determines the output.
  2. The Function does not change its input.
  3. The Function does not have any side effects.

I have following observations.

  1. The function testRT violates the first principle. Its output depends upon an external variable g.
  2. The testRT qualifies for the second rule because it does not modify the input parameter.
  3. It is not eligible to qualify the third law. The testRT has a side effect because it changes the state of an external variable.

That is all about referential transparency. You might be wondering about the benefits of a pure function and referentially transparent functions.
Continue reading for the answer.

Read More

Pure Functions | Referential Transparency | Benefits of pure functions | First class functions | Higher order function | Anonymous functions | Immutability | Tail Recursion | Expressions in Scala | Lazy Evaluations | Pattern Matching | Closures

By Prashant Pandey -

You will also like: