-- Binary string transmitter example from chapter 7 of Programming -- in Haskell, Graham Hutton, Cambridge University Press, 2016. -- Example: -- This example simulate the transmission of a string of characters -- in low-level form, as a list of binary digits import Data.Char -- import Cipher --------------------- -- Base conversion -- --------------------- type Bit = Int -- for the purpose of the example the binary entries are reversed -- so the example calcuates the integer of the binary 1101 -- bin2int' [1,0,1,1] -- 1*1 + 2*0 + 4*1 + 8*1 = 13 -- 1 + 2*(0 + 2*1 + 4*1) bin2int' :: Num a => [a] -> a bin2int' [] = 0 bin2int' (x:xs) = x + 2 * bin2int' xs -- change the definition of bin2int so that it uses foldr instead -- bin2int :: [Bit] -> Int -- bin2int = -- int2bin 13 -- 13 devided by 2 is 6 and the reminder is 1, -- 6 devided by 2 is 3 and the reminder is 0, ..... -- [13 `mod` 2, 6 `mod` 2, 3 `mod` 2, 1 `mod` 2] -- [1,0,1,1] -- define int2bin in a recursive way -- int2bin :: Int -> [Bit] -- int2bin 0 = -- int2bin n = -- this is a function to make sure that all the inputs in the example have 8 bits -- make8 [1,0,1,1] returns [1,0,1,1,0,0,0,0] make8 :: [Bit] -> [Bit] make8 bits = take 8 (bits ++ repeat 0) ------------------ -- Transmission -- ------------------ -- > encode "abc" -- [1,0,0,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0] -- observe that it returns 8 bits per char -- define the funtion encode -- Hint: - you can use concat to concatenate the resulting list from a char -- - you can use ord to get the unicode of a character and then use int2bit, to create the list of bit -- - make sure that each char is encoded in 8 bits -- encode :: String -> [Bit] -- encode = -- this is a helping function for decoding -- separe the encoded bit, 8 at the time -- chop8 [1,0,0,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0] chop8 :: [Bit] -> [[Bit]] chop8 [] = [] chop8 bits = take 8 bits : chop8 (drop 8 bits) -- decode one binary at the time -- decode [1,0,0,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,1,0] -- decode :: [Bit] -> String -- decode = channel :: [Bit] -> [Bit] channel = id ------------- ------------- -- encoder -- ======= -- decoder -- ------------- ------------- -- transmit "haskell is fun" -- transmit :: String -> String -- transmit = ------------- ------------- -- cipher message ----> -- encoder -- ======= -- decoder -- -- decipher message --> ------------- ------------- -- merge this transmiter with the cipher example from last week so that -- Caesar can transmit "haskell is fun" (with shift factor of 3) which is then cracked at the decoder side -- caesartransmit "haskell is fun" -- caesartransmit :: String -> String -- caesartransmit =