Is this a referentially transparent function?

Chase Miller

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:

  1. It can be replaced by its value and the behavior of the program remains the same
  2. Given some input it will always produce the same output
  3. It only depends on its input
  4. It is stateless

Given each of the definitions above I would think the answer is:

  1. Maybe - I think it depends on how appState.runningTotal is used elsewhere in the program, but I'm not sure.
  2. Yes
  3. I'm not sure - It only depends on its input to produce the output, but it also uses appState in the body of the function
  4. No

Back 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.

TheInnerLight

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]

編集
0

コメントを追加

0

関連記事