module Caesar where import Data.Char import Data.Maybe alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" wtf = '¿' downGrade :: String -> String downGrade = fmap (clip . toUpper) where clip c | elem (toUpper c) alphabet = toUpper c clip ' ' = ' ' clip _ = wtf encode :: Int -> String -> String encode key msg = unwords $ encodeWord key <$> (words $ downGrade msg) decode :: Int -> String -> String decode key msg = unwords $ encodeWord k <$> (words $ msg) where k = l - (key `mod` l) l = length alphabet encodeWord :: Int -> String -> String encodeWord k = fmap (substitute $ mapping k) substitute :: [(Char,Char)] -> Char -> Char substitute m e = fromMaybe wtf $ lookup e m mapping :: Int -> [(Char,Char)] mapping k = zip alphabet (alphabet `rotateBy` k) l `rotateBy` n = take (length l) $ drop n (cycle l)