Advertisement
Mihai_Preda

Untitled

Jan 30th, 2021
502
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Exercitiul 1
  2.  
  3. data Arbore a
  4.     = Nod (Arbore a) a (Arbore a)
  5.     | Vid
  6.  
  7. -- For testing purposes.
  8. instance Eq a => Eq (Arbore a) where
  9.     Vid == Vid = True
  10.     _ == Vid = False
  11.     Vid == _ = False
  12.     (Nod stA a drA) == (Nod stB b drB) = a == b && stA == stB && drA == drB
  13.  
  14. instance Show a => Show (Arbore a) where  
  15.     show Vid = "VID"
  16.     show (Nod st a dr) = show st ++ " " ++ show a ++ " " ++ show dr
  17.  
  18. -- rootBigger x y -> checks if root of x is bigger than all the elements in y
  19. rootBigger :: Ord a => Arbore a -> Arbore a -> Bool
  20. rootBigger Vid _ = True
  21. rootBigger _ Vid = True
  22. rootBigger (Nod x a y) (Nod st other dr) = a > other && rootBigger (Nod x a y) st && rootBigger (Nod x a y) dr
  23.  
  24. -- rootSmaller x y -> checks if root of x is smaller than all the elements in y
  25. rootSmaller :: Ord a => Arbore a -> Arbore a -> Bool
  26. rootSmaller Vid _ = True
  27. rootSmaller _ Vid = True
  28. rootSmaller (Nod x a y) (Nod st other dr) = a < other && rootSmaller (Nod x a y) st && rootSmaller (Nod x a y) dr
  29.  
  30. -- a)
  31. verif :: Ord a => Arbore a -> Bool
  32. verif Vid = True
  33. verif (Nod st a dr) = rootBigger (Nod st a dr) st && rootSmaller (Nod st a dr) dr && verif st && verif dr
  34.  
  35. arb1 :: Arbore Integer
  36. arb1 = Nod Vid 5 Vid
  37. arb2 :: Arbore Integer
  38. arb2 = Nod (Nod Vid 3 Vid) 5 (Nod Vid 7 Vid)
  39.  
  40. test1 :: Bool
  41. test1 = verif arb1
  42.  
  43. test2 :: Bool
  44. test2 = verif arb2
  45.  
  46. test3 :: Bool
  47. test3 = not (verif (Nod (Nod Vid 6 Vid) 5 (Nod Vid 7 Vid)))
  48.  
  49. test4 :: Bool
  50. test4 = not (verif (Nod (Nod Vid 3 Vid) 5 (Nod Vid 7 (Nod Vid 4 Vid))))
  51.  
  52. test5 :: Bool
  53. test5 = not (verif (Nod (Nod Vid 3 Vid) 5 (Nod Vid 7 (Nod Vid 7 Vid))))
  54.  
  55. -- b)
  56. insert :: Ord t => Arbore t -> t -> Arbore t
  57. insert Vid x = Nod Vid x Vid
  58. insert (Nod st a dr) x
  59.     | x < a = Nod (insert st x) a dr
  60.     | x > a = Nod st a (insert dr x)
  61.     | otherwise = Nod st a dr
  62.  
  63. test6 :: Bool
  64. test6 = insert Vid 5 == Nod Vid 5 Vid
  65.  
  66. test7 :: Bool
  67. test7 = insert arb1 5 == arb1
  68.  
  69. test8 :: Bool
  70. test8 = insert arb2 6 == Nod (Nod Vid 3 Vid) 5 (Nod (Nod Vid 6 Vid) 7 Vid)
  71.  
  72. -- c)
  73. instance Functor Arbore where
  74.     fmap _ Vid = Vid
  75.     fmap f (Nod st a dr) = Nod (fmap f st) (f a) (fmap f dr)
  76.  
  77. test9 :: Bool
  78. test9 = fmap (+1) arb2 == Nod (Nod Vid 4 Vid) 6 (Nod Vid 8 Vid)
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement