hs-caesar/src/Caesar.hs

36 lines
833 B
Haskell
Raw Normal View History

2019-07-18 23:17:42 +02:00
module Caesar where
import Data.Char
import Data.Maybe
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2019-07-19 17:56:37 +02:00
wtf = '¿'
2019-07-18 23:17:42 +02:00
downGrade :: String -> String
downGrade = fmap (clip . toUpper)
where
clip c | elem (toUpper c) alphabet = toUpper c
clip ' ' = ' '
2019-07-19 17:56:37 +02:00
clip _ = wtf
2019-07-18 23:17:42 +02:00
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
2019-07-19 17:56:37 +02:00
substitute m e = fromMaybe wtf $ lookup e m
2019-07-18 23:17:42 +02:00
mapping :: Int -> [(Char,Char)]
mapping k = zip alphabet (alphabet `rotateBy` k)
l `rotateBy` n = take (length l) $ drop n (cycle l)