I learnt that mutability of an object is defined with respect to its state but not with its identity.
Below program changes state of a locally scoped object referred by name count
within function hailstone()
.
def hailstone(n):
count = 1
"""Print the terms of the 'hailstone sequence' from n to 1."""
assert n > 0
print(n)
if n > 1:
if n % 2 == 0:
count += hailstone(n / 2)
else:
count += hailstone((n * 3) + 1)
return count
if (__name__ == '__main__'):
result = hailstone(10)
print(result)
After reading the below paragraph of this article, I see that the above code looks fine as regards changing the state of the locally scoped object that name count
refers to (i.e. count += hailstone(n / 2)
):
Ignore all that. Functional code is characterised by one thing: the absence of side effects. It doesn't rely on data outside the current function, and it doesn't change data that exists outside the current function. Every other “functional” thing can be derived from this property. Use it as a guide rope as you learn.
So, how do I understand the meaning of this statement from this answer:
In functional programming, it is not proper to ever change the value of a variable.
Does functional programming allow changing the state of the locally scoped object referred by name count
in my above program?