Skip to content

Instantly share code, notes, and snippets.

@barisere
Created January 21, 2020 18:37
Show Gist options
  • Save barisere/4e6dda709d0619784fcd5afc6b445e44 to your computer and use it in GitHub Desktop.
Save barisere/4e6dda709d0619784fcd5afc6b445e44 to your computer and use it in GitHub Desktop.
An OCaml implementation of the core functions of the Caesar cipher. See the Python implementation at https://gist.github.com/barisere/cf57c33eb826156f6b2e6b78f6b087c6.
open Core
module type Caesar_intf = sig
val decrypt: string -> int -> string
val encrypt: string -> int -> string
end
module Caesar: Caesar_intf = struct
let transform_alpha scale c =
if not (Char.is_alpha c) then c else
let code = Char.hash c in
let scale_factor = Char.(if is_lowercase c then hash 'a' else hash 'A') in
scale (code - scale_factor) |> (+) scale_factor |> Char.of_int_exn
let encrypt plain_text shift =
String.map ~f:(transform_alpha (fun c -> (c + shift) % 26)) plain_text
let decrypt cipher_text shift =
String.map ~f:(transform_alpha (fun c -> (c - shift) % 26)) cipher_text
end
let text_param, shift_param = Command.(
Param.(anon ("text" %: string)),
Param.(anon ("shift-key" %: int))
)
let encrypt_command = Command.(
basic ~summary:"Encrypt the given text using the given shift key."
Param.(map2 text_param shift_param ~f:(fun text shift_key ->
fun () -> Stdio.print_endline (Caesar.encrypt text shift_key)))
)
let decrypt_command = Command.(
basic ~summary:"Decrypt the given text using the given shift key."
Param.(map2 text_param shift_param ~f:(fun text shift_key ->
fun () -> Stdio.print_endline (Caesar.decrypt text shift_key)))
)
let command = Command.(
group ~summary:"Cryptography using the Caesar shift substitution cipher."
[("encrypt", encrypt_command); ("decrypt", decrypt_command)]
)
let () = Command.run command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment