Skip to content

Instantly share code, notes, and snippets.

@neevek
Created March 25, 2018 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neevek/7e74ef2c5e78ca5e4bf331865ac26d2f to your computer and use it in GitHub Desktop.
Save neevek/7e74ef2c5e78ca5e4bf331865ac26d2f to your computer and use it in GitHub Desktop.
CaesarCipher
import Data.Char
data CaesarCipherShift = CipherShift Int
caesarEncode :: CaesarCipherShift -> String -> String
caesarEncode _ [] = []
caesarEncode (CipherShift shiftCount) (x:xs)
| shiftedOrd > printableMax =
(chr $ ((shiftedOrd - 1 - printableMin) `mod` printableRange) + printableMin) :
(caesarEncode (CipherShift shiftCount) xs)
| shiftedOrd < 0 =
(chr $ printableMax + ((shiftedOrd + 1) `rem` printableMax)) :
(caesarEncode (CipherShift shiftCount) xs)
| shiftedOrd < printableMin =
(chr $ ((shiftedOrd + 1) `mod` printableRange) + printableRange) :
(caesarEncode (CipherShift shiftCount) xs)
| otherwise = chr shiftedOrd : (caesarEncode (CipherShift shiftCount) xs)
where
printableMin = 0x20
printableMax = 0x7e
printableRange = printableMax - printableMin
shiftedOrd = ord x + shiftCount
caesarDecode :: CaesarCipherShift -> String -> String
caesarDecode (CipherShift shiftCount) xs =
caesarEncode (CipherShift (negate shiftCount)) xs
@neevek
Copy link
Author

neevek commented Mar 25, 2018

Usage:

-- use negative CipherShift to shift left, and positive to shift right
caesarDecode (CipherShift 13) . caesarEncode (CipherShift 13) $ "Hello World"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment