There is a code:
(define (factorial a)
(define (iter b c)
(if (> b a) c
(iter (* b c)
( b 1))
(iter 1 1)
I got some questions:
- The function stops when
b
become larger thana
after n times of iterations? - If so, function must take the value
c
(because ofif (> b a) c)
, and to me it's seems like there is really no manipulation withc
inside the code so it's just must display argument that we give at start? Or the values(* b c)
goes toc
(it really does), but why?
CodePudding user response:
The code should be:
(define (factorial a)
(define (iter b c)
(if (> b a) c
(iter ( b 1)
(* b c))
(iter 1 1))
with the arguments to iter
in the other order.
Yes. Each recursion call with
b
incrementing by 1, so it will stop aftera
iterations.When you call
(iter ( b 1) (* b c))
(* b c)
goes to c
in the recursive call. So each recursion multiplies c
by the current value of b
. Since we add 1 to b
each time, this results in multiplying 1 * 2 * 3 * 4 ...
, which is the definition of factorial.