Search code examples
schemesicp

Is my implementation of SICP Exercise 1.3 going in the right direction?


Exercise 1.3 in SICP asks to define a procedure that takes 3 numbers as arguments and returns the sum of the squares of the 2 largest numbers. I think I've gotten it correct but I wasn't totally sure if I've covered all cases. My implementation is as follows:

(define (bigsq a b c)
    (cond ((and (> a b) (> b c)) (+ (* a a) (* b b)))
          ((and (> a b) (not (> b c))) (+ (* a a) (* c c)))
          ((> c a) (+ (* b b) (* c c)))
          (else (+ (* a a) (* b b))))

Is there a way to write those first 2 conditions as one, as well? Also any comments on efficiency are welcome as well.


Solution

  • For starters, we could use a helper procedure for implementing the sum just once:

    (define (sum x y)
      (+ (* x x) (* y y)))
    

    Now, for the conditions: given that the order doesn't matter - (sum a b) is the same as (sum b a), there's only 4 cases to consider, and we can avoid repeating some of the comparisons by nesting ifs:

    (define (sum-max a b c)
      (if (>= a b)
          (if (>= b c)
              (sum a b)
              (sum a c))
          (if (>= a c)
              (sum b a)
              (sum b c))))