Wednesday, October 03, 2007

Reading SICP in Ruby: 1.1.4

Recently, I posted about reading and working through SICP in languages other than scheme. Today is the day that I start. I don’t know how quickly I’ll work through things, but we’ll see what I can do. In addition to Ruby, I’m also hoping to work with Factor and Erlang in parallel.

My first SICP post is nice and easy, I’m skipping up to Section 1.1.4 of SICP which covers compound procedures (procedures made up of other procedures). This is really the heart of concatenative programming (like forth and factor) and of the style of short method OO espoused be Martin Fowler in Refactoring.

Sussman starts out by defining a procedure to square a number, then another that uses the new square procedure to create a sum-of-squares procdure. In Ruby, this would look something like this:

def square(num)
  num * num
end
def sum_of_squares(num1, num2)
  square(num1) + square(num2)
end

If I type these definitions into irb and then try running them, I get the following:


 sum_of_squares(3,4)
 => 25
 sum_of_squares(3.0,4.0)
 => 25.0
 sum_of_squares(3.0,4)
 => 25.0
Just what you’d expect.

Next up, section 1.1.6 (Conditional Expressions and Predicates)

No comments: