Sum of squares of two largest of three numbers Given the following problem (SICP Exercise 1.3):


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


I wrote the following (somewhat clumsy) solution in Scheme.  How can I make it better?

(define (greatest-two a b c)
  (cond ((&gt; a b) (cond ((&gt; b c) (list a b))
                       (else (list a c))))
        ((&gt; a c) (cond ((&gt; c b) (list a c))
                       (else (list a b))))
        (else (list b c))))

(define (square x) (* x x))
(define (sum-of-squares a b) (+ (square a) (square b)))
(define (f a b c)
  (apply sum-of-squares (greatest-two a b c)))
Scheme is a lot more functional than Common Lisp. The way you can apply that to this situation is by making more use of passing functions around (to the point that this problem is almost a one-liner). For the puzzle as written, I'd do something like

(define (big-squares a b c)
   (apply + (map (lambda (n) (* n n))
                 (take (sort (list a b c) &gt;) 2))))


If you wanted to decompose it properly into named functions

(define (square num) (expt num 2))
(define (sum num-list) (apply + num-list))
(define (two-biggest num-list) (take (sort num-list &gt;) 2))

(define (big-squares a b c) (sum (map square (two-biggest (list a b c)))))


If you wanted to go completely overboard, also toss in

(define (squares num-list) (map square num-list))


which would let you define big-squares as

(sum (squares (two-biggest (list a b c))))


(code above in mzscheme)