Skip to content

Instantly share code, notes, and snippets.

@Spationaute
Created March 6, 2018 14:09
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 Spationaute/97b0ac75ac14d4f0c220e50d7997fe52 to your computer and use it in GitHub Desktop.
Save Spationaute/97b0ac75ac14d4f0c220e50d7997fe52 to your computer and use it in GitHub Desktop.
Haskell Fun Cesar Cypher
-- import Data.List
import Data.Char
import Data.Maybe
import System.Environment
-- import System.IO
import Control.Monad
import Text.Read
-- Evaluate if a value is between two other
between :: (Ord a) => a -> a -> a -> Bool
between bottom top target = (target >= bottom) && (target <= top)
-- Do a rotation on the alphanumeric value
rotateChar :: Int -> Char -> Char
rotateChar nR input
| between 48 57 inputOrd = rotBV 48 nR inputOrd 10
| between 65 90 inputOrd = rotBV 65 nR inputOrd 25
| between 97 122 inputOrd = rotBV 97 nR inputOrd 25
| otherwise = input
where inputOrd = ord input
rotBV base value char modMax = let modOrd = mod (char-base) modMax
in chr $ base + (mod (modOrd+value) modMax)
-- Apply rotate to a string
encrypt :: Int -> String -> String
encrypt nR (inChar:[]) = rotateChar nR inChar : []
encrypt nR (inChar:tl) = rotateChar nR inChar : encrypt nR tl
main = do
args <- getArgs
if not (length args == 1)
then putStr "The program need 1 and only 1 argument.\n"
else do
let nR = readMaybe (args!!0) :: Maybe Int
if isJust nR
then interact $ encrypt $ fromJust nR
else putStr "The argument need to be an interger.\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment