Functional programming in Python
Paweł Pamuła
First do this and next do that
Think in terms of objects
Evaluate an expression and use the resulting value for something
Referential transparency (pure functions)
Python does not promote functional approach!
I have never considered Python to be heavily influenced by functional languages, no matter what people say or think.
However, earlier on, it was clear that users wanted to do much more with lists and functions.
>>> def forall(fun, val):
... output = []
... for v in val:
... output.append(fun(v))
... return output
...
>>> def double(x):
... return 2*x
...
>>> forall(double, [1, 2, 3, 4])
[2, 4, 6, 8]
>>> reverse = lambda s: s[::-1]
>>> reverse('abc')
'cba'
>>> forall(lambda s: s[::-1], ['abc', 'kajak'])
['cba', 'kajak']
>>> def log(level, message):
... print "[%s] %s" % (level, message)
...
>>> log("error", "It's gonna explode!")
[error] It's gonna explode!
from functools import partial
def log(level, message):
print "[%s] %s" % (level, message)
levels = ['info', 'warning', 'error', 'debug']
funs = dict((item, partial(log, item)) for item in levels)
funs['info']("That's a very important information")
print funs
[info] That's a very important information
>>> 1 or 1/0
1
>>> import time
>>> print ['some text', time.sleep(3)][0]
import os
files = ['file1.pdf', 'file2.txt']
filename = lambda f: os.path.splitext(f)[0]
modules = map(filename, files)
['file1', 'file2']
Sum of integers
def isum(a, b):
return sum(range(a, b+1))
Sum of squares
def ssum(a, b):
return sum(map(lambda x: x**2, range(a, b+1)))
Sum of roots
import mathdef rsum(a, b):
return sum(map(lambda x: math.sqrt(x), range(a, b+1)))
import math
def general_sum(f):
def inner(a, b):
return sum(map(f, range(a, b+1)))
#returns function!
return inner
log_sum = general_sum(math.log)print log_sum(1, 10), ' should be more or less equal to ', math.log(reduce(lambda x, y: x*y, range(1, 11)))
15.1044125731 should be more or less equal to 15.1044125731
>>> f = lambda a,b: "f(%s,%s)" % (a,b)
>>> reduce(f, '1234')
f(f(f(1,2),3),4)
>>> mul = lambda x, y: 10*x + y
>>> reduce(mul, [1, 4, 1, 0])
1410
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
def lcmm(*args):
return reduce(lcm, args)
print lcmm(10, 17, 4)
How are parameters passed to function in Python?
def f(x):
x[0] = 10
def g(x):
x = [4, 5, 6, 7]
def h(some_string):
some_string = 'New string'
x = [0, 1, 2, 3]
f(x)
h(x)
s = 'Some string'
h(s)
Thank you for your attention!
Paweł Pamuła
pawel.pamula@gmail.com
@github: PawelPamula