简体   繁体   中英

Scheme Sum from a to b Iteratively

I am trying to write a procedure that adds all the numbers between a and b. For example if a=1 and b=5, the procedure would add 1+2+3+4+5. Here's what I have so far. I want to write this iteratively. Thanks!

(define (sum term a next b)
  (define (iter a result)
    (if (> a b)
        sum
        (iter ?? ??)))
  (iter ?? ??))

For starters, notice that the sum procedure receives four parameters, clearly you'll have to use all of them as part of the solution, in particular, the two procedures will bee needed at some point. Here's what each one represents:

  • term : function to apply to each element of the sequence
  • a : starting number of the range (inclusive)
  • next : function to determine the next element of the sequence
  • b : ending number of the range (inclusive)

For instance, this is how you'd test the procedure with the example in the question:

(sum identity 1 add1 5)
=> 15

(= (sum identity 1 add1 5) (+ 1 2 3 4 5))
=> #t

But wait, how do we implement it? that's for you to discover - it won't do you any good if we give the answer right away, but I can give you some hints:

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

Okay, so you have two iter calls, and you have to decide which values to put into them:

  • For the outer iter call, you have to decide what the initial value for a and result is.
    • For the initial value of result , think about what your function should return if a were greater than b to begin with.
  • For the inner iter call, you have to decide what the next value for a and result will be.
    • For the next value of result , you should add in the current number to the previous result.

I hope this helps.

A lot of algorithms call for iteration, like simpson's rule for approximating integrals. We can 'fake' the iteration by calling an iterative helper .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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