r/functionalprogramming • u/Echoes1996 • Dec 02 '24
Question Is this function pure?
Consider a function f(x) that invokes an impure function g(), which is not referentially transparent, though it has no side effects. Then, function f decides to do nothing with the result returned by function g and goes on to return a value based on its argument x. My question is: is f pure?
Example:
global y
def g():
# Not referentially transparent, though it does not
# alter the "outside world".
return y
def f(x: int):
_ = g() # Invoke non-referentially transparent function g.
return x + 1 # Return result solely based on input x.The output of f is completely dependent on its input, and it has no side effects, as g has no side effects as either. So, is f pure or not?
7
Upvotes
View all comments
Show parent comment
3
u/Pristine-Staff-5250 Dec 04 '24
I believe there is a nuance to this, `1,2,3` or other "constants" are referenced inside a function.
f(x) = x+2
if `+` is variable that holds a binary operation that could mutate, f would still be non-referentially transparent because the references are not clear from some POV.
however, if a language can guarantee the constant-ness of symbols, then the use of those symbols does not constitute a side effect or non-referential transparency, because the references are indeed clear.
So if the global n, can be defined in the language such that it couldn't possibly change for the life of the program, then the reference is clear and using it isn't impure. it becomes just an alias, like if
global n = 2(and can never be changed by any magic of the language)
then f(x) = g+x is the same as f(x) = 2+x; because x and + refers to the same thing on both expressions. g and 2 would refer to the same thing too.