Last active
July 5, 2017 18:32
-
-
Save bbuck/e4e52a46c24778367fa0d5563ee82ad7 to your computer and use it in GitHub Desktop.
Caeser cipher written as part of a Chapter 9 challenge in the Haskell Book: http://haskellbook.com/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Cipher where | |
import Data.Char | |
clampAlpha :: (Integral a) => a -> a | |
clampAlpha = (`mod` 26) | |
lowerBound :: Char -> Char | |
lowerBound c | |
| isUpper c = 'A' | |
| isLower c = 'a' | |
| otherwise = undefined | |
caesarShift :: Int -> Char -> Char | |
caesarShift i c | |
| not (isAlpha c) = c | |
| otherwise = chr (clampped + baseN) | |
where base = lowerBound c | |
baseN = ord base | |
n = ord c - baseN + i | |
clampped = clampAlpha n | |
caesar :: Int -> String -> String | |
caesar shift = map (caesarShift shift) | |
unCaesar :: Int -> String -> String | |
unCaesar shift = map (caesarShift (-shift)) | |
rot13 :: String -> String | |
rot13 = caesar 13 | |
unRot13 :: String -> String | |
unRot13 = unCaesar 13 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment