The exercise asks us to write a procedure which returns the sum of the squares of the two larger numbers given three numbers.
First, we setup the
(define (square x) (* x x))
and using this, write a procedure to return the sum of the squares of two given numbers.
(define (sum-squares x y) (+ (square x) (square y)))
Now, we need to write the procedure. Given three numbers,
z, there are three possibilities:
(and (< x y) (< x z)), which means that
xis the smallest of the three numbers, so we need to return the sum of the squares of
(and (< y x) (< y z)), which means that
yis the smallest and we need to return the sum of the squares of
(and (< z x) (< z x)), which means that
zis the smallest and we need to return the sum of the squares of
y. If we check for the first two conditions, we don’t need to explicitly state the third one, since if either
yis not the smallest, then
zis the smallest one.
So, the procedure can now be written as:
(define (sum-squares-largest x y z) (cond ((and (< x y) (< x z)) (sum-squares y z)) ((and (< y x) (< y z)) (sum-squares x z)) (else (sum-squares x y))))
The given procedure can also be written without
cond expressions by using the built-in procedures
Suppose we take the pair
(y, z), then at least one variable out of this pair is in the maximum two and it is indeed the maximum of these 2 variables, i.e.
(max y z). Now, to find if the other variable, i.e.
(min y z) is in the maximum two, we can take the maximum of that with
x, thus giving us the procedure
(define (sum-square-largest x y z) (sum-squares (max y z) (max x (min y z))))
Another clever way to do this question is by using rotations, as specified in the blog ProgrammingPraxis.
The idea is to recursively call the same procedure until the first argument is the minimum of the three, and this is done by rotating the arguments at every call until the minimum is at the first position.
(define (sum-square-largest x y z) (if (= x (min x y z)) (sum-squares y z) (sum-square-largest y z x)))
The above procedure works by finding out the minimum of the three variables using the
min procedure, and comparing it with the first argument, if they are found equal, the sum of squares of the other two arguments is calculated, else, the arguments are rotated and the procedure is recursively called. The procedure can be called a maximum of 3 times (including the first call).