liveBook · Manning

Caesar cipher

As explained in Learn Haskell by Example

A Caesar cipher is a substitution cipher that replaces each letter with another letter a fixed distance away in an ordered alphabet.

A Caesar cipher is a substitution cipher that shifts every letter by a fixed offset in an ordered alphabet. The offset acts as the key: encryption moves letters forward, while decryption reverses the rotation. It demonstrates practical functional-programming techniques, but it is not suitable for protecting real data. section 2.1 section 2.1.1

Figure 2.1 Letter substitution wheel
figure

A substitution wheel makes the circular alphabet and fixed-offset rotation visible: letters wrap from the end back to the beginning. section 2.1.1

A Haskell implementation can be built incrementally:

  • Represent the offset with Int and messages with String. section 2.3
  • Define alphabets for lowercase letters, uppercase letters, and digits, then identify which alphabet contains each Char. section 2.5.3
  • Rotate a character within its alphabet, wrapping around when the offset passes an endpoint. section 2.1.1 section 2.5.3
  • Transform a String by applying the character rotation to every element and constructing a new immutable list. section 2.5
  • Generalize the traversal with map; define ROT13 as Caesar rotation by 13. section 2.5.3

ROT13 in GHCi

caesar 13 "Caesars Cipher!" produces "Pnrfnef Pvcure!". Applying the same transformation again restores the original message, because ROT13 is its own inverse. A combined ROT13.5 variant can also rotate letters by 13 and digits by 5. section 2.5 section 2.5.3

Frequency analysis exposes the cipher's weakness: counting character occurrences in plain and transformed text can support a best-guess decryption. This makes Caesar cipher useful as a programming exercise, not as secure encryption. section 2.5.3

How Learn Haskell by Example covers it

How deep it goes
Works from alphabet rotation through character helpers, recursion, map, symmetry, and frequency analysis, while stopping short of secure cryptography.
Examples
Uses substitution wheels, ROT13 messages, digit rotations, GHCi evaluations, and frequency-analysis exercises.
What you can do after
Build a Caesar cipher in Haskell, test reversible rotations, and investigate weak encryption with frequency counts.
How it connects
Connects substitution ciphers with ROT13, immutable data, recursion, pattern matching, map, type synonyms, and frequency analysis.

Also explained in

Compare how 2 books explain Caesar cipher →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.