SICP-2nd-Edition-Exercise-1.30

From Boozled

Jump to: navigation, search

Contents

Exercise 1.30 From SICP

Details from SICP are here

The (sum) procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:

  1. (define (sum term a next b)
  2.   (define (iter a result)
  3.     (if <??>
  4.         <??>
  5.         (iter <??> <??>)))
  6.   (iter <??> <??>))


Attempt

I changed the names of some of the internal functions in my answer because it seemed easier to think of the function calculating something using a than a as just a term. It's strange that this actually made it easier for me to think about the question.

Scheme

  1. (define (inc a) a)
  2. (define (step a) (+ a 1))
  3.  
  4. (define (sum term a next b)
  5.   (if (> a b)
  6.       0
  7.       (+ (term a)
  8.          (sum term (next a) next b))))
  9.  
  10. (define (my-sum calc a next b)
  11.   (define (iter a result)
  12.     (if (> a b) 
  13.         result
  14.         (iter (next a) (+ result (calc a))  )))
  15.   (iter a 0))
  16.  
  17. (display (my-sum inc 0 step 10))

Parent Course

6.001_Structure_and_Interpretation_of_Computer_Programs

Further Reading

Personal tools