WfRec.agda 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. module _ where
  2. open import Common.Prelude renaming (_∸_ to _-_) -- work-around for #1855
  3. data Acc {a} {A : Set a} (_<_ : A → A → Set) (x : A) : Set a where
  4. acc : (∀ y → y < x → Acc _<_ y) → Acc _<_ x
  5. data _<_ : Nat → Nat → Set where
  6. zero : ∀ {n} → zero < suc n
  7. suc : ∀ {n m} → n < m → suc n < suc m
  8. _≤_ : Nat → Nat → Set
  9. n ≤ m = n < suc m
  10. data LeqView (n : Nat) : Nat → Set where
  11. less : ∀ {m} → n < m → LeqView n m
  12. equal : LeqView n n
  13. leqView : ∀ {n m} → n ≤ m → LeqView n m
  14. leqView {m = zero} zero = equal
  15. leqView {m = suc m} zero = less zero
  16. leqView {m = zero} (suc ())
  17. leqView {m = suc m} (suc leq) with leqView leq
  18. leqView {._} {suc m} (suc leq) | less lt = less (suc lt)
  19. leqView {.(suc m)} {suc m} (suc lt) | equal = equal
  20. case_of_ : ∀ {A B : Set} → A → (A → B) → B
  21. case x of f = f x
  22. wfAux : ∀ {n y} → (∀ z → z < n → Acc _<_ z) → y ≤ n → Acc _<_ y
  23. wfAux f leq with leqView leq
  24. wfAux f leq | less lt = f _ lt
  25. wfAux f leq | equal = acc f
  26. wfNat : ∀ n → Acc _<_ n
  27. wfNat zero = acc λ _ ()
  28. wfNat (suc n) with wfNat n
  29. ... | acc f = acc (λ y lt → wfAux f lt)
  30. ≤-refl : ∀ n → n ≤ n
  31. ≤-refl zero = zero
  32. ≤-refl (suc n) = suc (≤-refl n)
  33. wk< : ∀ {n m} → n < m → n < suc m
  34. wk< zero = zero
  35. wk< (suc lt) = suc (wk< lt)
  36. less-minus : ∀ n m → (suc n - suc m) ≤ n
  37. less-minus n zero = ≤-refl n
  38. less-minus zero (suc m) = zero
  39. less-minus (suc n) (suc m) = wk< (less-minus n m)
  40. NonZero : Nat → Set
  41. NonZero zero = ⊥
  42. NonZero (suc _) = ⊤
  43. divsuc : ∀ n → Nat → Acc _<_ n → Nat
  44. divsuc 0 _ _ = 0
  45. divsuc (suc n) m (acc f) =
  46. suc (divsuc (n - m) m (f _ (less-minus n m)))
  47. div : Nat → (m : Nat) → {_ : NonZero m} → Nat
  48. div n zero {}
  49. div n (suc m) = divsuc n m (wfNat n)
  50. main : IO Unit
  51. main = printNat (div 1000000 1000)