This is a factorial procedure from SICP that generates a recursive process.
(define (factorial n)
(if (= n 1)
1
(* n (factorial (- n 1)))))
Now this is the same procedure, but generates an iterative process. Counter increments up to n and product multiplies itself by counter in each procedure call. When not in a block structure, fact-iter has a variable max-count which is actually n.
(define (factorial n)
(define (iter product counter)
(if (> counter n)
product
(iter (* counter product)
(+ counter 1))))
(iter 1 1))
I'm a little curious as to why we need counter, it doesn't really do anything but incrementing itself and using its value for testing the base case. as with the recursive process, can't we just do the same process while just adding an accumuator to make it iterative? For example:
(define (factorial n)
(define (fact-iter product n)
(if (= n 1)
product
(fact-iter (* n product)
(- n 1))))
(fact-iter 1 n))
So, this is still an iterative process, and I think a more obvious procedure than the first example.
However, there must be a reason why the book prefered the first example. So what is the advantage of the first iterative example over the second procedure?
n
in the inner function. That's needlesly confusing. – jkiiski(= n 1)
in(= n 0)
in your function, otherwise(factorial 0)
causes an endless loop. – Renzo1 * 2 * ... * n
and the second asn * (n - 1) * ... * 1
. The first is more "loop-like" and the second more "recursion-like", in my opinion. – molbdnilo