2

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 ?? ??))
4

3 に答える 3

5

まず、プロシージャが4 つのパラメータsumを受け取ることに注意してください。明らかに、ソリューションの一部としてそれらすべてを使用する必要があります。特に、2 つのプロシージャはある時点で必要になります。それぞれが表すものは次のとおりです。

  • 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?
于 2013-09-10T13:39:13.127 に答える
1

さて、2 つのiter呼び出しがあり、どの値をそれらに入れるかを決める必要があります。

  • 外側の呼び出しでは、 anditerの初期値を決定する必要があります。 aresult
    • の初期値については、最初より大きかっresultた場合に関数が何を返すべきかを考えてください。ab
  • 内部iter呼び出しでは、 and の次の値を決定する必要がaありresultます。
    • の次の値についてはresult、現在の数値を前の結果に追加する必要があります。

これが役立つことを願っています。

于 2013-09-10T06:09:05.450 に答える