sicp-ex-1.3



<< Previous exercise (1.2) | sicp-solutions | Next exercise (1.4) >>


 (define (square x) (* x x)) 
  
 (define (squareSum x y) (+ (square x) (square y))) 
  
 (define (sumOfLargestTwoSquared x y z) 
   (cond ((and (>= (+ x y) (+ y z)) (>= (+ x y) (+ x z))) (squareSum x y)) 
         ((and (>= (+ x z) (+ y z)) (>= (+ x z) (+ x y))) (squareSum x z)) 
         (else (squareSum y z)) 
   ) 
 ) 

one more way to determine sum of largest two numbers among 3 numbers

  (define (sumOfLargestTwoSquared x y z)  
    (+(if (>(* x x)(* y y))  
          (* x x)  
          (* y y))  
      (if (>(* y y)(* z z))  
          (* y y)  
          (* z z)))   
   )  
 (sumOfLargestTwoSquared 1 2 3) 
 ;Value: 13 
 (sumOfLargestTwoSquared 1 1 1) 
 ;Value: 2 
 (sumOfLargestTwoSquared 1 2 2) 
 ;Value: 8 
 (sumOfLargestTwoSquared 1 1 2) 
 ;Value: 5 
 (sumOfLargestTwoSquared 1 4 3) 
 ;Value: 25 

mdsib

Here's a version with simpler logic to detect the smallest of the three values:

 (define (ssq a b) (+ (* a a) (* b b))) 
  
 (define (sumOfLargestTwoSquared x y z) 
   (cond ((and (<= x y) (<= x z)) (ssq y z)) 
         ((and (<= y x) (<= y z)) (ssq x z)) 
         (else (ssq x y))))