yingpotter

[99p]Logic(Complete)

Jul 15th, 2011
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.List
  2. import Data.Function
  3.  
  4. -- predefine
  5. not' :: Bool -> Bool
  6. not' True  = False
  7. not' False = True
  8.  
  9. and',or',nor',nand',xor',impl',equ' :: Bool -> Bool -> Bool
  10.  
  11. and' True True = True
  12. and' _ _ = False
  13.  
  14. or' False False = False
  15. or' _ _ = True
  16.  
  17. nand' a b = not' (and' a b)
  18. nor' a b = not' (or' a b)
  19.  
  20. xor' a b
  21.    | a==b   =False
  22.    | a/=b   =True
  23.    
  24. equ' a b = not' (xor' a b)
  25.  
  26.    ----- not understand
  27. impl' a b = or' (not' a) b
  28.  
  29. -- problem 46
  30. table :: (Bool -> Bool ->t) -> [(Bool, Bool, t)]
  31. table f = [(a, b, f a b)| a <- [True, False], b <- [True, False]]
  32.  
  33. -- problem 47
  34.   ------ the same w/ above
  35.  
  36. -- problem 48
  37.   ------ not understand
  38.   ------ tablen f = [(a, b, c, f [a, b, c])| a <- [True, False], b <- [True, False], c <- [True, False]]
  39.  
  40. -- problem 49
  41. gray :: Num a => a -> [[Char]]
  42. gray 0 = [[]]
  43. gray n = (map ("0"++) $ gray (n-1)) ++ (map ("1"++) $ reverse $ gray (n-1))
  44.  
  45. -- problem 50
  46.   ------ type and data structure for I/O and huffman trees
  47. type FList = [(Char, Int)]  
  48. type CList = [(Char, String)]
  49. data HTree = Leaf {symbol :: Char, wt :: Int} | Branch {wt :: Int, l :: HTree, r :: HTree} deriving (Eq)
  50. instance Ord HTree
  51.            where compare = compare `on` wt
  52.   ------ functions
  53. htmerge :: HTree -> HTree -> HTree
  54. htmerge x y = Branch (wt x + wt y) x y
  55. flist2ht :: FList -> HTree
  56. flist2ht = buildht . sort . map (uncurry Leaf)
  57.           where
  58.                buildht :: [HTree] -> HTree
  59.                buildht [] = error "Empty Tree"
  60.                buildht (t:[]) = t
  61.                buildht (x:y:ts) = buildht $ insert (htmerge x y) ts
  62. ht2clist :: HTree -> CList
  63. ht2clist = htextract ""
  64.            where
  65.                htextract :: String -> HTree -> CList
  66.                htextract s (Leaf sy _) = [(sy,s)]
  67.                htextract s (Branch _ lt rt) = htextract (s ++ "0") lt ++ htextract (s ++ "1") rt
  68. huffman = sortBy (compare `on` fst) . ht2clist . flist2ht
Advertisement
Add Comment
Please, Sign In to add comment