Created
September 10, 2017 08:36
-
-
Save fayazkhan/7476c7774b3a9046fa768cf51aa0ae6d to your computer and use it in GitHub Desktop.
Ceasar cipher challenge solution
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
{- 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