Function Pipelines and Caesar’s Code in Elm

The Idea

The idea behind Caesar’s code is simple: Take a message like HELLO and shift the characters forward by k units in the alphabet — or, better, in the characters as laid out in the ASCII code. Thus, if k = 1, then the encrypted message is IFMMP. If k = 2, then the encrypted message is JGNNQ. Etc. Decryption is simple: shift by -k. Decryption is just encryption with a different key.

  1. The second letter of the key is B, so shift the P of APPLE one place to Q.
  2. The third letter of the key is C, so shift the next P of APPLE two places to R.
  3. Etc.

Elm code

Here we discuss only the simple Caesar method, with the one-time pad version left as an exercise. The full Elm code is displayed in module Encrypt below. It has just five function definitions. Let’s go through them one at a time. First is a function which converts strings into lists of integers.

string2ascii message =
message
|> String.toList
|> List.map Char.toCode
> string2ascii "HELLO"
[72,69,76,76,79] : List Char.KeyCode

Aside

Notice that we are using the “forward pipe operator” to make function composition easier to read. As an example, consider the function double x = 2*x. To double the number 1 three times, we could write

(double (double (double 1)))
1 |> double |> double |> double
> double x = 2*x
<function> : number -> number
> 1 |> double |> double |> double
8 : number
Function Pipeline

Continuing with the code

Back to theEncryptmodule. The function ascii2string is the inverse of string2ascii. Thus,

> ascii2string [72,69,76,76,79]
"HELLO" : String
nums |> List.map Char.fromCode |> String.fromList
> List.map (add 2) [1,2,3,4]
[3,4,5,6] : List number
encrypt k str =
str
|> String.toUpper
|> string2ascii
|> List.map (add k)
|> ascii2string
decrypt k str = encrypt -k str

module Encrypt

module Encrypt exposing (..)import Charstring2ascii message =
message
|> String.toList
|> List.map Char.toCode
ascii2string nums =
nums
|> List.map Char.fromCode
|> String.fromList
add x y =
x + y
encrypt k str =
str |> String.toUpper |> string2ascii |> List.map (add k) |> ascii2string
decrypt k str =
encrypt -k str

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store