Recursion in Lisp

A recursive program calls itself as a subroutine. Recursion allows programs that are powerful, yet simple and elegant. Often, a large problem can be handled by a small program which:

  1. Tests for a base case and computes the value for this case directly.

  2. Otherwise,
    1. calls itself recursively to do smaller parts of the job,

    2. computes the answer in terms of the answers to the smaller parts.


   (define (factorial n)
     (if (<= n 0)
         1
         (* n (factorial (- n 1))) ) )

Rule: Make sure that each recursive call involves an argument that is strictly smaller than the original; otherwise, the program can get into an infinite loop.

A good method is to use a counter or data whose size decreases with each call, and to stop at 0; this is called a well-founded ordering.

Contents    Page-10    Prev    Next    Page+10    Index