Sum of squares of 2 largest numbers out of a list of 3 numbers The problem is:


  Define a procedure that takes 3 number arguments and returns the sum of the squares of the 2 largest numbers.


I am a CS graduate and I am revising my university notes. This is my code so far:

(define (square n) (* n n))

(define (square_of_larger_numbs a b c)
  (cond ((and (&gt; a b) (&gt; a c))
         (cond ((&gt; b c)
         (+ (square a) (square b)))
               (else (+ (square a) (square c))))
        )(else (cond ((&gt; b c)
                      (+ (square b) (square c)))
                      (else (+ (square b) (square c))))
               )
         )
  )


(display (square_of_larger_numbs 4 3 3))


It seems to be working but the code looks terrible unreadable. Please note that I am not allowed to sort yet, as the book I am reading hasn't mentioned sorting yet, so I assumed that sorting is not welcomed as a part of the solution.

How can I make this more efficient/ readable?
Specification

It is helpful to specify the solution before writing code. The mathematics of sorting three values (a b c) means there are six (3!) permutations:

(define abc (a b c))
(define acb (a c b))
(define bac (b a c))
(define bca (b c a))
(define cab (c a b))
(define cba (c b a))


The code must cover all six possibilities.

There are three possible outputs:

(define output-ab (+ (* a a) (* b b)))
(define output-ac (+ (* a a) (* c c)))
(define output-bc (+ (* b b) (* c c)))


The code must map the six permutations to the three outputs.

abc || bac -&gt; output-ab
acb || cab -&gt; output-ac
bca || cba -&gt; output-bc


Now the code can reflect the specification

   (cond 

     ((or (and (&gt;= a b)
               (&gt;= b c))
          (and (&gt;= b a))
               (&gt;= a c)))
      output-ab)

     ((or (and (&gt;= a b)
               (&gt;= c b))
          (and (&gt;= a b))
               (&gt;= c a)))
      output-ac)

     ((or (and (&gt;= b a)
               (&gt;= c a))
          (and (&gt;= c b))
               (&gt;= b a)))
      output-bc)

     (else (error "unhandled condition")))


Review

Style

Scheme has formatting conventions. The code does better with indentation than with parenthesis.

Logic

The lack of a specification and tests based upon it leads to an incorrect implementation and poorly organized code. There is a branch which returns the same value on both paths:

 (else (cond ((&gt; b c)
                (+ (square b) (square c)))
              (else (+ (square b) (square c))))


Efficiency

Correct code is the first order objective. Writing clear code facilitates that because it makes debugging and testing and maintenance easier.

Speed of execution matters only when it matters. That is always after the code is correct and after there is an objective performance issue, not just a theoretical one. Getting a wrong answer fast may be worse than no answer at all if we mistakenly believe the wrong answer is correct.