As @WorBlux pointed out, you have some parenthesis problems. Besides that, I have a couple of tips:
- It's a bit clearer if you use nested
if
s to separate conditions
- Your conditions are not correct, the equality cases are missing
- If the conditions are right, it won't be necessary to have a catch-all
else
case
- You should declare a helper procedure for performing the actual squared sum
This is what I mean:
(define (sumsq x y)
(+ (* x x) (* y y)))
(define (toptwosq a b c)
(if (>= a b)
(if (>= b c)
(sumsq a b)
(sumsq a c))
(if (>= a c)
(sumsq b a)
(sumsq b c))))
The same code can be written as follows using cond
, notice how to correctly express the conditions in such a way that all cases are covered:
(define (toptwosq a b c)
(cond ((and (>= a b) (>= b c)) (sumsq a b))
((and (>= a b) (< b c)) (sumsq a c))
((and (< a b) (>= a c)) (sumsq b a))
((and (< a b) (< a c)) (sumsq b c))))
The last condition can be replaced with an else
. It's not a "catch-all", we're certain that at this point no more cases remain to be considered:
(define (toptwosq a b c)
(cond ((and (>= a b) (>= b c)) (sumsq a b))
((and (>= a b) (< b c)) (sumsq a c))
((and (< a b) (>= a c)) (sumsq b a))
(else (sumsq b c))))
And finally, if we're smart we can get rid of one case (the first and third cases are the same) and simplify the conditions even more:
(define (toptwosq a b c)
(cond ((or (>= a b c) (and (>= a c) (> b a)))
(sumsq a b))
((and (>= a b) (> c b))
(sumsq a c))
(else (sumsq b c))))