With this cipher, we shift letters forward or backward 13 places in the alphabet. ROT13 obscures text. It does not encrypt it. This algorithm is implemented with some simple logic.
To implement ROT13 in F# we can use the String.map
function. We specify a rot13
function to pass to String.map
. This must receive a char
and return its mapped version.
Here we introduce the rot13
function, which accepts a single character and returns a char
. It handles lowercase letters and uppercase letters in separate blocks.
if-else
is specified directly after "then."int
before subtracting or adding 13.let rot13 c = // Shift char value 13 places based on logic. if c >= 'a' && c <= 'z' then if c >= 'm' then (char)((int)c - 13) else (char)((int)c + 13) elif c >= 'A' && c <= 'Z' then if c >= 'M' then (char)((int)c - 13) else (char)((int)c + 13) else c let test = "Do you have any cat pictures?" // Apply map to string. let result1 = String.map rot13 test printfn "%s" result1 // Call map again to reverse the transformation. let result2 = String.map rot13 result1 printfn "%s" result2Qb lbh unir nal png cvpgherf? Do you have any cat pictures?
Typically the clearest way to implement ROT13 in languages is with a method like String.map
. Then a char
transformation function specifies how each char
is mapped.
ROT13 is rarely used in serious programs (although it has its place). By implementing ROT13 we can learn how to modify chars in strings based on their values.