chong.franklin
2/10/2016 2:02:00 PM
On Wednesday, February 10, 2016 at 9:43:15 PM UTC+8, Dan Sommers wrote:
> On Wed, 10 Feb 2016 14:09:19 +0100, Norbert_Paul wrote:
>
> > franklin wrote:
>
> >> (define (factorial n)
> >> (define (iter product counter)
> >> (if (> counter n)
> >> product
> >> (iter (* counter product)
> >> (+ counter 1))))
> >> (iter 1 1))
>
> >> (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?
>
> > Without having tested if your second example is correct, both seem equivalent.
> > You merely rename counter to n and decrease it from n to 1.
> > So SICP's iteration does 1 * 2 * ... * n by incrementing counter
> > You seeminly do n * ... * 2 * 1 by decrementing n.
> > To me neither is more obvious than the other.
>
> They give different results for (factorial 0).
That might be, but changing (= n 1) to (= n 0) fixes the problem.