繁体   English   中英

从a到b的方案总和

[英]Scheme Sum from a to b Iteratively

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

对于初学者来说,注意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?

好的,因此您有两个iter调用,并且必须确定要在其中放入哪些值:

  • 对于外部iter调用,您必须确定aresult的初始值是什么。
    • 对于result的初始值,请考虑一下,如果a大于b ,函数应该返回什么。
  • 对于内部iter调用,您必须确定aresult的下一个值是什么。
    • 对于result的下一个值,您应该将当前数字添加到上一个结果中。

我希望这有帮助。

许多算法都要求迭代,例如用于近似积分的辛普森规则。 我们可以通过调用迭代助手来“伪造”迭代。

(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)))
 )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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