Rot13 (Scheme)

From LiteratePrograms

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

This code makes heavy use on the comparison of characters with respect to their position in the code table, namely, the functions char-ci<=? and char-ci>=?

Bug: Only works on small letters.

If the character is not within the range of a-z, return the character unaffected, otherwise rotate.

(define (char-rot13 c)
  (if c in the range from a to z?
      if c is after m, deduct 13 positions, otherwise add 13
<<c in the range from a to z?>>=
(and (char-ci>=? c #\a) (char-ci<=? c #\z))

In order to rotate, we must convert c to an integer, and convert the result back to character. Note the usage of if to select the operator + or -: The if expression will evaluate to + or - before its result will be applied to the arguments.

<<if c is after m, deduct 13 positions, otherwise add 13>>=
(integer->char ((if (char-ci<=? c #\m) + -) (char->integer c) 13))

Converting a string can be reduced to converting its characters. We have to convert to list and back though, as "map" only works on lists.

(define (string-rot13 s)
  (list->string (map char-rot13 (string->list s))))
Download code