impera Open Impera

A levels Computer Science · Programming and data

Functional programming

1Functions as first-class objects

In functional programming, a program is built from functions. A function maps each value in its domain to a value in its codomain; its type is written f: A → B.

Functions are first-class objects: they can be stored in variables, passed as arguments and returned as results.

def double(x):
    return 2 * x

f = double # store a function in a variable
print(f(7)) # 14
square = lambda x: x * x
print(square(5)) # 25

A lambda is a function with no name, useful for short functions passed to others.

Check yourself

What does it mean for functions to be first-class objects?

  • They run before all other code when the program is loaded

  • They cannot take other functions as parameters or return them

  • They can be stored, passed as arguments and returned like any other value

  • They must always have a name and cannot be anonymous lambdas

Show the answer

They can be stored, passed as arguments and returned like any other value

Treated like data.

2Pure functions and immutability

A pure function always gives the same output for the same input and has no side effects: it does not change global variables, files or its arguments.

  • Data is immutable: instead of changing a value, a new value is created.
  • Without side effects, code is easier to test, reason about and run in parallel, because functions cannot interfere with each other.
def add_item(lst, x):
    return lst + [x]          # returns a new list; lst is unchanged
Check yourself

Which of these is a side effect?

  • Using a parameter

  • Calling another pure function

  • Returning a value

  • Changing a global variable

Show the answer

Changing a global variable

Changes the outside world.

3Function application and composition

Function application gives a function its arguments. Composition combines two functions: (g ∘ f)(x) = g(f(x)), so f is applied first.

Worked example

Composing functions

  1. f(x) = x + 2 and g(x) = 3x.
  2. (g ∘ f)(4) = g(f(4)) = g(6) = 18.
  3. (f ∘ g)(4) = f(g(4)) = f(12) = 14.
  4. Order matters: g ∘ f is not the same as f ∘ g.

For g ∘ f to work, the codomain of f must match the domain of g.

Check yourself

If f(x) = x² and g(x) = x + 1, what is (g ∘ f)(3)?

  • 10

  • 9

  • 16

  • 4

Show the answer

10

f first: 9, then + 1.

4Partial application

A function of two arguments can be seen as a function that takes one argument and returns a function for the second. Its type is written add: int → (int → int), or int → int → int.

Partial application fixes some arguments to make a new function:

from functools import partial

def add(x, y):
return x + y

add3 = partial(add, 3) # a new function: y → 3 + y
print(add3(10)) # 13

Check yourself

What is the type of a function that takes two integers and returns a Boolean, written in functional style?

  • int → int → bool

  • bool → int → int

  • int → bool

  • (int, bool) → int

Show the answer

int → int → bool

One argument at a time.

5Higher-order functions: map, filter and fold

A higher-order function takes a function as an argument or returns one.

FunctionDoesExampleResult
mapapplies a function to every itemmap(square, [1, 2, 3, 4])[1, 4, 9, 16]
filterkeeps items that pass a testfilter(is_even, [1, 4, 9, 16])[4, 16]
fold (reduce)combines all items into one valuefold(+, 0, [4, 16])20

Chaining higher-order functions: map, then filter, then fold turns [1, 2, 3, 4] into 20, the sum of the even squares.

from functools import reduce
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
evens = list(filter(lambda x: x % 2 == 0, squares))
total = reduce(lambda a, b: a + b, evens, 0)     # 20
Check yourself

What does filter(lambda x: x > 2, [1, 3, 5, 2]) give?

  • [3, 5, 2]

  • [3, 5]

  • [1, 2]

  • 8

Show the answer

[3, 5]

Keep items > 2.

6Lists: head and tail

In functional languages a list is either empty or a head (its first item) joined to a tail (the rest of the list, itself a list).

ExpressionResult
head [4, 7, 9]4
tail [4, 7, 9][7, 9]
2 : [4, 7] (prepend)[2, 4, 7]
length []0

There are no loops; lists are processed by recursion:

def total(lst):
    if lst == []:                    # base case: empty list
        return 0
    return lst[0] + total(lst[1:])   # head + total of tail

Functional languages such as Haskell are used where correctness and parallel processing matter, for example in finance and big data (the "MapReduce" pattern comes from map and fold).

Check yourself

What is the tail of [5, 8, 1]?

  • [8, 1]

  • 5

  • [5, 8]

  • 1

Show the answer

[8, 1]

Everything after the head.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera