domenica 8 novembre 2015

A crash course in Python - Lesson 7: Functional programming

In this post, I don't want to discuss functional programming at all, but I would like to list some of the functional tools I encountered while using Python.

Curry functions

From Wikipedia:
"Currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument"

Suppose we have the following function:

def exp(base, power):
    return base ** power

If we want to create the function two_to_the with a single input (which is the power) and fixed base (which is 2), we may do it by simply doing the following:

def two_to_the(power):
    return exp(2, power)

The same thing can be done as follows:


from functools import partial

two_to_the = partial(exp,2)  # is a function of one variable
print two_to_the(3)  # 8

square_of = partial(exp, power=2)
print square_of(3)  # 9

Map, Filter and Reduce

We occasionally use map, reduce and filter, which provide functional alternatives to list comprehension.

Map

The map function can be used with multiple-argument function if you provide multiple lists:

def multiply(x, y):
    return x * y

products = map(multiply, [1,2], [4,5])
# [1*4, 2*5] = [4, 10]

Filter

The filter function does the work of a list-comprehension if:

def isEven(x):
    return x % 2 == 0

xs = [1,2,3,4]
x_evens = [x for x in xs if isEven(x)]  # [2,4]
x_evens = filter(isEven, xs)  # same as above
list_evener = partial(filter, isEven)  # function that filters a list
x_evens = list_evener(xs)  # again [2,4]

Reduce

The reduce function combines the first two elements of a list, then that result with the third, that result with the fourth, and so on.

xProduct = reduce(multiply, xs)  # = 1*2*3*4 = 24
listProduct = partial(reduce, multiply)  # function that reduces a list
xProduct = listProduct(xs)  # again = 24

Nessun commento:

Posta un commento