Edexcel International Advanced Level Computer Science, point 13.1.2
Definition
Functional programming is a paradigm in which a program is built by applying and combining functions, as in mathematics, avoiding changing data and avoiding side effects. Computation is the evaluation of functions, not a sequence of commands that change variables. Languages include Haskell, Lisp, Scala and F#. Python supports a functional style.
Function and why needed
It makes programs easier to reason about, test and run in parallel, because functions depend only on their inputs and don't change anything else. In Unit 3 you must understand it. In Unit 4 you use it (20.1.2).
a. Concepts
Pure functions
A pure function:
- Always gives the same output for the same input (it depends only on its parameters).
- Has no side effects: it doesn't change any variable outside itself, write files, print, or modify its arguments.
def add_vat(price): # PURE
return price * 1.2
total = 0
def add_to_total(n): # NOT pure: changes a global
global total
total += n
# NOT pure: different results each call
def random_discount(price):
import random
return price * random.random()
Benefits: predictable, easy to test (add_vat(100) is always 120), and safe to run in parallel.
First-class functions
Functions are treated like any other value: they can be stored in variables, put in data structures, passed as arguments and returned from other functions.
def square(n):
return n * n
f = square # a function stored in a variable
print(f(4)) # 16
operations = [square, abs, str] # functions in a list
for op in operations:
print(op(-3)) # 9, 3, '-3'
Higher-order functions
A higher-order function is one that takes a function as an argument, returns a function, or both. Python's well-known ones:
| Function | Job | Example |
|---|---|---|
map(f, items) |
Apply f to every item |
map(square, [1, 2, 3]) gives 1, 4, 9 |
filter(f, items) |
Keep the items for which f is true |
filter(is_even, [1, 2, 3, 4]) gives 2, 4 |
reduce(f, items) |
Combine all the items into one value | reduce(add, [1, 2, 3, 4]) gives 10 |
from functools import reduce
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda n: n % 2 == 0, nums)) # [2, 4, 6]
squares = list(map(lambda n: n * n, evens)) # [4, 16, 36]
total = reduce(lambda a, b: a + b, squares) # 56
print(total)
A lambda is a short anonymous function. A function that returns a function:
def make_multiplier(factor):
return lambda x: x * factor
double = make_multiplier(2)
print(double(7)) # 14
Immutable variables
Once a value is created, it is never changed: instead of modifying data, you create new data. Python's tuples and strings are immutable.
# mutable (procedural style)
scores = [50, 60]
scores.append(70) # the list is changed in place
# immutable (functional style)
scores = (50, 60)
# a NEW tuple; the original is unchanged
new_scores = scores + (70,)
Benefits: no unexpected changes, safe sharing between parts of a program or threads, and easier to follow how a value came about.
Avoiding side effects
A function shouldn't change anything outside itself or depend on hidden state. Everything it needs comes in through parameters, and everything it produces goes out through its return value. This is why pure functions and immutability work together.
# side effect: modifies the list it was given
def add_item(items, x):
items.append(x)
# no side effect: returns a new list
def add_item_pure(items, x):
return items + [x]
Recursion in place of loops
Pure functional code has no changing loop counters, so it uses recursion (5.1.3) instead of loops:
def total(items):
if not items:
return 0
return items[0] + total(items[1:])
Imperative (procedural) and functional compared
| Procedural / imperative | Functional | |
|---|---|---|
| Describes | Steps that change state | Functions applied to data |
| Variables | Changed as the program runs | Immutable |
| Loops | for, while |
Recursion, map, filter, reduce |
| Side effects | Common | Avoided |
| Functions | May depend on and change global state | Pure |
Benefits
- Easier to test and debug: same input, same output.
- Easier to reason about: no hidden state changes.
- Safe for parallel and concurrent code (no shared changing data, 11.1.4).
- Reusable, small, composable functions.
- Fewer bugs from unexpected changes.
- Concise code for data transformations.
Drawbacks
- A different way of thinking: harder to learn for many programmers.
- Recursion and creating new data can use more memory and be slower.
- Some things need side effects (input and output, databases, user interfaces), so real programs must manage them carefully.
- Less natural for tasks based on changing state (such as games with moving objects).
- Fewer examples and libraries in some situations, and debugging deeply nested recursion can be harder.
Worked example
Task: a list of marks must be processed: keep passes (50 or more), add 5 bonus marks (maximum 100), and find the average. Write it in a functional style, and explain why it is functional.
from functools import reduce
marks = [45, 72, 38, 90, 55]
passes = filter(lambda m: m >= 50, marks) # keep passes
boosted = map(lambda m: min(m + 5, 100), passes) # add the bonus
boosted = list(boosted) # [77, 95, 60]
average = reduce(lambda a, b: a + b, boosted) / len(boosted)
# 77.33333333333333
print(average)
Why it's functional:
- It uses higher-order functions (
filter,map,reduce) that take functions (first-class, aslambdas). - No variable is changed in place: each step produces a new collection, and
marksis untouched (immutability). - The
lambdas are pure: same input, same output, no side effects.
Check: passes are 72, 90, 55. With bonus: 77, 95, 60. The mean is .
Exam tip: give a definition and an example for each concept: pure function (same input gives the same output, with no side effects), first-class (functions as values), higher-order (takes or returns a function), immutable (never changed). Be ready to identify these features in code, and to compare with the procedural paradigm (5.4.1).
Check yourself
What is a pure function?
A function that always gives the same output for the same input and has no side effects, so it doesn't change anything outside itself.
What is a higher-order function? Give an example
A function that takes a function as an argument or returns one, such as map, filter or reduce.
What does immutable mean?
A value that can't be changed once created; a new value is made instead of modifying the old one.
Why is functional code easier to run in parallel?
Pure functions don't share or change data, so there are no race conditions between them.
Give one drawback of functional programming
Any one of: harder to learn; recursion and new data can use more memory and time; input/output and state need special handling.