Thursday, November 30, 2006

rot13 in Factor

Daniel Ehrenberg implemented the rot13 algorithm in Factor. I added it to the demos/ directory; it is very simple and elegant:
IN: rot13
USING: kernel math sequences strings ;

: rotate ( ch base -- ch ) tuck - 13 + 26 mod + ;

: rot-letter ( ch -- ch )
{ [ dup letter? ] [ CHAR: a rotate ] }
{ [ dup LETTER? ] [ CHAR: A rotate ] }
{ [ t ] [ ] }
} cond ;

: rot13 ( string -- string ) [ rot-letter ] map ;


Anonymous said...

This is the Perl-version:

tr 'a-zA-Z' 'n-za-mN-ZA-M'

Much more readable, isn't it :-)

Anyhow, I liked the Factor version.

When it comes to readability - does anyone else than me miss local variables in Factor? It seems to have become a rather standard thing in most Forths?

Slava Pestov said...

Locals would defeat the purpose of Factor, in a sense. I'm trying to explore stack programming and build a complete high level stack language environment, which hasn't been done before. If I wanted locals, I may as well have built another Scheme dialect, which would be pointless since there are hundreds out there already. :-)

I don't think the Perl version is more readable, although in some sense it does express the intent better. You do have to know what 'tr' and regular expressions are to understand it, though; the Factor version only uses basic control flow and mapping over a sequence.