Skip to content Skip to sidebar Skip to footer

Referential Transparency In Functional Programming

I am new to JS and was learning functional programming and came across the term 'referential transparency'. Also, I found this statement 'Referential transparency says it's safe to

Solution 1:

Here's an example:

This is a pure function: it will always return the same output for the same input

consteven = x => x % 2 === 0;

And let's create isTenEven() which will check wether 10 is an even number or not:

constisTenEven = () => even(10);

Since we're guaranteed that even(10) === true will always be true then we can indeed replace a function call with a value:

constisTenEven = () => true;

And your program would still work.

However you wouldn't be able to do so if even wasn't pure! Here's a silly example: once per month 10 won't be an even number anymore:

consteven = x => (newDate()).getDate() === 15 ? false : x % 2 === 0;

Perhaps your program is excepting isTenEven() to return either true or false, so forcing it to always assume that it will return truecould lead to unexpected consequences.

Of course in this particular case I'm not sure what those consequences would be but you never know... which is exactly the point.

Solution 2:

Yes, that is exactly an advantage of RT. The compiler can not only inline a function but replace its invocations with the corresponding return value, that is it can eliminate common sub-expressions and rewrite code according to specific rules like you can rewrite formulas in math. This way of reasoning about a program is called equational reasoning and is also very helpful for the programmer.

But RT allows other optimization techniques as well, like lazy evaluation. If you want to automatically delay the evaluation of an arbitrary expression up to the point where its result is actually needed, you need the guarantee that this expression yields the same result no matter when you actually evaluate it. RT gives this guarantee.

Post a Comment for "Referential Transparency In Functional Programming"