3
\$\begingroup\$

Define a procedure that takes three numbers as arguments and returns the sum of squares of the two largest numbers.

I'm using just the machinery that was developed so far in SICP to be true to the exercise. My method works as far as I can tell -- I tested it for a number of cases and tested different permutations of inputs and get the same answers in each case. I just wasn't sure if there were a better way to do this exercise. Any feedback whatsoever is welcomed.

;; Define the squaring function. 
(define (square n)
 (* n n)
)
;; Define the maximum of two inputs a and b.
(define (mx a b)
 (cond ((< a b) b)
 ((< b a) a)
 ((= a b) a))
)
;; Define the constant of elimination. 
 (define (coe x y z)
 (cond ((= x y) (-(square x)))
 ((= y z) (-(square y)))
 ((= x z) (-(square z))))
)
;; Define the sum of squares function. It consists of the sum of squares of the maxima of
;; each of three possible pairs of three elements. Two of the first three terms will always
;; evaluate to the same value, and so the constant of elimination is added to get rid of the redundant term. 
(define (sosl a b c)
 (+ (square (mx a b)) (square (mx b c)) (square (mx a c)) (coe (mx a b) (mx b c) (mx a c)) )
)
asked Apr 8, 2016 at 5:50
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

In my opinion this is too much code for such a simple task.

Assuming that you do not have a max function, you can define it in this way:

 (define (max x y)
 (if (>= x y) x y))

or, if you cannot use if:

(define (max x y)
 (cond ((>= x y) x)
 (#t y)))

Then, the function sosl could be defined as:

(define (sosl a b c)
 (if (> a b) 
 (+ (square a) (square (max b c)))
 (+ (square b) (square (max a c)))))

or, again, if you need to use cond, as

(define (sosl a b c)
 (cond ((> a b) (+ (square a) (square (max b c))))
 (#t (+ (square b) (square (max a c))))))
answered Apr 8, 2016 at 7:06
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.