I wrote a variation of the Caeser Cipher and would like some feedback. Is it idiomatic? Can you generally see anything that can be improved?
Use example:
let e = enc "Hello World" "This is the key"
in dec e "This is the key"
Instead of taking a single value as the offset, it takes a String
as the key and uses each respective character from the key as the offset; wrapping when it reaches the upper/lower bound.
module Encryption where
import Data.Char
type Key = String
type Message = String
type Direction = (Int -> Int -> Int)
--Upper and lower ascii code bounds
upperBound = 127 ; lowerBound = 32
shift :: Char -> Char -> (Int -> Int -> Int) -> Char
shift char charoff dir = fix $ dir (ord char) (ord charoff)
fix :: Int -> Char
fix charcode
| charcode > upperBound = chr $ (lowerBound - 1) + excessOf (upperBound + lowerBound)
| charcode < lowerBound = chr $ (upperBound + 1) - excessOf (lowerBound - lowerBound)
| otherwise = chr charcode
where excessOf boundry = abs(boundry - charcode)
alter :: Message -> Key -> (Int -> Int -> Int) -> Message
alter msg key dir = [(shift c k dir) | (c,k) <- zip msg (cycle key)]
enc msg key = alter msg key (+)
dec msg key = alter msg key (-)
--Basic Caeser Cipher
{-
alter :: Message -> Key -> Direction -> Message
alter m k dir = [chr $ dir (ord out) k | out <- m]
enc m k = alter m k (+)
dec m k = alter m k (-)
-}