Home Segments Index Top Previous Next

314: Mainline

If you are not yet familiar with recursion, it is best to see how recursion works through an example involving a simple mathematical computation that you already know how to perform using iteration. Suppose, for example, that you want to write a method, recursivePowerOfTwo, that computes the nth power of 2 recursively.

To define recursivePowerOfTwo, you can take advantage of the powerOfTwo method already provided in Chapter 16, because one way to define recursivePowerOfTwo is to hand over the real work to powerOfTwo:

Integer method definition • instance 
recursivePowerOfTwo 
  ^ self powerOfTwo 
Workspace
Transcript show: 4 recursivePowerOfTwo printString; cr  
Transcript 
16