我正在尝试编写一个在a和b之间添加所有数字的过程。例如,如果a = 1且b = 5,则该过程将添加1 + 2 + 3 + 4 + 5。这是我到目前为止所拥有的。我想迭代地写这个。谢谢!
(define (sum term a next b)
(define (iter a result)
(if (> a b)
sum
(iter ?? ??)))
(iter ?? ??))
答案 0 :(得分:5)
对于初学者,请注意sum
过程接收四个参数,显然您 将所有这些参数用作解决方案的一部分,特别是,在某些时候需要这两个程序。以下是每个人所代表的内容:
term
:应用于序列的每个元素的函数a
:范围的起始编号(含)next
:用于确定序列的下一个元素的函数b
:范围的结束数字(包括)例如,这是您使用问题中的示例测试过程的方法:
(sum identity 1 add1 5)
=> 15
(= (sum identity 1 add1 5) (+ 1 2 3 4 5))
=> #t
但是等等,我们如何实施呢?这是你要发现的 - 如果我们马上给你答案,那对你没有任何好处,但我可以给你一些提示:
(define (sum term a next b)
; internal procedure for implementing the iteration
; a : current number in the iteration
; result : accumulated sum so far
(define (iter a result)
(if (> a b) ; if we traversed the whole range
result ; then return the accumulated value
(iter ; else advance the iteration
?? ; what's the next value in the range?
(+ ; accumulate the result by adding
?? ; the current term in the range and
??)))) ; the accumulated value
; time to call the iteration
(iter ?? ; start iteration. what's the initial value in the range?
??)) ; what's the initial value of the sum?
答案 1 :(得分:1)
好的,所以你有两个iter
来电,你必须决定将哪些值放入其中:
iter
来电,您必须确定a
和result
的初始值。
result
的初始值,请考虑一下如果a
大于b
,您的函数应该返回什么。iter
来电,您必须确定a
和result
的下一个值是什么。
result
的下一个值,您应该将当前数字添加到上一个结果中。我希望这会有所帮助。
答案 2 :(得分:0)
许多算法都需要迭代,就像辛普森对近似积分的规则一样。我们可以通过调用迭代帮助器来“伪造”迭代。
(define (sum a b)
(sum-iter a b 0))
(define (sum-iter index n sum)
(if (= n index)
(+ sum index)
(+ (sum-iter n (+ index 1) (+ sum index)))
)