Grade 9 Computer Science · Recursion

A function that calls itself

Two required parts, and what happens when one is missing.

A total with no loop and no counter

You can add up all the numbers in a list with no loop, no counter and no accumulator: the total is the first number plus the total of all the rest. That definition sounds like a circle that never ends — and there is exactly one line that stops it from being one.

Until here a function called other functions. It is also allowed to call itself — and that sounds like an endless circle. It is not, on one condition, and once that is understood the idea becomes simple.

The problem shrinks at every call, down to a size solved directly.
def total(numbers):
    if not numbers:          # the base case
        return 0
    return numbers[0] + total(numbers[1:])   # a smaller problem

print(total([4, 7, 2]))
The partWhat corresponds to it in a loop
A base caseThe stopping condition
A step that shrinksThe progress

Why this works without anyone counting

The point that is hard at first: the function does not “know” how deep it is and does not need to. Each call deals only with its own problem — the total of a list — and assumes that the call it makes will return a correct answer for the smaller problem. That assumption is justified because it is true at the base, and because every step preserves it. This is exactly the same structure of proof we saw: a claim kept at every stage, and a base at which it is true.

Example 1 — following the descent

  1. The list holds three items.
  2. Each call passes a list shorter by one.
  3. After three calls it is empty.
  4. There the base case answers directly.

Example 2 — why the depth need not be known

  1. Each call deals only with its own problem.
  2. It assumes its own call will return correctly.
  3. The assumption is true at the base.
  4. And every step preserves it.
Delete lines 2–3, and no call ever reaches an end: an error about exceeded depth appears.