Thursday, May 28, 2009

Factor

Reading Hacker News lead me to the Factor language. For some reason the language's pages seem to feel the need to use a lot of fancy language, but as I understand it the gist of it is simple and beautiful: it's Forth crossed with a modern functional programming language.

Back when I was a budding programmer with a Commodore 64, Forth was a godsend. A vastly better language than old Microsoft Basic, fast, terse, and powerful. On a par with C, but with a design simple enough you could probably code a Forth system from scratch in a day or two. And it was extensible in a way more reminiscent of C++ than C.

On the other hand, it had too many shortcomings to be really viable as a general purpose language. Which is where Factor comes in. It's a stack-based language with an obvious Forth ancestry, but instead of the stack being limited to integers, you can put sequences, strings, and even anonymous functions on it. It makes the language considerably more elegant, and a bit more weird.

For instance, here's a factorial function in Forth. (From long-rusted skills, and I don't have a Forth interpreter handy to test it, so it may not be quite right. Also, I believe not all versions of Forth allowed recursive calls without additional magic.)

Note that strange if - else - then construct, which was a control structure which took a bit of magic to implement -- it takes a boolean off the top of the stack, and then jumps to either the bit after the if or the bit after the else, with both paths merging at the then.

By constrast, here's the version I just implemented in Factor.

The "( n -- n2 )" bit is a mandatory comment describing the function's inputs and outputs. (Maybe it has additional meaning I don't understand yet?) Code surrounded by brackets is an anonymous function (don't know if that's the terminology they use). So in Factor, instead of the tricky implementation of Forth's if - else - then construct, the if statement is dead simple to implement. (Seriously, it's one short line of code -- the help system actually has the code in it!) Basically it takes three things on the stack: a boolean and two anonymous functions. If the boolean is true, it executes the first anonymous function; if false, the second.

So Factor seems to embrace anonymous functions in a big way, and creating them is completely natural in it. It's a neat idea, and I look forward to playing around with it some more.

And hey, it even has a unit testing framework built in!

No comments:

Post a Comment