Sha256: e28b0c0c433bdfcdcb57b09a231e69b3789cb41d4beab9af8dad3c92f304f23b

Contents?: true

Size: 784 Bytes

Versions: 396

Compression:

Stored size: 784 Bytes

Contents

module Cipher (caesarEncode, caesarDecode, caesarEncodeRandom) where

import Data.Char     (isAsciiLower)
import System.Random (newStdGen, randomRs)

caesarEncode, caesarDecode :: String -> String -> String
caesarEncode = caesar (+)
caesarDecode = caesar (-)

caesarEncodeRandom :: String -> IO (String, String)
caesarEncodeRandom xs = do
  g <- newStdGen
  let ks = take (length xs) (randomRs ('a', 'z') g)
  return (ks, caesarEncode ks xs)

caesar :: (Int -> Int -> Int) -> String -> String -> String
caesar op = zipWith rotate . cycle
  where
    rotate k x = if isAsciiLower k && isAsciiLower x
                then toAlpha (op (fromAlpha x) (fromAlpha k) `mod` 26)
                else x
    fromAlpha = subtract (fromEnum 'a') . fromEnum
    toAlpha = toEnum . (fromEnum 'a' +)

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.179 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.178 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.177 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.176 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.175 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.174 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.173 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.172 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.171 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.170 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.169 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.167 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.166 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.165 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.164 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.163 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.162 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.161 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs
trackler-2.2.1.160 tracks/haskell/exercises/simple-cipher/examples/success-standard/src/Cipher.hs