r/functionalprogramming • • 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.

19 Upvotes

25 comments sorted by

View all comments

Show parent comment

4

u/[deleted] Jan 24 '23 edited Jan 24 '23

Thanks for the refresher. When I say pure I'm usually thinking referentially transparent, which is, I think, the more important aspect of the two requirements.

I have a fair share of functions which log to the console. These aren't scary. However, some side effects mutate external things. These can cause the imperative parts of the program which use those things to misbehave.

So clearly there's safe and unsafe side effects. Safe meaning having no ability to impact behavior elsewhere. And I have little qualms calling a function with safe side effects pure although technically, since the logging eats memory and affects performance, it's not.

2

u/hoimass Jan 30 '23

Logging is code behavior.