Thursday, October 04, 2007

Reading SICP in Factor: Section 1.1.4

Here’s my cut at SICP 1.1.4 in Factor. I’m a lot less sure of this than I am of the Ruby translation since I’m learning Factor as I go along. I’d appreciate comments from the Factor community as I go along, especially about Factor idioms.

In my Ruby translation, I failed to talk about some things, like procedures in SICP being methods in Ruby, and changing the method names to match the snake_case style favored by Rubyists. In the factor translation, procedures would be referred to as words, but I’ll be keeping the lispy-lowercase-divided-by-hyphens look.

There’s already a sq word in Factor, and I based my definition on that one.


> : square dup * ;
> 5 square .
25

The first line defines the word square and the second line tests it by excution. Lets see if I can explain the second line:

word or literal stack explanation
5 5 puts 5 on the stack
square 5 (I’ll explain this below)
dup 5 5 duplicates the top value on the stack
* 25 multiplies the top two values on the stack and replaces them with the result
. {} returns and removes prettyprints (and consumes) the top value on the stack

To create1 and execute the sum-of-squares word we can do the following:


> : sum-of-squares ( a b -- c ) square swap square + ;
> 3 4 sum-of-squares .
25

Again, my attempt at explaining the second line:

word or literal stack explanation
3 3 put 3 on the stack
4 3 4 puts 4 on the stack
sum-of-squares 3 4 (explained below)
square 3 16 squares the top value on the stack
swap 16 3 swaps the top two values on the stack
sqare 16 9 squares the top value on the stack
+ 25 adds the top two values on the stack and replaces them with the result
. {} returns and removes prettyprints (and consumes) the top value of the stack

(By the way, big thanks to Wilson Bilkovich for his editorial work on this post … he improved it immensely.)

1 In trying to create sum-of-squares, I ran into an initial problem understanding word definition. Thanks to gnomon in #concatenative for his help in straightening me out. Further updates are a result of the kind folks on #concatenative reading this and correcting me.

No comments: