Advertisement
giganetom

Untitled

Nov 20th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.List
  2. import Test.QuickCheck
  3.  
  4. -- Tree data structure, functions
  5.  
  6. data Tree = Nil | Node Tree Int Tree deriving (Show, Eq)
  7.  
  8. tInsert :: Int -> Tree -> Tree
  9. tInsert x Nil = Node Nil x Nil
  10. tInsert x (Node lt y rt)
  11.     | x > y     = Node (tInsert x lt) y rt
  12.     | otherwise = Node lt y (tInsert x rt)
  13.  
  14. tInsertMany :: [Int] -> Tree -> Tree
  15. tInsertMany [] t = t
  16. tInsertMany (x:xs) t = tInsertMany xs (tInsert x t)
  17.  
  18. tFromList :: [Int] -> Tree
  19. tFromList xs = tInsertMany xs Nil
  20.  
  21. -- Functions specific to the problem
  22.  
  23. nexts :: [Tree] -> [(Int, [Tree])]
  24. nexts [] = []
  25. nexts (t:ts) =
  26.     case t of
  27.         Nil -> nexts ts
  28.         Node c1 i c2 -> (i, ts ++ filter (/=Nil) [c1, c2])
  29.                       : map (\(t_, ts_) -> (t_, t : ts_)) (nexts ts)
  30.  
  31. alls :: [Tree] -> [[Int]]
  32. alls [] = [[]]          -- These two lines are to properly handle
  33. alls (Nil:ts) = alls ts -- Empty lists, and lists of Nil trees -> no trees.
  34. alls ts = concat $ map (\(i, ts_) -> map (i:) $ alls ts_) $ nexts ts
  35.  
  36. -- Stuff related to tests
  37.  
  38. prop_sameTree :: Tree -> Property
  39. prop_sameTree t = forAll (elements (alls [t])) $ \is -> t == tFromList is
  40.  
  41. prop_noTwice t = let as = alls [t] in as == nub as
  42.  
  43. instance Arbitrary Tree where
  44.     arbitrary = do
  45.         k <- choose (0,10) :: Gen Int
  46.         is <- sequence [ arbitrary | _ <- [1..k] ]
  47.         return $ tFromList is
  48.  
  49. -- And here we go.
  50.  
  51. main :: IO ()
  52. main = do
  53.     quickCheckWith stdArgs { maxSuccess = 10000 } prop_sameTree
  54.     quickCheckWith stdArgs { maxSuccess = 1000 } prop_noTwice
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement