Functional Programming in Python Abhishek Dasgupta Indian Institute of Science Education and Research, Kolkata
What is Functional Programming? ● Most programs use procedural instructions ● a = a + 1, this simple statement is disallowed in pure functional programming (assignment can only be done to constants) ● Code modularised into functions ● FP: Everything is a function. ● Church's Thesis: Any intuitively computable function is recursive (can be expressed in terms of composition of functions)
Building blocks of FP in Python ● Are the following functions ● map ● reduce ● filter ● Along with lambda. (defines anonymous function, like >>> f = lambda x: x**2 >>> f(2) 4
operator module ● Contains functions corresponding to the logical operators and binary operators ● add ● mul ●... and so on... ● Useful in map() calls, no need to define trivial functions.
map ● map(function, list) Applies function to each element of a list and returns a new list ● Map is an alternative way of specify the familiar for loops: ● a=[] for i in range(10): a.append(i**2) map(lambda x: x**2, range(10)) alternative [x**2 for x in range(10)] (list-comprehension)
reduce ● Similar to foldr/foldl in traditional functional programming languages (like Haskell) ● reduce(function, list) Here function should be a binary function, then reduce applies function to first two elements of list, then takes the result and applies it to third element and so on: [1,2,3,4,5] would become ((((1.2).3).4).5) where. signifies the binary operation.
reduce ● You can sum a series in one line now! ● Earlier: s = 0 for i in range(1,10): s += 1.0/i ● Now: reduce(operator.add, map(lambda x: 1.0/x, range(1,10)))
filter ● filter(function, list) Applies the function to each item of a list; if the evaluation is True, then keeps the element in a new list. ● Example: filter even numbers >>> filter(lambda x: x % 2 == 0, range(10)) [0, 2, 4, 6, 8] >>> [x for x in range(10) if x % 2 == 0] [0, 2, 4, 6, 8]
Conclusion ● Functional programming not very hairy or complicated ● In fact, makes code simpler to understand ● Big monolithic functions replaced by atomic functions which do really one thing ● Makes us think about the code structure
An example: QuickSort def QuickSort(List): if List == []: return [] else: x = List[0] xs = List[1:] return QuickSort(filter(lambda l: l = x, xs)) ● Much simpler to code than the traditional way using a partition function.
Further Information ● Why Functional Programming matters ● Charming Python: Functional programming in Python ● Functional Programming HOWTO ● Functional Programming with Python (LG#109)