Recursive Function Execution

We have seen the recursive function factorial:


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

Consider the computation of (factorial 3). A new stack frame is created in which n = 3:

n = 3

Now we can execute the code of factorial. We test (if (<= n 0) ...) and, since n = 3, evaluate (* n (factorial (- n 1))). n evaluates to 3, and then we evaluate (factorial (- n 1)) which is (factorial 2). This creates a new stack frame in which n = 2:

n = 2
n = 3

Note that the older binding, n = 3, has not gone away, but is now shadowed by a new binding n = 2 in the current stack frame.

Contents    Page-10    Prev    Next    Page+10    Index