Bacon cipher: Difference between revisions
→{{header|Haskell}}: Applied hlint, hindent, inlined comments, added main.
(→{{header|Haskell}}: Applied hlint, hindent, inlined comments, added main.) |
|||
Line 938:
=={{header|Haskell}}==
<lang haskell>-- Necessary imports
import Data.
import Data.
import Data.List.Split (chunksOf)
-- The list of characters to be encoded:
chars :: String
bitsPerChar = 6 :: Int</lang>▼
Some simple helper functions:▼
bitsPerChar = 6
<lang Haskell>toBinary :: Int -> [Bool]▼
toBinary = unfoldr (pure . (\(a,b)->(odd b,a)) . (`divMod` 2))▼
▲-- Some simple helper functions:
▲toBinary = unfoldr (pure . (\(a, b) -> (odd b, a)) . (`divMod` 2))
fromBinary :: [Bool] -> Int
fromBinary = foldr (\x n -> (2 * n) + bool 0 1 x) 0
-- And
encode
mask <- traverse coding message
zipAlphas (bool toLower toUpper) (concat mask) txt
where
coding ch =
case elemIndex ch chars of
Just i -> Right $ take bitsPerChar (toBinary i)
zipAlphas f = go
where
go _ [] =
| isAlpha y = (f x y :) <$> go xs ys
| otherwise = (y :) <$> go (x : xs) ys
-- And decoding:
decode = map decipher . chunksOf bitsPerChar . filter isAlpha
where
decipher = (chars !!) . min (length chars - 1) . fromBinary . map isUpper
chunksOf n = takeWhile (not . null) . unfoldr (pure . splitAt n)
text :: String
text =
unwords
]
message :: String
main :: IO ()
main = do
mapM_
(either
(putStrLn . ("-> " ++))
(putStrLn . (++ "\n") . unlines . fmap unwords . chunksOf 10 . words))
[ m
, encode "abc" message
]</lang>
{{Out}}
<pre>BAcoN's CIPher is A metHod Of StegaNogrApHy creAted By franCiS
baCon. ThIS task iS to iMplEMEnt a PRoGrAm FOr eNcrYpTIoN
and dECRypTIOn Of PlaInTExt Using ThE simPLe aLPHAbet Of tHe
BacOnIaN CIphEr Or Some OtheR kinD oF rePrESEntAtION of thiS
alpHabEt (MAKe Anything sIgnIFy anyTHiNg). tHe BAConian ALPhabET may
▲'''Examples'''
▲<lang Haskell>text = concat ["Bacon's cipher is a method of steganography created by Francis Bacon. "
▲ ,"This task is to implement a program for encryption and decryption of "
▲ ,"plaintext using the simple alphabet of the Baconian cipher or some "
▲ ,"other kind of representation of this alphabet (make anything signify "
▲ ,"anything). The Baconian alphabet may optionally be extended to encode "
▲ ,"all lower case characters individually and/or adding a few punctuation "
▲ ,"characters such as the space." ]
▲message = "the quick brown fox jumps over the lazy dog"</lang>
▲<lang Haskell>λ> let m = encode message text
▲λ> decode <$> m
▲Right "the quick brown fox jumps over the lazy dog"
▲λ> encode "something wrong @ in the message" text
▲Left "Unknown symbol '@'"
▲Left "Text is not long enough!"</lang>
=={{header|J}}==
|