Rot13 (Forth)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Forth | Haskell | Java | Python | Scheme | Sed

Simple

: r13 ( c -- o )
  dup 32 or                             \ tolower
  dup [char] a [char] z 1+ within if
    [char] m > if -13 else 13 then +
  else drop then ;

Table based

This implementation of rot13 constructs a translation table which maps 8-bit characters to 8-bit characters. This moves the logic of the translation from run-time to compile time.

xlate is a defining word for a table which does a character lookup (+ c@) when invoked. xlate rot13 and the following lines create the specific table for the rot13 mapping.

,chars is a utility for laying down a run of consecutive characters in the dictionary.

rot13-string applies the rot13 character transform to a string, modifying it in-place.

<<rot13 characters and strings>>=
: xlate create does> ( c -- c' ) + c@ ;
: ,chars ( end start -- ) do i c, loop ;
xlate rot13
  char A         0    ,chars
  char Z 1+ char N    ,chars
  char N    char A    ,chars
  char a    char Z 1+ ,chars
  char z 1+ char n    ,chars
  char n    char a    ,chars
     256    char z 1+ ,chars
: rot13-string ( addr len -- )
  over + swap do i c@ rot13 i c! loop ;

.rot13" is a front-end to rot13-string which makes use on the Forth command line more convenient.

<<rot13 a parsed string>>=
: .rot13" ( string" -- )
  [char] " parse 2dup rot13-string type ;
.rot13" abjurer NOWHERE"   \ nowhere ABJURER

rot13-file will apply the rot13 transform to the contents of a file. The begin...while...repeat loop is the typical wrapper for doing something to each line of a file. pad is the built-in scratch buffer.

<<rot13 a file>>=
: rot13-file ( file -- )
  begin dup pad 256 rot read-line throw while
        pad over rot13-string
        pad swap type cr
  repeat 2drop ;
\ Examples:
\ s" foo" r/o open-file throw rot13-file
\ stdin rot13-file
<<rot13.f>>=
rot13 characters and strings
rot13 a parsed string
rot13 a file
Download code
Views