Trie.hs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. {-# LANGUAGE TemplateHaskell #-}
  2. module Internal.Utils.Trie ( tests ) where
  3. import Agda.Utils.Trie
  4. import Data.Function ( on )
  5. import Data.List ( nubBy, sortBy, isPrefixOf, inits )
  6. import Prelude hiding ( lookup, filter )
  7. import qualified Prelude
  8. import Internal.Helpers
  9. -- Tests ------------------------------------------------------------------
  10. newtype Key = Key Int
  11. deriving (Eq, Ord)
  12. newtype Val = Val Int
  13. deriving (Eq)
  14. newtype Model = Model [([Key], Val)]
  15. deriving (Eq, Show)
  16. instance Show Key where
  17. show (Key x) = show x
  18. instance Show Val where
  19. show (Val x) = show x
  20. instance Arbitrary Key where
  21. arbitrary = elements $ map Key [1..2]
  22. shrink (Key x) = Key <$> shrink x
  23. instance Arbitrary Val where
  24. arbitrary = elements $ map Val [1..3]
  25. shrink (Val x) = Val <$> shrink x
  26. instance Arbitrary Model where
  27. arbitrary = Model <$> arbitrary
  28. shrink (Model xs) = Model <$> shrink xs
  29. modelToTrie :: Model -> Trie Key Val
  30. modelToTrie (Model xs) = foldr (uncurry insert) empty xs
  31. prop_lookup :: [Key] -> Model -> Bool
  32. prop_lookup ks m@(Model ksvs) =
  33. lookup ks (modelToTrie m) == Prelude.lookup ks ksvs
  34. modelPath :: [Key] -> Model -> [Val]
  35. modelPath ks (Model xs) =
  36. map snd
  37. $ sortBy (compare `on` length . fst)
  38. $ nubBy ((==) `on` fst)
  39. $ Prelude.filter (flip isPrefixOf ks . fst) xs
  40. prop_path :: [Key] -> Model -> Property
  41. prop_path ks m =
  42. collect (length $ modelPath ks m) $
  43. lookupPath ks (modelToTrie m) == modelPath ks m
  44. prop_everyPrefix :: [Integer] -> Integer -> Bool
  45. prop_everyPrefix ks v =
  46. everyPrefix ks v ==
  47. foldr union empty [ singleton ks' v | ks' <- inits ks ]
  48. ------------------------------------------------------------------------
  49. -- * All tests
  50. ------------------------------------------------------------------------
  51. -- Template Haskell hack to make the following $allProperties work
  52. -- under ghc-7.8.
  53. return [] -- KEEP!
  54. -- | All tests as collected by 'allProperties'.
  55. --
  56. -- Using 'allProperties' is convenient and superior to the manual
  57. -- enumeration of tests, since the name of the property is added
  58. -- automatically.
  59. tests :: TestTree
  60. tests = testProperties "Internal.Utils.Trie" $allProperties