I picked out a nice exercise from the SICP book for this second installment of my series for beginner Scheme programmers (like myself). I chose Exercise 1.3 which reads as follows:
“Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers”
My goal is to show a simple yet somewhat clever solution. My first thought on how to accomplish this is to just test all 3 possible cases. This seems like a rather bland approach however and from what I understand, LISP is supposed to be exciting
. As a result, I’m going to go with a less efficient but more readable implementation. I’m going to add the squares of all three numbers and then subtract the square of the smallest.
(- (+ (* a a) (* b b) (* c c))
(* (min a b c)(min a b c))))
Here I define a procedure called “sicp1.3″ that takes 3 arguments. I then add the squares the those 3 args and subtract the square of the smallest. If you are not able to see how this code does what I described, then checkout my earlier post.
Now, I already admitted that this is not an optimally efficient algorithm, so I better make this at least a little easier on the eyes. First by pulling out the “square of the minimum value” part to it’s own procedure. That gives us:
(* (min a b c)(min a b c)))
(define (sicp1.3 a b c)
(- (+ (* a a) (* b b) (* c c))
(sqmin a b c)))
and finally, I’d say that the “sum of squares” part should really be it’s own procedure as well
(* (min a b c)(min a b c)))
(define (sumsq a b c)
(+ (* a a) (* b b) (* c c)))
(define (sicp1.3 a b c)
(- (sumsq a b c)
(sqmin a b c)))
So thats what I’ve got. Upon looking this up on Stackoverflow I found a similar solution to the one given here, plus a number of much more sophisticated examples. Enjoy!
