I'm trying to learn scheme via SICP. Exercise 1.3 reads as follow: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. Please comment on how I can improve my solution.
(define (big x y)
(if (> x y) x y))
(define (p a b c)
(cond ((> a b) (+ (square a) (square (big b c))))
(else (+ (square b) (square (big a c))))))
big
is calledmax
. Use standard library functionality when it's there.My approach is different. Rather than lots of tests, I simply add the squares of all three, then subtract the square of the smallest one.
Whether you prefer this approach, or a bunch of
if
tests, is up to you, of course.Alternative implementation using SRFI 95:
As above, but as a one-liner (thanks synx @ freenode #scheme); also requires SRFI 1 and SRFI 26:
What about something like this?
You can also sort the list and add the squares of the first and second element of the sorted list: