Python-a10-Functional Programming

This article shows the examples of Functional Programming in python

function composition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 1
def inner():
print('this is the inner function')

def outer(func):
func()

outer(inner) # this is the inner function

# 2
def outer():
def inner():
print('this is the inner function')
return inner

outer()() # this is the inner function

# sorted
animals = ["ferret", "vole", "dog", "gecko"]
print(sorted(animals, key=len)) # ['dog', 'vole', 'gecko', 'ferret']

lambda

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# callable Return whether the object is callable
print(callable(lambda s: s[::-1])) # True

# 2
reverse = lambda s: s[::-1]
print(reverse('This is a test')) # tset a si sihT<

# 3
print((lambda s: s[::-1])('This is a test')) # tset a si sihT

# 4
print((lambda x, y, z: x + y + z / 3)(1, 2, 3)) # 4.0

# 5
def func(x):
return x, x ** 2, x ** 3

print(func(3)) #(3, 9, 27)

# 6
print((lambda x: (x, x ** 2, x ** 3))(3)) #(3, 9, 27)

map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# map returns an iterator
def reverse(s):
return s[::-1]

animals = ["cat", "dog", "hedgehog", "gecko"]
iterator = map(reverse, animals)
print(iterator) # <map object at 0x000001ADCF5CFCD0>
print(list(iterator) # ['tac', 'god', 'gohegdeh', 'okceg']

# 2
print(list(map(lambda s: s[::-1], animals))) # ['tac', 'god', 'gohegdeh', 'okceg']

# map with multiple iterables
def func(a, b, c):
return a + b + c

print(list(map(func, [1, 2, 3], [10, 20, 30], [100, 200, 300]))) # [111, 222, 333]

filter

1
2
3
4
5
6
# 1
def greater_than_100(x):
return x > 100

print(list(filter(greater_than_100, [1, 3, 5, 100, 200, 300]))) # [200, 300]

reduce

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 1
from functools import reduce

def add(x, y):
return x + y

print(reduce(add, [1, 3, 5])) # 9

# complex
def custom_map(function, iterable):
from functools import reduce

return reduce(
lambda items, value: items + [function(value)],
iterable,
[]
)

print(list(custom_map(str, [2, 3, 3, 4, 5]))) # ['2', '3', '3', '4', '5']