10 Minutes with Factor

Posted 2007-12-17…

Factor is a stack-oriented language, similar in that respect to Forth and Joy. I’ve played with both at one point or another, so when I recently ran across a reference to Factor in a recent interview with Zed Shaw, I thought I’d take a look. I’m always on the prowl for little esoteric languages, hoping to harvest new (or newly revised) approaches to software development.

First of all, some caveats. I don’t know much about Factor yet, and I’ve never been successful at implementing anything worthwhile in any stack-oriented language (not that I’ve tried); my strengths mainly lie along the OOP and functional fronts, and I haven’t really hit the “Aha!” moment yet with stacks. I do, however, appreciate the syntactic simplicity and extensibility of the idea, and hope to get there soon.

Let’s get started.

Installing Factor

You can grab binary and source copies of Factor from the website here. Make sure you download an image file as well if you’re building from source.

You can also clone the Factor repository using git, with the standard disclaimers on stability.

The GUI

As crazy little esoteric languages go, Factor comes well-dressed… with a relatively simple, but powerful GUI for interactive hacking, debugging, and code/documentation browsing. It completely puts irb to shame, of course; though there has been some work in this direction in Ruby, it sure would be nice if something similar would come standard with the language. I’m not a big fan of big IDEs that do enough work for you that you forget how to do things yourself, but give me a little hacking console any day.

Basic Concepts

The basic concept of stack-oriented programming centers around manipulation of one or more stacks. In Factor this manipulation is done via words (that sit in _vocabularies_), and generally a single stack is used. Let’s try a simple example using the “+” word.

1 2 + .

The first thing you might notice is that ‘+’ comes at the end. This is called Reverse Polish Notation (RPN), and though it might seem a bit weird to those of us with infix operator leanings (and backwards to PN Schemers), it makes complete sense when you’re dealing with a stack.

Let’s break the example down, bit by bit.

  1. ‘1’ is recognized as a number literal. It’s pushed onto the stack.
    • Stack looks like: 1
  2. ‘2’ is recognized as a number literal. It’s pushed onto the stack.
    • Stack looks like: 1 2
  3. ‘+’ isn’t recognized as a literal; it’s a word that’s found and executed. It pops off two items from the stack, adds them (just pretend how that happens is unimportant for the moment), and pushes the result on the stack.
    • Stack looks like: 3
  4. A single period pops off an item from the stack. Think of it as returning a value.
    • Stack is now empty