Created
July 10, 2019 21:39
-
-
Save jcottrell/2eece79dc2160e65b6f5154325b256b8 to your computer and use it in GitHub Desktop.
Practicing haskell with a short encoding problem to help me create alphabet shifts for my children. Loaded into ghci you would do `encode 1 "Welcome to spy class!"` and get `23-5-12-3-15-13-5 20-15 19-16-25 3-12-1-19-19!`
This file contains hidden or 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
module Encode (encode) where | |
import Data.Char (isAlpha, isDigit, isUpper, toLower) | |
switchChar :: Int -> Char -> String | |
-- needs to wrap around if shift is greater than alphabet ?? | |
switchChar shift x = | |
show | |
$ head | |
$ map snd | |
$ filter ((== toLower x).fst) | |
$ zip ['a'..'z'] [shift..] | |
encodeSingle :: Int -> Char -> String | |
encodeSingle shift x | |
| isAlpha x = switchChar shift x ++ "-" | |
| otherwise = [x] | |
trimEnds :: String -> String | |
trimEnds = reverse . trimDashes . reverse | |
trimDashes :: String -> String | |
trimDashes xs | |
| null xs = "" | |
| length xs == 1 = xs | |
| not (isDigit (head xs)) && head (tail xs) == '-' = head xs : trimDashes (tail (tail xs)) | |
| otherwise = head xs : trimDashes (tail xs) | |
encode :: Int -> String -> String | |
encode shift plain = trimEnds (encodeSingle shift =<< plain) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment