Reputation: 301
So I have written I function in racket that calculates Sums:
(define (sum term a next b)
(if (> a b)
0
(+ (term a) (sum term (next a) next b))))
Term is what function is applied to every argument. A is the beginning next is how we advance to the next element (i.e. a2 = 2*a1 or a2 = a1 +1 etc.) and b is the final element.
There are 2 additional functions:
(define (square x) (* x x))
(define (inc x) (+ x 1))
If I type:
(sum square 1 inc 5) I get which is correct 55
But if I type:
(sum square 1 square 5)
I am stuck in a loop!? Why is that a2 should be a1*a1 and a3=a2*a2 and a should surpass b so the condition to end the recursion would be fultifield. Very strange.
Upvotes: 1
Views: 165
Reputation: 1819
Your sum
function will loop forever because (square 1)
always evaluates to 1
and will never be greater than 5
.
Upvotes: 8