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.
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 part | What corresponds to it in a loop |
|---|---|
| A base case | The stopping condition |
| A step that shrinks | The 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
- The list holds three items.
- Each call passes a list shorter by one.
- After three calls it is empty.
- There the base case answers directly.
Example 2 — why the depth need not be known
- Each call deals only with its own problem.
- It assumes its own call will return correctly.
- The assumption is true at the base.
- And every step preserves it.