less prototype, less bad code implementation of CCHM type theory
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.2 KiB

  1. module Elab.Eval.Formula where
  2. import qualified Data.Map.Strict as Map
  3. import qualified Data.Sequence as Seq
  4. import Data.Map.Strict (Map)
  5. import Syntax
  6. import {-# SOURCE #-} Elab.WiredIn (inot, ior, iand)
  7. toDnf :: Value -> Maybe Value
  8. toDnf (VNe _ _) = Nothing
  9. toDnf x = toDnf x where
  10. toDnf (VIAnd x y) = idist <$> toDnf (inot x) <*> toDnf (inot y)
  11. toDnf (VIOr x y) = ior <$> toDnf x <*> toDnf y
  12. toDnf (VINot x) = inot <$> toDnf x
  13. toDnf VI0 = pure VI0
  14. toDnf VI1 = pure VI1
  15. toDnf v@(VNe _ Seq.Empty) = pure v
  16. toDnf _ = Nothing
  17. compareDNFs :: Value -> Value -> Bool
  18. compareDNFs (VIOr x y) (VIOr x' y') =
  19. let (a, a') = swap x y
  20. (b, b') = swap x' y'
  21. in compareDNFs a b && compareDNFs a' b'
  22. compareDNFs (VIAnd x y) (VIAnd x' y') =
  23. let (a, a') = swap x x'
  24. (b, b') = swap y y'
  25. in compareDNFs a a' && compareDNFs b b'
  26. compareDNFs x y = x == y
  27. swap :: Ord b => b -> b -> (b, b)
  28. swap x y =
  29. if x <= y then (x, y) else (y, x)
  30. possible :: Map Head Bool -> Value -> (Bool, Map Head Bool)
  31. possible sc (VINot (VNe n Seq.Empty)) =
  32. case Map.lookup n sc of
  33. Just True -> (False, sc)
  34. _ -> (True, Map.insert n False sc)
  35. possible sc (VNe n Seq.Empty) =
  36. case Map.lookup n sc of
  37. Just False -> (False, sc)
  38. _ -> (True, Map.insert n True sc)
  39. possible sc (VIAnd x y) =
  40. let (a, sc') = possible sc x
  41. (b, sc'') = possible sc' y
  42. in (a && b, sc'')
  43. possible sc (VIOr x y) =
  44. case possible sc x of
  45. (True, sc') -> (True, sc')
  46. (False, _) -> possible sc y
  47. possible sc VI0 = (False, sc)
  48. possible sc VI1 = (True, sc)
  49. possible sc _ = (False, sc)
  50. truthAssignments :: NFEndp -> Map Name (NFType, NFEndp) -> [Map Name (NFType, NFEndp)]
  51. truthAssignments VI0 m = []
  52. truthAssignments VI1 m = pure m
  53. truthAssignments (VIOr x y) m = truthAssignments x m ++ truthAssignments y m
  54. truthAssignments (VIAnd x y) m = truthAssignments x =<< truthAssignments y m
  55. truthAssignments (VNe (HVar x) Seq.Empty) m = pure (Map.insert x (VI, VI1) m)
  56. truthAssignments (VINot (VNe (HVar x) Seq.Empty)) m = pure (Map.insert x (VI, VI0) m)
  57. truthAssignments x _ = error $ "impossible formula: " ++ show x
  58. idist :: Value -> Value -> Value
  59. idist (VIOr x y) z = (x `idist` z) `ior` (y `idist` z)
  60. idist z (VIOr x y) = (z `idist` x) `ior` (z `idist` y)
  61. idist z x = iand z x