This tutorial is adapted from the Web Age course Introduction to Python Programming.
1.1 What is Functional Programming?
Functional programming reduces problems to a set of function calls.
The functions used, referred to as Pure functions, follow these rules:
- Only produce a result
- Do not modify the parameters that were passed in
- Do not produce any side effects
- Always produce the same result when called with the same parameters
Another condition of functional programming is that all data be immutable.
1.2 Benefits of Functional Programming
Solutions implemented using functional programming have several advantages:
- Pure functions are easier to test
- Programs follow a predictable flow
- Debugging is easier
- Functional building blocks allow for high-level programming
- Parallel execution is easier to implement
1.3 Functions as Data
In Python, functions can be assigned to and passed as variables. This allows for:
- Passing functions as parameters to other functions
- Returning functions as the result of a function
Python functions such as map(), filter() and sort() take functions as parameters. Functions that accept other functions as parameters or return functions as their result are referred to as higher-order functions.
1.4 Using Map Function
map( transform_function, iterable )
def toUpper(item): return item.upper()
states = map_result = map( toUpper, states) list_result = list(map_result) print(list_result) # prints:
1.5 Using Filter Function
filter( check_function, iterable )
def lengthCheck(item, maxlen=7): return len(item) <= maxlen
states = filter_result = filter( lengthCheck, states) list_result = list(filter_result) print(list_result) # prints:
1.6 Lambda expressions
Lambda expressions in Python:
- Are a special syntax for creating anonymous functions
- Are limited to a single line of code
- Return the result of their single code statement by default
- Are typically defined in-line where they will be used
- Some lambda expressions
lambda x : x * x # multiply parameter by itself lambda y : y * 2 # multiply parameter by 2 lambda z : z # get value from dict with # key = 'name'
list(map(lambda x:x*x, )) # outputs
Lambda expressions can be tested as shown here by supplying a parameter in parenthesis:
(lambda x : x * x)(5) # returns 25
1.7 List.sort() Using Lambda Expression
List.sort() takes two parameters:
list.sort( key, reverse )
-
- key = function that should return a value to be sorted on
- reverse = True/False to indicate source order
In the code below a lambda expression is used to provide the function for the ‘key’ parameter:
list1 = list1.sort(key=lambda item: item, reverse=False) print(list1) # outputs:
Notes
Python’s sorted() function is similar to list.sort() except that you need to pass in the list as the first parameter and that sorted() returns the sorted list which must then be assigned to a variable
list_sorted = sorted(list1, key, reverse)
1.8 Difference Between Simple Loops and map/filter Type Functions
# loop over and mutate iterable list1 = for i in range(len(list1)): list1 = list1.upper()
The problems with this are:
- The original list is no longer available as it has been mutated
- This code would not work with immutable sequences like tuples
- The equivalent code using map fixes both of these issues
# map creates new list based on original list1 = list2 = list(map(lambda x: x.upper(), list1))
Here is an example of the same map function being used with a tuple:
tup1 = ( 'c', 'f', 'a', 'e', 'b' ) tup2 = tuple(map(lambda x:x.upper(), tup1))
1.9 Additional Functions
Notes:
randint() is part of the random module which must be imported:
import random as r
r.randint(0,10)
Counter is part of the collections module and must be imported
import collections as c
c.Counter(‘asdffg’)
1.10 General Rules for Creating Functions
Since creating functions is a big part of functional programming we will re-iterate here some of the rules we learned earlier
- Name functions appropriately
- Limit the function to a single responsibility
- Include a docstring
- Always return a value
- Limit functions to 50 lines or less
- Make the function ‘idempotent’ and ‘pure’ if possible
1.11 Summary
In this tutorial, we covered:
- What is Functional Programming
- Functional Programming Benefits
- Using Map Function
- Using Filter Function
- Lambda Expressions
- List.sort() using Lambda
- Loops vs. map/filter
- Additional Functions
- General Rules for Creating Functions