简体   繁体   中英

Recursive call in Scheme language

I am reading sicp, there's a problem (practice 1.29), I write a scheme function to solve the the question, but it seems that the recursive call of the function get the wrong answer. Really strange to me. The code is following:

(define simpson
  (lambda (f a b n)
    (let ((h (/ (- b a) n))
          (k 0))
      (letrec
          ((sum (lambda (term start next end)
                  (if (> start end)
                      0
                      (+ (term start)
                         (sum term (next start) next end)))))
           (next (lambda (x)
                   (let ()
                     (set! k (+ k 1))
                     (+ x h))))
           (term (lambda (x)
                   (cond
                     ((= k 0) (f a))
                     ((= k n) (f b))
                     ((even? k) (* 2
                                   (f x)))
                     (else (* 4
                              (f x)))))))
        (sum term a next b)))))

I didn't get the right answer.

For example, if I try to call the simpson function like this:

(simpson (lambda (x) x) 0 1 4)

I expected to get the 6, but it returned 10 to me, I am not sure where the error is.It seems to me that the function "sum" defined inside of Simpson function is not right.

If I rewrite the sum function inside of simpson using the iteration instead of recursive, I get the right answer.

您需要将总和乘以h/3

 (* 1/3 h (sum term a next b))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM