hs-caesar/src/Caesar.hs

35 lines
822 B
Haskell

module Caesar where
import Data.Char
import Data.Maybe
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
downGrade :: String -> String
downGrade = fmap (clip . toUpper)
where
clip c | elem (toUpper c) alphabet = toUpper c
clip ' ' = ' '
clip _ = '_'
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 '_' $ lookup e m
mapping :: Int -> [(Char,Char)]
mapping k = zip alphabet (alphabet `rotateBy` k)
l `rotateBy` n = take (length l) $ drop n (cycle l)