Referential transparency in functional programming

风流意气都作罢 提交于 2020-01-14 17:50:13

问题


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 replace a pure function with its value". Does it mean that the use of RT makes it easy for JIT compiler to replace function with its return value as long as function gets hot? Is that true?


回答1:


Here's an example:

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

const even = x => x % 2 === 0;

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

const isTenEven = () => 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:

const isTenEven = () => 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:

const even = x => (new Date()).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 true could 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.




回答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.



来源:https://stackoverflow.com/questions/59624286/referential-transparency-in-functional-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!