Skip to content

Instantly share code, notes, and snippets.

@fayazkhan
Created September 10, 2017 08:36
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 fayazkhan/7476c7774b3a9046fa768cf51aa0ae6d to your computer and use it in GitHub Desktop.
Save fayazkhan/7476c7774b3a9046fa768cf51aa0ae6d to your computer and use it in GitHub Desktop.
Ceasar cipher challenge solution
{- Performs the Ceasar cipher encryption.
Compile this file by running:
ghc ceasar.hs
You'll need to have ghc package installed.
-}
import Data.Char
main = do
putStrLn "Enter string to encrypt:"
plainText <- getLine
putStrLn "Enter key:"
keyString <- getLine
putStrLn $ evaluateInput keyString plainText
evaluateInput keyString plainText = case reads keyString of
[(key, _)] -> "Your encrypted string:\n" ++ show (ceasar key plainText)
_ -> "Invalid key number."
ceasar key plainText = map (ceasarEncryptCharacter key) plainText
ceasarEncryptCharacter :: Int -> Char -> Char
ceasarEncryptCharacter key character
| isLower character = fromCode smallA (toCode smallA character + key)
| isAlpha character = fromCode bigA (toCode bigA character + key)
| otherwise = character
fromCode offset code = chr (mod code 26 + offset)
toCode offset character = mod (ord character - offset) 26
smallA = ord 'a'
bigA = ord 'A'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment