方案总和从a到b迭代

Mar*_*ang 2 iteration scheme

我正在尝试编写一个程序,在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 ?? ??))
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 5

对于初学者,请注意sum程序接收4个参数,显然你必须使用所有这些作为解决方案的一部分,特别是将蜜蜂需要在某一时刻的两个过程.以下是每个人代表的内容:

  • term:应用于序列的每个元素的函数
  • a:范围的起始编号(含)
  • next:用于确定序列的下一个元素的函数
  • b:范围的结束数字(包括)

例如,这是您使用问题中的示例测试过程的方式:

(sum identity 1 add1 5)
=> 15

(= (sum identity 1 add1 5) (+ 1 2 3 4 5))
=> #t
Run Code Online (Sandbox Code Playgroud)

但是等等,我们该如何实施呢?这是你要发现的 - 如果我们马上给你答案,它对你没有任何好处,但我可以给你一些提示:

(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?
Run Code Online (Sandbox Code Playgroud)