F# Zen - ROT13

Below is a primitive implementation of ROT13 / Ceasar Cipher in F#. In short it is a simple encryption algorithm that works by 'shifting' each letter 13 places. So an 'a' becomes an 'n', a 'b' becomes an 'o', and so on. To decrypt the text you simply move 13 places in reverse.

We can do this in F# easily using function composition. Given a string, which is also a sequence of characters, we pass it to Array.of_seq so we have an array of characters. This will enable us to replace each character with its encrypted version. Next we map each character to our encryption function, which I'll go over next. Finally, we take our array of encrypted characters and return a new string.

To actually do the encryption, we will compose three functions together. int, will convert the character to its integer representation. "(+) 13" is a curried version of the (+) function, so it adds 13 to its argument. And then we compose that with the char function, which will convert the integer result to a character.

#light

(**
* ROT13 in F#
*
* 1. Convert the sequence of chars (string) to an array of chars
* 2. For each character do the following:
*    - Convert the character to an integer
*    - Add 13 to the integer value of the character (by currying (+))
*    - Convert the integer to a character
* 3. Create a new string based off the encrypted characters
*)

let EncryptText (text : string) =
text
|> Array.of_seq
|> Array.map (int >> ((+) 13) >> char)
|> (fun chars -> new string(chars))

let DecryptText (text : string) =
text
|> Array.of_seq
|> Array.map (int >> ((+) -13) >> char)
|> (fun chars -> new string(chars))

let Test message =
let encrypted = EncryptText message
let decrypted = DecryptText encrypted

printfn "Original Message  = %s" message
printfn "Encrypted Message = %s" encrypted
printfn "Decrypted Message = %s" decrypted

Test "The quick fox jumped over the lazy dog"