r/functionalprogramming • u/cizizen • Jan 24 '23
Question Example of a function that has referential transparency but is not pure?
I've read that Functions that have referential transparency can be replaced by their output. And also that Pure functions return the same result for the same input (which makes them referentially transparent) and don't have any effect on the rest of the program.
So what is an example of a function that has referential transparency but is not pure? Does a function which only depends on its inputs but modifies a global variable still have referential transparency? It wouldn't be pure from my understanding because it modifies other parts of the program.
View all comments
Show parent comment
2
u/SomewhatSpecial Jan 24 '23
Not really, no. You can have an upsert that returns 'itemAdded' or 'itemAlreadyExists'. It does not always return the same result with the same input (first call returns 'itemAdded', second - 'itemAlreadyExists'). Yet it would still be an idempotent operation, because calling it once would have the same effect as calling it two or more times.