“Programming-language related pun” print

Factor is a fun language. It’s postfix, making your code look like mirror-image LISP (or, RPN, which of course is what it is), and for the most part, all the data (and functions, etc) are all on a single stack at once.

An example, which finds the answer to Project Euler problem 5:

USING: math kernel math.ranges sequences ;
 
: gcd ( x y -- z ) dup 0 = [ drop ] [ swap over mod gcd ] if ;
 
: lcm ( x y -- z ) 2dup gcd / * ;
 
: answer ( -- n ) 2 20 [a,b] 1 [ lcm ] reduce ;

Take the gcd function. It looks at the top of the stack, and if it’s equal to zero, deletes it. We have to duplicate it before checking, because = (and < and friends) replace the top two elements with t/f, and we may want to keep it around. If it’s not equal to zero, we swap the top elements, copy the second one over to the top, find the modulus of the top two, and recurse. So it’s basically the Euclidean algorithm in RPN.

Isn’t it funny-looking? The spaces around the brackets and (semi)colons are necessary; the tokens are separated by whitespace but otherwise can contain any character. Like in the above, [a,b] is all one word, a function which makes a range (or interval if you use the one in math.intervals, of course) from the top two stack elements.

For bonus points, it supports functional programming; the blobs in square brackets are ‘quotations’, which are just pushed on the stack as they are to maybe be called later. We need to do this for if, because only one of them is ever used. Similarly for while the quotations (one for the condition, one for the body) are called repeatedly.

A pity my syntax highlighting doesn’t support it. :(

edit: Euclidean algorithm fixed.

Leave a Reply

You must be logged in to post a comment.