Exercise 1.3

Pre-exercise Theory

A procedure can be defined in Scheme like this:

(define (cube x) (* x x x))

The problem

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

(define (squared_sum_of_two_largest x y z)
        (define (squared x) (* x x))
        (define (sum_of_squares x y) (+ (squared x) (squared y)))
        (
            cond
            ((and (>= x y) (>= y z)) (sum_of_squares x y))
            ((and (>= y x) (>= x z)) (sum_of_squares y x))
            ((and (>= y z) (>= z x)) (sum_of_squares y z))
            ((and (>= z y) (>= y x)) (sum_of_squares z y))
            ((and (>= z x) (>= x y)) (sum_of_squares z x))
            ((and (>= x z) (>= z y)) (sum_of_squares x z))
        )
)

; z > y > x
(squared_sum_of_two_largest 2 3 4)
; 25

; x > y > z
(squared_sum_of_two_largest 4 3 2)
; 25

; y > x > z
(squared_sum_of_two_largest 3 4 2)
; 25

; z > x > y
(squared_sum_of_two_largest 3 2 4)
; 25

; x = y = z
(squared_sum_of_two_largest 2 2 2)
; 8

; x = y > z
(squared_sum_of_two_largest 3 3 2)
; 18

; x < y = z
(squared_sum_of_two_largest 2 3 3)
; 18

; z = x > y
(squared_sum_of_two_largest 3 2 3)
; 18