Lecture 17 - Recursion

We talked in class about how to think about recursion:

  1. Define a type with all of the methods that both base case and recursive case classes must implement.
  2. Define an object or class representing the base case(s). Make sure that all methods from the type are implemented. Convince yourself that the methods work correctly. (Usually they just do very trivial things!)
  3. Define the recursive class(es). Defs and instance variables that have the same type of object as being constructed should only refer to objects simpler than the one being constructed. In particular, the construction of simpler objects in the body of the class should eventually end up at a base case. Convince yourself that the initialization will be correct under the assumption that the construction of simpler objects is correct.
  4. Write each method under the assumption that it works correctly on all simpler objects. Convince yourself that the methods will be correct under the assumption that instance variables hold simpler objects.

See the program ChainReaction Click to create a new ball and move the mouse in and out of the window to get the chain reaction.

For a final demonstration of a recursive picture see broccoli BroccoliTest Notice that you can drag it around.

We can also do recursion in methods rather than classes and objects. This is when you have a method that requests itself during a computation. As a first example, we saw an algorithm to computer fast powers of numbers. powers