SICP 练习 1.11

SICP Exercise 1.11

无法获取执行结果

我认为它会无限期地重复。

我通过将计数加 1 并重复它来构建结构。

我做错了什么?

   #lang sicp
   (define (fi n)
    (f-iter 0 3 n))
 
  (define (f-iter sum count n)
    (cond ((= count (+ n 1)) sum)
          ((< count 3) count)
          (+ (f-iter sum (- count 1) n)
             (* 2 (f-iter sum (- count 2) n))
             (* 3 (f-iter sum (- count 3) n))
             sum))
          (+ count 1)
          (f-iter sum count n))

最后的代码总结了我在问题下方的评论。

For any value of n greater and equal to 3, you need the values of the function at three more values of n. For n = 3, you need f(2), f(1) & f(0). For f(4), you need f(3), f(2), f(1). You need to have three older values from the previous computation for a fresh calculation. So in your iterative function, you need to keep three arguments which store the above 3 values, one argument for storing the value of n, and a counter argument which keeps track of the progress.

(define (funcn n) (func-iter 2 1 0 n 2))

(define (func-iter p1 p2 p3 n count) ; p1 and p2 exchange places with
                                     ; p2 and p3 respectively on every iteration
  (cond ((= n 0) 0)
        ((= n 1) 1)
        ((= n count) p1) ; p1 stores the cumulative sum to be returned
                         ; when 'count' is equal to n
        (else (func-iter (+ p1 (* p2 2) (* p3 3)) p1 p2 n (+ count 1)))
  )
)

您需要做的第一件事是正确缩进您的代码:

(define (f-iter sum count n)
  (cond ((= count (+ n 1)) sum)
        ((< count 3) count)
        (+ (f-iter sum (- count 1) n)
           (* 2 (f-iter sum (- count 2) n))
           (* 3 (f-iter sum (- count 3) n))
           sum))
  (+ count 1)
  (f-iter sum count n))

让我们用注释来注释代码:

(define (f-iter sum count n)
  (cond ((= count (+ n 1)) sum)
        ((< count 3) count)
        (+ (f-iter sum (- count 1) n)       ; the syntax of COND expects
                                            ; a list with a condition as
                                            ; the first element.
                                            ; here the first element is the
                                            ; function +, which is always true.
                                            ; as such it makes no sense.

           (* 2 (f-iter sum (- count 2) n))
           (* 3 (f-iter sum (- count 3) n))
           sum))                            ; here the result of COND is not
                                            ; used anymore. It is not returned from
                                            ; f-iter.

  (+ count 1)                               ; this result is never used.

  (f-iter sum count n))                     ; this calls the same function with the
                                            ; same arguments. Thus
                                            ; f-iter calls itself
                                            ; indefinitely at this point.