Choosing a Base Case for Recursion
A base case produces an answer directly for an input that needs no further recursive work.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Look for the smallest legal input
A recursive sum can stop on an empty list and return zero. A routine computing the smallest element of a guaranteed nonempty list can stop at a list of one item and return it. Its input contract determines whether empty input needs a separate result.
Trace the transition to the base
For values 4 and 8, a first-plus-rest approach calls the routine on 8 and eventually on the empty tail. Check even a singleton call, since its recursive step can reach a smaller domain than expected. A termination measure establishes that this descent stops.[1]
Include the identity case used by the recurrence
To sum a list recursively, combine its first element with the sum of its remainder. The call for an empty list returns zero, the additive identity. That decision supports a singleton and an initially empty input with one rule. Test both before trying longer recursive list processing.
sum([2, 7]) = 2 + sum([7])
sum([7]) = 7 + sum([])
sum([]) = 0
Return through the waiting calls: 0, 7, 9
Justify the stopping rule for the whole domain
A recursion on nonnegative integers that subtracts two needs stopping cases for zero and one. Stopping only at zero misses every odd input. Define what negative inputs mean before applying the rule. A base case should return immediately without attempting decomposition.