Friday, March 20, 2009

SICP Problems

Hello All~

Off late besides playing around with Haskell, I started reading the classic "Structured Interpretation Of Computer Programs".
I have been working with Scheme for a week now and am blown away by the intuitiveness and simplicity of the language.

What I don't really understand, is that why don't more people use languages like Haskell and Scheme. It more fun and productive, I guess it's got something to do with the guys that sponsor the popular languages. Sun and IBM for Java, C# for Microsoft.

Anyway's here's a problem from SICP that I was working on yesterday. Thought of sharing the Scheme solution with all.

Problem: Define a procedure that takes three numbers as arguments and returns the sum of sqaures of 2 larger numbers.

#| Function to find the min value |#
(define (mins x y)
(if (> x y) y x))
#| Function to find max value |#
(define (maxs x y)
(if (> x y) x y))

; Function to find the square of a number
(define (square x) (* x x))

;Function to find the sum of sqaure
(define (sum-of-square x y) (+ (square x) (square y)))

#|
The logic we apply to find the 2 larger numbers out of 3 numbers is as follows.
suppose the 3 numbers are a b and c.
Firstly we find the greater number between a and b, using the maxs function that
we have already defined. Now we find the mins(a b) and the number genrated from this
is compared with c using the maxs.

Let us take an example.

sum-of-square-2-greatest 30 20 10

Here a=30, b=20 and c=10

maxs (a b) = 30

d=mins (a b) = 20

max (d, 10) = 20

Hence we will find the sum-of-square of these 2 numbers.

|#

(define (sum-of-square-2-greatest a b c)
(sum-of-square (maxs a b) (maxs (mins a b) c))
)

1 comment:

weima said...

it is even more interesting to generalize it for more than 3 variables... and find a generic solution... :)

(sum-of-square-2-greatest 10 20 30)
(sum-of-square-2-greatest 10 20 30 40)
(sum-of-square-2-greatest 10 20 30 40 50)
(sum-of-square-2-greatest 10 20 30 40 50 60 ...)