Is the following add()
function referentially transparent?
const appState = {
runningTotal: 0
}
function add(x, y) {
const total = x + y;
appState.runningTotal += total;
return total;
}
I'm unsure of the answer due to a handful of definitions I've found for referential transparency. Here are some in the order of my confidence of their correctness.
A function is referentially transparent if:
Given each of the definitions above I would think the answer is:
appState
in the body of the functionBack to the specific question: is add()
referentially transparent?
Thanks in advance!
P.S. - please let me know if I'm conflating multiple concepts, namely the concept of a pure function
.
No, it isn't a referentially transparent function.
Referential transparency refers specifically to the first criteria you have listed, namely that you can freely substitute the values on the left and right hand side of an expression without changing the behaviour of the program.
add(2,3)
returns the value 5
but you cannot replace instances of add(2,3)
with 5
in your program because add(2, 3)
also has the side effect of incrementing runningTotal
by 5
. Substituting add(2, 3)
for 5
would result in runningTotal
not being incremented, changing the behaviour of your program.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加