Is this a referentially transparent function?
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 function Back to the specific question: is add()
referentially transparent?
Thanks in advance!
PS - 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.
I'd go with
Maybe - It depends on how appState.runningTotal
is used
as when it is not used, then it can be ignored. Obviously it is global state, but is it just for debugging or is it part of your actual application state? If the latter, then the function is not pure of course - it does change the state and replacing a call with the result value (or doing unnecessary calls whose result is dropped) would change the behaviour of your program.
But if you do consider appState.runningTotal
to not be part of the semantics of your program, and non of its functionality depends on it, you might as well ignore this side effect. We do this all the time, every real world computation affects the state of the computer it runs on, and we choose to ignore that when we consider the purity of our functions.
A pure function is referentially transparent. I call it "copypastability", aka you can copy paste each part of referentially transparent code around, and it'll still work as originally intended.
All of the four criteria have to be fulfilled, although you can shrink them to the first statement. The others can all be inferred from that one.
If a function can be reasonably replaced, that means you can replace it with a map/dictionary which has input as keys and outputs as values. So it'll always return the same thing on the same input. The same analogy works just fine with the "only depends on input" and "stateless".
链接地址: http://www.djcxy.com/p/80586.html上一篇: 带递归调用的F#System.OutOfMemoryException
下一篇: 这是一个引用透明的功能吗?