[   ^ to index...   |   <-- previous   |   next -->   ]

Recursion

A recursive definition is one that uses itself. At first, this seems like a confusing idea, but we use recursive ideas all the time in everyday life:

The second example demonstrates the fact that there must be a base case to any recursion. That is, at some point, an animal that was not, biologically, a chicken, must have laid a chicken egg. Otherwise, we have infinite recursion.

Therefore, the general formula for defining recursive functions, data structures, etc. is as follows:

  1. Define a base case for the recursion. Most often this will be zero, one, the empty list/tree/node, or something similar.

  2. Define the inductive case (or cases) that "shrinks" all other cases towards the base case.

This probably doesn't make much sense right now, but it will.

The dumbest possible recursion

It is possible to define all arithmetic operations on the integers using only "increment by 1", "decrement by 1", "compare with 0", and function application (including recursion). Here's addition:

int add(int x, int y) { if (x == 0) return y; // base case else return 1 + add(x-1, y); // inductive case }

Notice that the inductive case, by subtracting 1 from x, "shrinks" all integers down to 0, which is the base case.


Last modified: Wed Jul 5 13:35:10 PDT 2000