Designing Recursive Functions
Some guidelines for designing recursive functions:
- Write a clear definition of what your function should do,
including inputs, outputs, assumptions.
Write this definition as a comment above the function code.
- Identify one or more base cases:
simple inputs for which
the answer is obvious and can be determined immediately.
- Identify the recursive case: an input
other than the base case.
How can the answer be expressed in terms of the present input and
the answer provided by this function (assuming that it works as desired)
for a smaller input?
There are two common ways of making the input smaller:
- Remove a piece of the input, e.g. remove the first element
from a linked list.
- Cut the input in half, e.g. follow one branch of a tree.