0
\$\begingroup\$

Given the following recursive definition of sum:

(define (sum term a next b)
 (if (> a b)
 0
 (+ (term a)
 (sum term (next a) next b))))

And the task:

Exercise 1.30

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

I wrote the following code. What do you think?

(define (i-sum term a next b)
 (define (iter a result)
 (if (> a b)
 result
 (iter (next a) (+ result (term a)))))
 (iter a 0))
(define (identity x) x)
(define (inc x) (+ 1 x))
(define (sum-integers a b) (i-sum identity a inc b))
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 30, 2011 at 1:48
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

I believe your answer is correct, although I'm not sure why you need the identity, inc, and sum-integers procedure on the bottom for your solution.

answered Mar 30, 2011 at 2:04
\$\endgroup\$
3
  • \$\begingroup\$ Not homework - personal growth exercise :) \$\endgroup\$ Commented Mar 30, 2011 at 2:51
  • \$\begingroup\$ @Joshua: Haha okay, just checking. :) \$\endgroup\$ Commented Mar 30, 2011 at 2:57
  • \$\begingroup\$ They're there for testing purposes - I suppose maybe I should have removed them before posting the question?...hmm \$\endgroup\$ Commented Mar 30, 2011 at 3:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.