FFFF Safe (non-raising) divide / remainder / modulo · Issue #705 · kexhq/kex · GitHub
[go: up one dir, main page]

Skip to content

Safe (non-raising) divide / remainder / modulo #705

Open

Description

@akoskovacs

Proposal: non-raising counterparts of the integer division operations, plus Float division, returning an Optional instead of raising on a zero divisor.

What exists (src/stdlib/number.kex), all raising on 0:

  • a / b: truncating (5 / 2 == 2, pinned by spec/backend_arithmetic_errors.kex)
  • a % b: remainder
  • a.div(n): floored quotient
  • a.modulo(n): floored modulo
  • a.divmod(n): (div, modulo)

a.dividesBy?(0) is already total.

Sketch:

raising safe on 0
a / b a.divide(b) -> Integer? None
a % b a.remainder(b) -> Integer? None
a.modulo(b) checked modulo None
a.div(b) checked div None
a.divmod(b) checked divmod -> (Integer, Integer)? None
Float a / b a.divide(b) -> Float? None, also instead of raising on overflow / NaN

Naming is the main open question:

  • Gleam: word forms. int.divide, int.remainder, int.modulo → Result(Int, Nil); / itself is total (x / 0 == 0).
  • Rust: a checked_ prefix (checked_div, checked_rem, checked_rem_euclid).
  • Crystal: a ? suffix means "nil instead of raising" (arr[i]?, to_i?, first?), as well as predicates. So a.modulo?(b) would be natural there. Kex currently uses ? for predicates only (even?, dividesBy?), so adopting it would be a convention change.

Other notes:

  • Optional is enough for Int (zero is the only failure). For Float, a Result with the IEEE-style kinds (DivisionByZero | Overflow | Invalid) might be worth it.
  • Cost on BEAM: measured on OTP 29 JIT, ns/op including the loop.
    • Int: raw div 9.4, guarded 13.6–14.3, {ok,V}-wrapped 20–22.
    • Float: raw / 17.3, try … catch badarith 41.5–42.9.
    • A guard clause is cheap for Int. For Float, avoid try in the hot path: it stops the JIT keeping floats unboxed.
  • Specs for each op on both backends.
  • Related: Runtime faults must be rescuable: walker cannot rescue div by zero, BEAM reasons inconsistent #704 (the plain operators keep raising, and that becomes rescuable).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0