---
logosub: "Software"
language: "en"
title: "Caesar Cipher"
code: "Haskell"
---

The implementation of the [Caesar's Cipher](https://en.wikipedia.org/wiki/Caesar_cipher) in Haskell.

*Source*: [Programming in Haskell, by Graham Hutton](https://people.cs.nott.ac.uk/pszgmh/pih.html)

```haskell
import Data.Char
import Prelude

let2int :: Char -> Int
let2int c | isLower c = ord c - ord 'a'
          | otherwise = ord c - ord 'A'

int2let :: Int -> Bool -> Char
int2let n isLowercase = chr (ord (if isLowercase then 'a' else 'A') + n)

shift :: Int -> Char -> Char
shift n c | isLower c = int2let ((let2int c + n) `mod` 26) (isLower c)
          | isUpper c = int2let ((let2int c + n) `mod` 26) (isLower c)
          | otherwise = c

encode :: Int -> String -> String
encode n xs = [shift n x | x <- xs]


ghci> encode 5 "This is a Caesar Cipher"
-- "Ymnx nx f Hfjxfw Hnumjw"
ghci> encode (-5) "Ymnx nx f Hfjxfw Hnumjw"
-- "This is a Caesar Cipher"
```