ROT13 Example, String.map
This page was last reviewed on May 19, 2022.
Dot Net Perls
ROT13. 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.
Our solution. 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.
And For characters not in the range of uppercase or lowercase ASCII letters, it returns the value unchanged.
Tip In F# no "return" statement is needed. The return value from the if-else is specified directly after "then."
Detail We use casts in the same style as C#. We must convert to an 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" result2
Qb lbh unir nal png cvpgherf? Do you have any cat pictures?
Some concepts. 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.
However There is a complication. Performance may not be optimal with this style of code.
And Extensive benchmarking usually reveals that a C-like method, with no function calls, is the fastest transformation approach.
A review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 19, 2022 (edit).
© 2007-2024 Sam Allen.