I’m trying to write a scheme function that does the following (taken from SICP):
Exercise 1.3. Define a procedure that takes three numbers as arguments
and returns the sum of the squares of the two larger numbers.
Here’s my attempt:
(define (square-sum-larger a b c)
(cond ((and (< a b) (< a c))) (+ (* b b) (* c c)))
(cond ((and (< b c) (< b a))) (+ (* a a) (* c c)))
(cond ((and (< c a) (< c b))) (+ (* b b) (* a a)))
)
When I enter this into the biwa scheme interpreter, I get the following:
(square-sum-larger 4 5 6)
16
Since 4 is less than 5 and 6, shouldn’t the first condition be evaluated, meaning that the sum of the squares of 5 and 6 should be returned?
>Solution :
(define (square-sum-larger a b c)
(cond ((and (< a b) (< a c))) (+ (* b b) (* c c))) ;; this is thrown away
(cond ((and (< b c) (< b a))) (+ (* a a) (* c c))) ;; this is thrown away
(cond ((and (< c a) (< c b))) (+ (* b b) (* a a)))
)
Only the last of the three cond does anything useful; the previous cond expressions do not have any side effect, since they perform only calculations, and their value is not used. The are dead code which a Scheme compiler can eliminate entirely.
You probably wanted to combine all of the clauses into a single cond:
(define (square-sum-larger a b c)
(cond ((and (< a b) (< a c))) (+ (* b b) (* c c))
((and (< b c) (< b a))) (+ (* a a) (* c c))
((and (< c a) (< c b))) (+ (* b b) (* a a))))