You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Activity