Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. data Bit = B0 | B1 deriving (Show)
  2.  
  3. bitToInt :: Bit -> Int
  4. bitToInt B0 = 0
  5. bitToInt B1 = 1
  6.  
  7. bitsToInt :: [Bit] -> Int
  8. bitsToInt bits = sum (zipWith (*) digits digitValues)
  9.     where
  10.         digits = map bitToInt bits
  11.         digitValues = map (2^) [0..]
  12.  
  13. boolToBit :: Bool -> Bit
  14. boolToBit True  = B1
  15. boolToBit False = B0
  16.  
  17. intToBits :: Int -> [Bit]
  18. intToBits 0 = [B0]
  19. intToBits 1 = [B1]
  20. intToBits n = let (rem, quotient) = (n `mod` 2, n `div` 2)
  21.               in (boolToBit (rem /= 0)) : intToBits quotient
  22.  
  23. xor :: [Bit] -> [Bit] -> [Bit]
  24. xor []  y = y
  25. xor x  [] = x
  26. xor (x:xs) (y:ys) = (x `xorBit` y) : (xor xs ys)
  27.  
  28. xorBit :: Bit -> Bit -> Bit
  29. xorBit B0 B1 = B1
  30. xorBit B1 B0 = B1
  31. xorBit B0 B0 = B0
  32. xorBit B1 B1 = B0
  33.  
  34. main = do
  35.     let one = intToBits 1
  36.     let six = intToBits 6
  37.     let ten = intToBits 10
  38.  
  39.     print ("Should be 11", bitsToInt $ one `xor` ten)
  40.     print ("Should be 12", bitsToInt $ six `xor` ten)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement