Monday, December 25, 2006

Still more ROT13

This is the last post on ROT13, I promise. The shortest version in F# is a low-level one, working with character codes. This is the most obvious solution to C programmers, and I considered it from the start, but I feel it loses something from the other versions. We have to "break" the abstraction of characters and think about their representation, and this lowers the level we are working. Here it is:

#light

let strmap f (s : string) =
let sb = new System.Text.StringBuilder(s)
let rec aux i =
if i = sb.Length then () else
(sb.Chars(i) <- f (sb.Chars(i)) ; aux (i + 1))
( aux 0; sb.ToString() )

// still another one
let rot13 s =
strmap
(fun c -> Char.chr ((((Char.code c) - 97 + 13) mod 26) + 97))
s

I should probably substitute Char.code 'a' for 97 there, and this would work as long as the encoding guaranteed that letters a to z were assigned contiguous codes, which I believe is valid in most or all current text encodings. Still, we have to think about text encodings and character representations. And we still need a function to map over strings.

No comments: