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" result2Qb 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 19, 2022 (edit).