Lesson 2 · Unit 03
Mutation and side effects
Who changed this list? Pure functions and copies
What you practise
- Pure functions, a function that quietly changes its argument, shared mutable state, copying against mutating, why fewer moving parts are easier to test
Try a question from this lesson
Pick one
Which of these three functions are pure?
total = 0
def add(n):
global total
total += n
return total
def double(n):
return n * 2
def show(n):
print(n)
return nlet total = 0;
function add(n) {
total += n;
return total;
}
function double(n) {
return n * 2;
}
function show(n) {
console.log(n);
return n;
}let total = 0;
function add(n: number): number {
total += n;
return total;
}
function double(n: number): number {
return n * 2;
}
function show(n: number): number {
console.log(n);
return n;
}Hint
For each one ask: does it read or change anything besides its argument and its return value?
Correct answer
Only the second
Why
The first changes a global: call it twice with 1 and it answers 1, then 2. The third writes to the screen, which is an effect outside the function. Only the doubling one depends on its argument and nothing else.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Pure functions
A pure function works only from its arguments and only produces a return value. It changes nothing outside itself: not its inputs, not a global, not the screen.
Same input, same output, every time. That makes it the easiest kind of code to check, to move and to call twice.
def top_score(scores):
ordered = sorted(scores)
return ordered[-1]function topScore(scores) {
const ordered = [...scores];
ordered.sort((a, b) => b - a);
return ordered[0];
}function topScore(scores: number[]) {
const ordered = [...scores];
ordered.sort((a, b) => b - a);
return ordered[0];
}Python notesorted builds a new list, smallest first, so ordered[-1] is the largest. The list that was passed in is never touched.
TypeScript note[...scores] copies the items into a new array, and only the copy is sorted.
9 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 1× true or false
- 1× multiple choice
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.