## A Surprising Solution

In Exercise 1.3 of SICP, we are asked to define a procedure that
take three numbers as input and returns the sum of the squares of the
2 larger numbers. We already have a procedure, `sum-of-squares`

, that
returns the sum of the squares of its two inputs, so a natural
solution is something of the sort

(define sum-of-squares-of-max (lambda (a b c) (sum-of-squares (if (< a b) b a) (if (< (if (< a b) a b) c) c (if (< a b) a b)))))

or, perhaps, the less opaque

(define sum-of-squares-max (lambda (a b c) (cond ((and (<= a b) (<= a c)) (sum-of-squares b c)) ;;a smallest ((and (<= b a) (<= b c)) (sum-of-squares a c));;b smallest (else (sum-of-squares a b))))) ;;c smallest

Joe Marshall over at Abstract Heresies offers this surprising and elegant solution

(define sum-of-squares-max (lambda (a b c) (if (and (<= a b) (<= a c)) ;;a smallest (sum-of-squares b c) (sum-of-squares-max b c a))))

## No comments:

## Post a Comment