Home > Mobile >  Where does function gets values
Where does function gets values

Time:08-05

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:

  1. The function stops when b become larger than a after n times of iterations?
  2. If so, function must take the value c (because of if (> b a) c), and to me it's seems like there is really no manipulation with c inside the code so it's just must display argument that we give at start? Or the values (* b c) goes to c (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.

  1. Yes. Each recursion call with b incrementing by 1, so it will stop after a iterations.

  2. 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.

  • Related