0

What is the difference between impure and pure functions in Python?

can a pure function work like impure function?

29th Dec 2017, 1:53 PM
Ankit Pal
Ankit Pal - avatar
2 Answers
0
Pure functions are deterministic and have no side effects. So for deterministic, when you input the same arguments, you must always get the same output. Like a function in math (the vertical line test). So for example x => 2 * x is pure, and x => x + rand() is not pure because it has randomness - when you input 1 you sometimes get 1.2 and sometimes 1.3. Usually what we’re most concerned about is when the function changes or depends on an internal state of an object. So get_age() is obviously not pure since the age can change. In OOP you can’t have pure functions. Another criteria is side effects. print(x) has the side effect of displaying on the screen. write(s) modifies a file. set_age(x) changes the internal state of an object. I’m not sure what you mean to have a pure function work like an impure function. No pure function can replace print(). Nor get_age() or rand().
1st Jan 2018, 1:40 AM
Alexander
Alexander - avatar
0
You might also have heard of a related concept, referential transparency. This happens when you only use pure functions. The definition is that in function calls, you can get the same result by replacing a call with its return value. Like in add(mul(3, 1), 4) we can replace mul(3, 1) with 3 and everything is still the same. But if we replace the print in bool(print(1)) with its return value None, we still get False but the screen no longer prints 1, so referential transparency is lost. Another example is add(int(set_age(3)), get_age()), if the original age was 2, then this returns 0 + 3 = 3. But if we replace set_age(3) with None, then 0 + 2 = 2.
1st Jan 2018, 1:48 AM
Alexander
Alexander - avatar