Skip to content

Instantly share code, notes, and snippets.

@jcottrell
Created July 10, 2019 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcottrell/2eece79dc2160e65b6f5154325b256b8 to your computer and use it in GitHub Desktop.
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!`
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