C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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?
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.