From SICP
Exercise 1.3: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
Square is:
(define (square x) (* x x))
I know the code could be written using language features like lambda or let, but first to remain true to the exercise, I wouldn't use features that are not discussed yet.
I took advantage of the fact that we only have three numbers that's why I am able to reduce my code into two if statements. All of the tests I've done produced correct output.
Please review my code.
(define (sum-of-squares a b c)
(if (> a b)
(+ (square a)
(square (if (> b c)
b
c)))
(+ (square b)
(square (if (> a c)
a
c)))))
Here's an implementation with let. If possible I would like this reviewed as well.
(define (sum-of-squares a b c)
(let ((bc (if (> b c) b c))
(ac (if (> a c) a c)))
(if (> a b)
(+ (square a) (square bc))
(+ (square b) (square ac)))))
Now, I find this second implementation not shorter than the first, but I think it's easier to read because it can be difficult to read expressions with more expressions nested inside as with the first implementation. On the other hand I realized it's worthless to do this because the variables aren't used more than once. For expressions more complicated than expressions contained in this procedure, would it be a good idea to put them inside let even if they are only used once?
How can I improve these codes and make them faster?