-
Notifications
You must be signed in to change notification settings - Fork 260
Open
Description
The gymnastics associated with the three constructors of ℤ exhaust me... especially when the signed representation seems to streamline the definition of division with remainder, as follows:
module _ (i : ℤ) (d : ℕ) .{{_ : ℕ.NonZero d}} where
infixl 7 _/ℕ_ _%ℕ_
divℕmod : ℤ × ℕ
divℕmod with s ◂ n ← signAbs i with q ← n ℕ./ d with r ← n ℕ.% d with s
... | Sign.+ = + q , r
... | Sign.- with r
... | ℕ.zero = - (+ q) , 0
... | r@(ℕ.suc _) = -[1+ q ] , d ℕ.∸ r
_/ℕ_ : ℤ
_/ℕ_ = proj₁ divℕmod
_%ℕ_ : ℕ
_%ℕ_ = proj₂ divℕmodAny reason why doing it this way would be a bad/worse idea than the current version?
UPDATED:
- tidied up the block
- followup question: could we make divℕmod a fully-fledged view which enforces the spec? (modulo importing the properties from Nat... so we'd have to move these operations out of
Base.. but maybe that's OK?) - see also [ question ] Status of
BUILTINpragmas: possibility of redefining 'basic'Datarepresentations? agda#8208 ... could we have a 'better' primitiveIntrepresentation? If only Agda permitted it?
Similarly, for Nat, we can fold fuse the helper functions together, and obtain
div-mod-helper : (m n j : ℕ) → ℕ × ℕ → ℕ × ℕ
div-mod-helper m zero _ p = p
div-mod-helper m (suc n) zero (k , _) = div-mod-helper m n m (suc k , 0)
div-mod-helper m (suc n) (suc j) (k , l) = div-mod-helper m n j (k , suc l)
module _ (dividend divisor : ℕ) .{{_ : NonZero divisor}} where
infixl 7 _/_ _%_
div-mod : ℕ × ℕ
div-mod = div-mod-helper n dividend n (0 , 0)
where n = pred divisor
_/_ = proj₁ div-mod
_%_ = proj₂ div-modNB. Issue #2644 may require further rethinking of such definitions!
Metadata
Metadata
Assignees
Labels
No labels