方案总和从a到b迭代

时间:2013-09-10 05:43:17

标签: scheme iteration

我正在尝试编写一个在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 ?? ??))

3 个答案:

答案 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来电,您必须确定aresult的初始值。
    • 对于result的初始值,请考虑一下如果a大于b,您的函数应该返回什么。
  • 对于内部iter来电,您必须确定aresult的下一个值是什么。
    • 对于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)))
 )