Skip to content

Instantly share code, notes, and snippets.

@remi6397
Created February 22, 2018 12:02
Show Gist options
  • Save remi6397/e975369eca0460401dbfaae33e87d2bf to your computer and use it in GitHub Desktop.
Save remi6397/e975369eca0460401dbfaae33e87d2bf to your computer and use it in GitHub Desktop.
module SubstitutionCipher where
import Data.List
import Data.Maybe
chunkify :: Int -> [a] -> [[a]]
chunkify _ [] = []
chunkify n xs = hd : chunkify n tl
where
(hd, tl) = splitAt n xs
-- | Substitution cipher
-- Example: "abcdefghij" x "haskell" -> "gbskfll"
cipher :: String -> String -> String
cipher key text = map recode text
where
recode c = altChar c $ find (elem c) keyChunks
altChar c (Just pair) = fromMaybe c $ find (/= c) pair
altChar c _ = c
keyChunks = chunkify 2 key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment