Skip to content
UoL CS Notes

Lecture 2-1

COMP105 Lectures

What is a pure function?

A function takes inputs and produces outputs. E.g. Input: $x$, Output: $f(x)$

In imperative languages, functions can do much more and are called subroutines.

Every function can be implemented in a subroutine but not all subroutines are functions.

A function maps inputs to outputs, however subroutines can have an effect on the global state. The global state is anything that is not within the function, such as modifying global variables, printing, network access…

Pure functions only influence the outside world through the return value.

When does this matter?

When the compiler compiles the code it may want to change the order of the instructions:

y = f(1) + f(2)  
y = f(2) + f(1)

For a function this will work but for a subroutine it may write out globally and not produce the desired effect.

Using functions makes compiler optimisations, code refactoring, and parallelization easier as the functions can be run in different orders, or concurrently at runtime.

More Rules

Pure functions always return a value

This is because pure functions only interact via their return value. If they don’t have a return value they have no effect.

Pure functions must be deterministic.

This means that they must return the same value every time, provided that they have the same input.

Determinism allows for logical assumptions such as f(x) + f(x) == 2 * f(x). If the function was a subroutine and returned a random value this wouldn’t be the case.

Summary

  • Pure Functions
    • Are a black box
    • Have no side effects
    • Are deterministic

Every pure function is a subroutine, some subroutines are not pure functions.