Referential transparency is a property of a program expression which states that it always produces the same output for a given input value. Just like mathematical functions, referentially transparent expressions in a program map each value (input) in the domain to exactly one element (return value) of the codomain. Which of the following Python functions are referentially transparent? Keep in mind that referential transparency does not imply absence of side-effects.
def fun_1(x, y):
return x + y
def fun_2(name):
file = open(name, 'r')
data = file.read() # Read file contents to variable 'data'
file.close()
return data
def fun_3(x):
launchRocket() # Function that sends a rocket to the moon
return x
A function that doesn’t exhibit side-effects is called pure. As already mentioned, referential transparency does not imply purity. But is the opposite true? That is to say; does purity imply referential transparency?
The first and the last functions are referentially transparent.
A function is a binary relation that associates at most one range element to any domain element.
The fact that fun_3
sends rockets to the moon doesn't change its behavior with regard to this property. It does, however, mean that fun_3
is not pure. Let's think of it as an effectful identity function. fun_1
, on the other hand, is both referentially transparent and pure.
The answer to the bonus question is yes; purity does imply referentially transparent. In other words, purity is a stronger guarantee than referential transparency. Thinking about it, a function that is pure behaves truly like a black box and has no way to interact with the outside world. All it can do is to act on its input. Therefore, the return value is not influenced by anything else than the arguments it is given as input.