SICP recursive process vs iterative process: using a recursive procedure to generate an iterative process

A recursive process needs to maintain the state of the caller while the recursive call is in progress. For instance, if you wrote:

(define (fact-recurse n)
  (if (< n 2)
      1
      (* n (fact-recurse (- n 1)))))

the outer call has to remember n and wait for the inner call to return before it can perform the multiplication. If you call (fact-recurse 10) there will be 9 stacked multiplications pending when the function reaches the end of its recursion.

But in an iterative process, the earlier state can be discarded. This is possible in the example code because all the information needed is passed as parameters in the recursive call. The variables in the outer call are no longer needed, so nothing needs to be kept on a stack.

Since the outer call’s parameters are no longer needed, the recursive call can be translated into assignments:

(set! product (* counter product))
(set! counter (+ counter 1)
(set! max-count max-count)

and then it just jumps to the beginning of the procedure.

Leave a Comment