SICP Exercise 1.3
Question
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
Answer
Here is my first attempt at an implementation of the solution. For this, I summed up the squares of all 3 numbers and then subtracted the smallest one.
(define (f a b c)
(- (+ (* a a) (* b b) (* c c))
(cond ((not (or (> a b) (> a c))) (* a a))
((not (or (> b c) (> b a))) (* b b))
(else (* c c)))))
Of course, this is not a particularly elegant solution.
A much better way would be to determine first whether a
is the smallest variable (by comparing against both b
and c
) and if it is, summing b
and c
.
This could then be repeated for the two other variables.
Here is the code for this implementation:
(define (g a b c)
(cond ((and (< a b) (< a c)) (+ (* b b) (* c c)))
((and (< b c) (< b a)) (+ (* a a) (* c c)))
(else (+ (* a a) (* b b)))))
We can improve this further by outsourcing the summing of the squares in order to repeat ourselves less and to make the code more readable.
(define (sumsquares a b)
(+ (* a a) (* b b)))
(define (h a b c)
(cond ((and (< a b) (< a c)) (sumsquares b c))
((and (< b c) (< b a)) (sumsquares a c))
(else (sumsquares a b))))