Saturday, January 6, 2007

First Steps with Factor

Today I did my first steps in Factor a stackbased programming language developed mainly by Slava Pestov. This guy must be a bloody genius!! Factor's development environment is great because it is very interactive. I never had the chance to get access to a Lisp Symbolics box but Factor must come very close to it. Slava wants to make Factor the best stackbased programming language. Hey, Slava, you already did!

So I played around with it and wrote the Hello programs of the Lisp world: factorial and fibonacci. Here we go:



: factorial ( n -- n! )
dup 1 <=
[ dup 1 - factorial * ] unless ;

: fibonacci ( n -- fib-n )
dup 1 <=
[ dup 1 - fibonacci swap 2 - fibonacci + ] unless ;



Looks strange and bizarr. But once you get the hang of it you never wanna stop.

I wrote the Factor code in Emacs. There is a factor mode file in the Factor distribution. The factor-listener function is broken (telnet function is not available any more in the latest release 0.87). But there is so much interactivity in the Factor listener that you don't need Emacs for it.

So these are the steps you have to do for Emacs integration:
1.) Add the following lines to your .emacs file:

(load-file "path-to/Factor/libs/factor.el")
(server-start)


2.) In Factor load the Emacs library from the listener

"libs/emacs" require


That's it. When you want to edit code press 'C+e' in Factor, choose the file from the pop-up, switch to your Emacs session and happy factoring.

Helpful functions in the listener:

  • see, e.g "\ dup see" to see definition of duplicate
  • help, e.g. "\ dup help" to get online help for duplicate
  • where, e.g. "\ send-button-up where" to see in which file the word (Factor term for a function) 'send-button-up' is defined
  • edit, e.g. "\ send-button-up edit" opens file where 'send-button-up' is defined and jumps to the appropriate line


Thank you, Slava!!!

1 Kommentare:

Corentin Plouët said...

Your factorial function is buggy: it doesn't work for the value zero.

Here's a working version:

: factorial ( n -- n! ) dup 0 = [ drop 1 ] [ dup 1 - factorial * ] if ;