Functional Programming
A pure function
does not modify any of the objects passed.
class Hour:
def increment_pure(t, d):
sum = Hour()
sum.hour = t.hour + d.hour
return sum
def increment_impure(t, d):
sum = Hour()
sum.hour = t.hour + int(d.hour)
return sum
start = Hour()
start.hour = 9.0
duration = Hour()
duration.hour = 1.5
end = increment_pure(start, duration)
assert end.hour == 10.5
assert end.hour != 10
end = increment_impure(start, duration)
assert end.hour != 10.5
assert end.hour == 10
end = increment_pure(start, duration)
def print_time(obj):
print('%.2d' % obj.hour)
print_time(end)
Modifiers
Functions that
modifiy the objects are called modifiers.
class Time: pass
def increment(t, seconds):
t.seconds = t.seconds + seconds
def increment_pure(seconds):
time = Time()
minutes, time.seconds = divmod(seconds, 60)
hour, time.minutes = divmod(minutes, 60)
time.hour = hour
return time
def print_time(t):
print('%.2d:%.2d:%.2d' % (t.hour, t.minutes, t.seconds))
t = Time()
t.hour = 9
t.minutes = 45
t.seconds = 0
increment(t, 20)
print_time(t)
t = increment_pure(160)
print_time(t)