まず、プロシージャが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?