Created
August 10, 2013 18:11
-
-
Save qoelet/6201499 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.Char | |
type Bit = Int | |
-- in reverse order | |
bits2int :: [Bit] -> Int | |
bits2int bits = sum [w*b | (w,b) <- zip weights bits] | |
where weights = iterate (*2) 1 | |
int2bin :: Int -> [Bit] | |
int2bin 0 = [] | |
int2bin n = n `mod` 2 : int2bin (n `div` 2) | |
-- truncates or extends a binary number to precisely eight bits | |
make8 :: [Bit] -> [Bit] | |
make8 bits = take 8 (bits ++ repeat 0) | |
encode :: String -> [Bit] | |
encode = concat.map (make8.int2bin.ord) | |
-- chops a list produce by encode into eight-bit binary numbers | |
chop8 :: [Bit] -> [[Bit]] | |
chop8 [] = [] | |
chop8 bits = take 8 bits: chop8 (drop 8 bits) | |
decode :: [Bit] -> String | |
decode = map (chr.bits2int).chop8 | |
-- simulates the transmission of a string of characters as a list of bits, using identity function to model a | |
-- perfect communication channel | |
transmit :: String -> String | |
transmit = decode.channel.encode | |
channel :: [Bit] -> [Bit] | |
channel = id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment