SICP-2nd-Edition-Exercise-1.30
From Boozled
Contents |
Exercise 1.30 From SICP
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:
(define (sum term a next b)
(define (iter a result)
(if <??>
<??>
(iter <??> <??>)))
(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
(define (inc a) a)
(define (step a) (+ a 1))
(define (sum term a next b)
(if (> a b)
0(+ (term a)
(sum term (next a) next b))))
(define (my-sum calc a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (+ result (calc a)) )))
(iter a 0))
(display (my-sum inc 0 step 10))
Parent Course
6.001_Structure_and_Interpretation_of_Computer_Programs

