Skip to content

Return an optional for numeric conversions instead of trapping? #192

Open
@rvanasa

Description

@rvanasa

Instead of trapping for lossy numeric conversions (e.g. Nat8.toNat() or Int.toNat()), it could make sense to return an optional value to give the developer a way to handle the error case in a more ergonomic way.

Examples:

let ?n = Int.toNat(-5) else return #err("Custom error message");

assert switch (Int.toNat(5)) {
  case (?n) n == 5;
  case _ false
}

For developers who want to maximize performance, or in cases where you can guarantee that the number will convert without trapping, it would remain possible to bypass this check by directly calling the corresponding Prim function.

Currently, Int.toNat() / Nat.fromInt() return an optional while fixed-size numeric types trap. Therefore, we should change the conversions one way or the other for consistency.

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