12
data DivMod : Nat -> Nat -> Set where
13
dm : forall {b} q (r : Fin b) -> DivMod (toNat r + q * b) b
15
getQ : forall {a b} -> DivMod a b -> Nat
18
getR : forall {a b} -> DivMod a b -> Nat
19
getR (dm _ r) = toNat r
21
divModˢ : (a b : Nat) -> DivMod a (suc b)
22
divModˢ zero b = dm 0 zero
23
divModˢ (suc a) b with divModˢ a b
24
divModˢ (suc ._) b | dm q r with maxView r
25
divModˢ (suc ._) b | dm q .(fromNat b) | theMax
26
with toNat (fromNat b) | lem-toNat-fromNat b
27
... | .b | refl = dm {suc b} (suc q) zero
28
divModˢ (suc ._) b | dm q .(weaken i) | notMax i
29
with toNat (weaken i) | lem-toNat-weaken i
30
... | .(toNat i) | refl = dm q (suc i)
32
divMod : (a b : Nat){nz : NonZero b} -> DivMod a b
34
divMod a (suc b) = divModˢ a b
36
module Inductive where
38
data DivMod : Nat -> Nat -> Set where
39
dmZ : forall {b} (i : Fin b) -> DivMod (toNat i) b
40
dmS : forall {a b} -> DivMod a b -> DivMod (b + a) b
42
getQ : forall {a b} -> DivMod a b -> Nat
44
getQ (dmS d) = suc (getQ d)
46
getR : forall {a b} -> DivMod a b -> Nat
47
getR (dmZ r) = toNat r
50
data BoundView (n : Nat) : Nat -> Set where
51
below : (i : Fin n) -> BoundView n (toNat i)
52
above : forall a -> BoundView n (n + a)
54
boundView : (a b : Nat) -> BoundView a b
55
boundView zero b = above b
56
boundView (suc a) zero = below zero
57
boundView (suc a) (suc b) with boundView a b
58
boundView (suc a) (suc .(toNat i)) | below i = below (suc i)
59
boundView (suc a) (suc .(a + k)) | above k = above k
61
data _≤_ : Nat -> Nat -> Set where
62
leqZ : forall {n} -> zero ≤ n
63
leqS : forall {n m} -> n ≤ m -> suc n ≤ suc m
65
≤-suc : forall {a b} -> a ≤ b -> a ≤ suc b
67
≤-suc (leqS p) = leqS (≤-suc p)
69
plus-≤ : forall a {b c} -> a + b ≤ c -> b ≤ c
71
plus-≤ (suc a) (leqS p) = ≤-suc (plus-≤ a p)
73
≤-refl : forall {a} -> a ≤ a
75
≤-refl {suc n} = leqS ≤-refl
77
-- Recursion over a bound on a (needed for termination).
78
divModˢ : forall {size} a b -> a ≤ size -> DivMod a (suc b)
79
divModˢ a b prf with boundView (suc b) a
80
divModˢ .(toNat r) b _ | below r = dmZ r
81
divModˢ .(suc b + k) b (leqS prf) | above k = dmS (divModˢ k b (plus-≤ b prf))
83
divMod : forall a b {nz : NonZero b} -> DivMod a b
85
divMod a (suc b) = divModˢ a b ≤-refl
87
-- We ought to prove that the inductive version behaves the same as the
88
-- direct version... but that's more work than we're willing to spend.
92
_div_ : (a b : Nat){nz : NonZero b} -> Nat
93
_div_ a b {nz} = getQ (divMod a b {nz})
95
_mod_ : (a b : Nat){nz : NonZero b} -> Nat
96
_mod_ a b {nz} = getR (divMod a b {nz})