[英]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. 我正在阅读sicp,有一个问题(练习1.29),我编写了一个scheme函数来解决该问题,但似乎该函数的递归调用得到了错误的答案。 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函数:
(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. 我希望得到6,但是它又返回了10,我不确定错误在哪里。在我看来,Simpson函数内部定义的函数“ sum”不正确。
If I rewrite the sum function inside of simpson using the iteration instead of recursive, I get the right answer. 如果我使用迭代而不是递归的方式在辛普森内部重写sum函数,那么我会得到正确的答案。
您需要将总和乘以h/3
:
(* 1/3 h (sum term a next b))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.