CompareNat.agda 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. {-# OPTIONS -v treeless.opt:20 #-}
  2. module _ where
  3. open import Agda.Builtin.Nat renaming (_<_ to _<?_)
  4. open import Common.Prelude
  5. open import Common.Equality
  6. open import Agda.Builtin.TrustMe
  7. data _<_ (a b : Nat) : Set where
  8. diff : (k : Nat) → b ≡ suc k + a → a < b
  9. data Comparison {a} {A : Set a} (_<_ : A → A → Set a) (x y : A) : Set a where
  10. less : x < y → Comparison _<_ x y
  11. equal : x ≡ y → Comparison _<_ x y
  12. greater : y < x → Comparison _<_ x y
  13. compare : (a b : Nat) → Comparison _<_ a b
  14. compare a b with a <? b
  15. ... | true = less (diff (b ∸ suc a) primTrustMe)
  16. ... | false with b <? a
  17. ... | true = greater (diff (a ∸ suc b) primTrustMe)
  18. ... | false = equal primTrustMe
  19. {-# INLINE compare #-}
  20. -- This should compile to two calls of _<?_ and only the possible cases.
  21. compare-lots : (a b : Nat) → String
  22. compare-lots a b with compare a b | compare (suc a) (suc b)
  23. compare-lots a b | less (diff k eq) | less (diff k₁ eq₁) = "less-less"
  24. compare-lots a .a | less (diff k eq) | equal refl = "less-equal"
  25. compare-lots a _ | less (diff k refl) | greater (diff j eq) = "less-greater"
  26. compare-lots a .a | equal refl | less (diff k eq₁) = "equal-less"
  27. compare-lots a b | equal eq | equal eq₁ = "equal-equal"
  28. compare-lots a .a | equal refl | greater (diff k eq₁) = "equal-greater"
  29. compare-lots _ b | greater (diff k refl) | less (diff j eq) = "greater-less"
  30. compare-lots _ b | greater (diff k refl) | equal eq = "greater-equal"
  31. compare-lots a b | greater (diff k eq) | greater (diff k₁ eq₁) = "greater-greater"
  32. main : IO Unit
  33. main = putStrLn (compare-lots 1500 2000) ,,
  34. putStrLn (compare-lots 2000 1500) ,,
  35. putStrLn (compare-lots 2000 2000)