Skip to content

[ add ] a 'better' division with remainder for Data.Integer.Base #2878

@jamesmckinna

Description

@jamesmckinna

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ℕmod

Any reason why doing it this way would be a bad/worse idea than the current version?

UPDATED:

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-mod

NB. Issue #2644 may require further rethinking of such definitions!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions