Edexcel International Advanced Level Computer Science, point 20.1.2
The ideas of functional programming are in 13.1.2. In Unit 4 you must write functional code in Python. Check the Programming Language Subset (PLS) for the features allowed.
a. Pure functions and e. avoiding side effects
A pure function returns the same output for the same input, and changes nothing outside itself.
def add_vat(price, rate=0.2): # pure
return price * (1 + rate)
basket = [10, 20]
def add_item(items, x): # pure: returns a NEW list
return items + [x]
new_basket = add_item(basket, 5)
print(basket, new_basket) # [10, 20] [10, 20, 5]
Impure (a side effect): items.append(x) changes the list that was passed in.
b. First-class functions
Functions are values: store them, pass them, return them.
def shout(text):
return text.upper() + "!"
actions = {"shout": shout, "len": len} # functions in a dictionary
print(actions["shout"]("hi"), actions["len"]("hello")) # HI! 5
c. Higher-order functions
A function that takes a function, or returns one.
def apply_twice(f, x):
return f(f(x))
print(apply_twice(lambda n: n * 2, 5)) # 20
def make_adder(n): # returns a function
return lambda x: x + n
add5 = make_adder(5)
print(add5(10)) # 15
g. Lambda functions
A short anonymous function in one expression: lambda arguments: expression.
square = lambda x: x * x
print(square(6)) # 36
words = ["pear", "fig", "banana"]
print(sorted(words, key=lambda w: len(w))) # ['fig', 'pear', 'banana']
Use for short, one-off functions, and def for anything longer.
i. Map, j. filter and k. reduce
from functools import reduce
nums = [1, 2, 3, 4, 5, 6]
doubled = list(map(lambda n: n * 2, nums)) # apply to each
# [2, 4, 6, 8, 10, 12]
print(doubled)
evens = list(filter(lambda n: n % 2 == 0, nums)) # keep some
print(evens) # [2, 4, 6]
# combine into one
total = reduce(lambda acc, n: acc + n, nums)
print(total) # 21
# 1 is the start value
product = reduce(lambda a, b: a * b, nums, 1)
print(product) # 720
| Function | Takes | Gives |
|---|---|---|
map(f, items) |
f and a list |
f applied to each item |
filter(f, items) |
A test and a list | Items where the test is true |
reduce(f, items, start) |
A two-argument function and a list | A single combined value |
map and filter return lazy iterators (below), so wrap them in list().
Chaining them (a data pipeline):
result = reduce(lambda a, b: a + b,
map(lambda n: n * n,
filter(lambda n: n % 2 == 1, range(1, 8))))
print(result) # squares of the odd numbers 1,3,5,7: 1+9+25+49 = 84
l. List comprehension and m. dictionary comprehension
Often clearer than map and filter.
# [1, 4, 9, 16, 25]
squares = [n * n for n in range(1, 6)]
odd_squares = [n * n for n in range(1, 8) if n % 2] # [1, 9, 25, 49]
names = ["amy", "raj", "sam"]
# {'amy': 3, ...}
lengths = {name: len(name) for name in names}
# {1: 'a', 2: 'b'}
inverse = {v: k for k, v in {"a": 1, "b": 2}.items()}
passes = {n: m for n, m in {"Amy": 72, "Li": 40}.items() if m >= 50}
print(passes) # {'Amy': 72}
Form: [expression for item in iterable if condition].
n. Zip
Pairs up items from several sequences.
names = ["Amy", "Raj", "Sam"]
marks = [72, 91, 58]
for name, mark in zip(names, marks):
print(name, mark)
# {'Amy': 72, 'Raj': 91, 'Sam': 58}
print(dict(zip(names, marks)))
# unzip: [(1, 2), ('a', 'b')]
print(list(zip(*[(1, "a"), (2, "b")])))
zip stops at the shortest sequence.
d. Immutable variables
Don't change data: build new data. Tuples and strings are immutable.
point = (3, 4)
moved = (point[0] + 1, point[1]) # a NEW tuple
print(point, moved) # (3, 4) (4, 4)
from types import MappingProxyType
# a read-only dictionary view
frozen = MappingProxyType({"a": 1})
frozenset({1, 2}) # an immutable set
Use tuple, frozenset and str, and return new lists instead of changing them.
f. Lazy evaluation
Values are produced only when needed, not all at once, which saves memory and time.
def count_up(start):
n = start
while True: # an infinite sequence
yield n # a generator
n += 1
gen = count_up(1)
print(next(gen), next(gen), next(gen)) # 1 2 3
squares = (n * n for n in range(1_000_000)) # a generator expression
# 0 1 (nothing else calculated yet)
print(next(squares), next(squares))
print(sum(n * n for n in range(1, 4))) # 14
yieldmakes a generator, producing values one at a time.map,filter,zipandrangeare also lazy.- Benefit: a million items needn't be in memory at once, and infinite sequences are possible.
h. Recursion
Functional code uses recursion in place of loops that change variables (5.1.3, 10.4.1):
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
def reverse(items):
return [] if not items else reverse(items[1:]) + [items[0]]
print(total([3, 5, 2]), reverse([1, 2, 3])) # 10 [3, 2, 1]
Comparing styles for the same task
"Sum of the squares of the even numbers up to 10":
# procedural
total = 0
for n in range(1, 11):
if n % 2 == 0:
total += n * n
print(total) # 220
# functional
print(sum(n * n for n in range(1, 11) if n % 2 == 0)) # 220
Worked example
Task: from students = [("Amy", 72), ("Raj", 91), ("Sam", 58), ("Li", 40)], in a functional style, (a) list the names of those who passed (50 or more) in capital letters, (b) find the total of their marks, and (c) build a dictionary of name to grade.
from functools import reduce
students = [("Amy", 72), ("Raj", 91), ("Sam", 58), ("Li", 40)]
PASS = 50
passed = list(filter(lambda s: s[1] >= PASS, students))
names = [name.upper() for name, _ in passed] # (a)
total = reduce(lambda acc, s: acc + s[1], passed, 0) # (b)
grades = {n: ("A" if m >= 70 else "B") for n, m in passed} # (c)
print(names) # ['AMY', 'RAJ', 'SAM']
print(total) # 221
print(grades) # {'Amy': 'A', 'Raj': 'A', 'Sam': 'B'}
print(students[3]) # ('Li', 40): the original data is untouched
Features used: filter, lambda, a list comprehension, reduce, a dictionary comprehension, no changes to students (immutability, no side effects), and each step produces new data.
Exam tip: know what each of map, filter and reduce returns. Wrap map and filter in list(). A comprehension is often the neatest answer. Say why the code is functional (no changing variables or side effects).
Check yourself
What does filter(lambda n: n > 2, [1, 2, 3, 4]) return (as a list)?
[3, 4].
What is the result of reduce(lambda a, b: a + b, [1, 2, 3, 4])?
What is lazy evaluation?
Producing values only when they are needed, instead of calculating them all at once, for example with a generator.
What does zip(["a", "b"], [1, 2]) produce?
Pairs of items: ("a", 1) and ("b", 2).
Why is add_item(items, x) returning items + [x] more functional than items.append(x)?
It creates a new list and leaves the original unchanged, so there is no side effect.