Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data Bit = B0 | B1 deriving (Show)
- bitToInt :: Bit -> Int
- bitToInt B0 = 0
- bitToInt B1 = 1
- bitsToInt :: [Bit] -> Int
- bitsToInt bits = sum (zipWith (*) digits digitValues)
- where
- digits = map bitToInt bits
- digitValues = map (2^) [0..]
- boolToBit :: Bool -> Bit
- boolToBit True = B1
- boolToBit False = B0
- intToBits :: Int -> [Bit]
- intToBits 0 = [B0]
- intToBits 1 = [B1]
- intToBits n = let (rem, quotient) = (n `mod` 2, n `div` 2)
- in (boolToBit (rem /= 0)) : intToBits quotient
- xor :: [Bit] -> [Bit] -> [Bit]
- xor [] y = y
- xor x [] = x
- xor (x:xs) (y:ys) = (x `xorBit` y) : (xor xs ys)
- xorBit :: Bit -> Bit -> Bit
- xorBit B0 B1 = B1
- xorBit B1 B0 = B1
- xorBit B0 B0 = B0
- xorBit B1 B1 = B0
- main = do
- let one = intToBits 1
- let six = intToBits 6
- let ten = intToBits 10
- print ("Should be 11", bitsToInt $ one `xor` ten)
- print ("Should be 12", bitsToInt $ six `xor` ten)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement