Bitpath

Lesson 1 · Unit 02

Pure functions

Same input, same output, nothing hidden

12 exercisesabout 3 min

What you practise

  • Same input, same output, no side effects
  • Separating logic from I/O
  • Injecting time and randomness instead of reaching for them

Try a question from this lesson

Pick one

You have to write a test for this dice function. Which claim can the test rely on?

import random

def roll():
    return random.randint(1, 6)
function roll() {
  const r = Math.random();
  return Math.floor(r * 6) + 1;
}
function roll(): number {
  const r = Math.random();
  return Math.floor(r * 6) + 1;
}

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's result depends only on its arguments, and it changes nothing outside itself: no globals, no printing, no files, no clock, no dice.

Same input, same output, every time. Testing one takes a call and a comparison, with nothing to set up and nothing to clean up.

total = 0

def add_impure(x):
    global total
    total += x       # changes a global
    return total

def add_pure(acc, x):
    return acc + x   # only its inputs
let total = 0;

function addImpure(x) {
  total += x;        // changes a global
  return total;
}

function addPure(acc, x) {
  return acc + x;    // only its inputs
}
let total = 0;

function addImpure(x: number): number {
  total += x;        // changes a global
  return total;
}

function addPure(acc: number, x: number) {
  return acc + x;    // only its inputs
}

Python noteglobal total is required to assign to a module-level name inside a function. Having to write it is a hint that the function is not pure.

TypeScript notelet total = 0 is inferred as number, so only the parameters need annotations.

10 more exercises in the app

  • 2× type the answer
  • 4× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 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.

One email when Bitpath is ready to try. Nothing else. Privacy