Showing posts with label Factor. Show all posts
Showing posts with label Factor. Show all posts

Tuesday, October 16, 2007

SICP 1.1.7 (Factor)

I’m going back to the idea of treating each langauge in a separate post. Hopefully this will make the comments a bit more manageable (especially since I cross posted the last one onto my erlang blog as well).

Housekeeping

There were several factor related comments on the last post that I wanted to address before I moved on to section 1.1.7.

Anonymous Is Factor “done”? Seems like it’s still very much a work in progress.

Can you comment on your choice of Factor and what has made it enjoyable for you?

Anonymous is right, Factor isn’t done yet. It is getting close though, and for what I’m doing, it seems to be “done enough”. I’m using it because I’ve been thinking about learning a stack based language for a while, just to learn to think a little bit differently. So far, it’s fun because it’s doing just that.

And the related:

Ed Borasky Factor? What does Factor have that Forth doesn’t have? At least Forth has an ANS standard and some vendors and a few thousand person-decades of programmer experience.

Ed, I think the big thing that drew me to Factor over Forth was an active Factor community that I sort of tripped over. Sometimes, it’s the squeaky wheel that draws a user.

The last two weren’t specifically related to Factor, but did show better ways of solving exercise 1.3 (without resorting to lists), so I worked up a factor solution in their vein:


: min ( a b -- a b ) 2dup <
  [ swap ] when ;
: top-two ( a b c -- d e ) min rot min -rot ;
: sum-of-squares ( a b -- c ) sq swap sq + ;
: sum-squares-of-larger ( x,y,z -- x ) top-two sum-of-squares ;

I agree that this is a much better way of solving the problem.

SICP 1.1.7

Okay, on to some code. I’m going to use the built-in sq and abs words from now on. There’s no sense in continuing to use mine when there’s a perfectly good version of the word already there. SICP built a series of procedures to find square roots using Newton’s method: sqrt, sqrt-iter, improve, average, and good-enough?. I rewrote these into the following Factor:


: average ( a b  -- c ) + 2 /f ;
: improve-guess ( num guess -- guess ) dup swapd /f average ;
: good-enough? ( num guess -- ? ) sq - abs 0.001 < ;
: sqrt-iter ( num guess -- guess ) 
  2dup good-enough? 
  [ ]
  [ swap dup swapd swap improve-guess sqrt-iter ] if ;
: sqrt ( num -- root ) 1.0 sqrt-iter ;

These are nice and fairly concise, but sqrt-iter seems pretty ugly. I checked back in with the good folks on #concatenative (who have been immensely helpful) and they agreed, saying “swap dup swapd swap is a code smell”. They pointed out the dupd word, which does the same thing. so a better version of sqrt-iter would be:

: sqrt-iter ( num guess -- guess )
   2dup good-enough? 
   [ ]
   [ dupd improve-guess sqrt-iter ] if ;

Which can be improved still further into:


: sqrt-iter ( num guess -- guess )
   2dup good-enough? 
   [ dupd improve-guess sqrt-iter ] unless ;

I’m sure there are ways this could be improved yet further. Leave me a comment with your ideas. I’ll try to post my Ruby version tomorrow and Erlang on Thursday.

Monday, October 08, 2007

Reading SICP 1.1.6

This time around, I’ve decided to toss the translations for Ruby, Factor, and Erlang into the same post instead of trying to juggle multiple posts and point them all at one another. So, without further ado …

Section 1.1.6

Let’s take a look at section 1.1.6, the goal of this section is to look at conditional expressions through implementing an absolute value procedure. the book iterates through a couple of versions, trimming away fat. In each of my examples below, I’ve only shown the final product.

In Ruby, the code should look something like this:


def abs(num)   
  if num < 0
    num = -num
  end
  return num
end

In Factor it looks like this:


: abs ( n -- n ) dup 0 < [ -1 * ] [ ] if ;

And in Erlang it looks like this (I’ve left out the administrative bits from the top of the file):


abs(A) ->
    case ( A < 0) of
    true -> -1 * A;
    false -> A
    end.

Exercise 1.3

Esercise 1.3 asks the reader to write a procedure that takes three numbers and returns the sum of the squares of the largest two of them. In each case below, I rely on the previously defined square and sum-of-squares (sum_of_squares) procedures.

Ruby was pretty easy:


def sum_squares_of_larger(a, b, c)
  sorted_nums = [a, b, c].sort.reverse
  sum_of_squares(sorted_nums[0], sorted_nums[1])
end

Factor took me a while to figure out (mostly in trying to figure out how to build the array):


: top-two ( x,y,z -- x,y ) 3array natural-sort reverse first2 ;
: sum-squares-of-larger ( x,y,z -- x ) top-two sum-of-squares ;

I’m least sure of my Erlang code. I couldn’t find a good function for sorting the array, so I borrowed the qsort function from Programming Erlang. In any case, here’s my cut at it:


qsort([]) ->
     [];
qsort([Pivot|T]) ->
    qsort([X || X <- T, X < Pivot])
    ++ [Pivot] ++
    qsort([X || X <- T, X >= Pivot]).

last_two([H|T]) -> 
    T.

sum_of_squares_of_list(L) ->
    lists:sum([square(A) || A <- L]). 

sum_squares_of_larger(A, B, C) ->
    sum_of_squares_of_list(last_two(qsort([A,B,C]))).

What I learned

The biggest thing I’ve taken away from this exercise so far is that I really need a good Factor book that covers both the language and the vocabulary. Along similar lines, Programming Erlang is a good book, but it could have spent some more time on basic programming (especially covering the provided functions in something other than an appendix).

Factor has been the language that’s been hardest to wrap my mind around so far. At the same time, it’s the one that I’ve enjoyed the most—I also think the word definitions have a sort of terse beauty. I think Ruby is probably the one that most programmers could just pick up and maintain though.

Next up, Section 1.1.7 “Square Roots By Newton’s Method”.

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.