HomeSearch

F# ROT13 Cipher (String.map)

Use the String.map function to implement the ROT13 cipher. Rotate characters 13 places.
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.
A helpful function. 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."

Casts: We use casts in the same style as C#. We must convert to an int before subtracting or adding 13.

F# program that uses String.map with rot13 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 Output 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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.