Skip to content

1 % 0 is an intentional runtime exception #909

@rtfeldman

Description

@rtfeldman

This was a design decision from 2013 based on how Haskell did it, which predated Elm's No Runtime Exceptions design guideline.

Creating an issue for this just to track it in https://github.com/elm-lang/core/issues/377

According to IEEE:

Some operations of floating-point arithmetic are invalid, such as taking the square root of a negative number. The act of reaching an invalid result is called a floating-point exception. An exceptional result is represented by a special code called a NaN, for "Not a Number".

Since NaN is already an Elm value due to IEEE's influence on hardware design, it seems in line with how Elm's design goals have evolved to remove the following conditional throw in favor of letting JavaScript's % return NaN in the case of division by zero, which is the normal behavior of JS %.

https://github.com/elm-lang/core/blob/80bbcc901b748f2af250b92a6a3aa5b43a73edcf/src/Elm/Kernel/Basics.js#L23-L25

A counter-argument to this is that in a world where Elm compiled to Assembly, although it could trap SIGFPE from the processor (supported on Windows as well as on POSIX) for integer division by zero, floating-point division by zero is considered well-defined by IEEE to be Infinity. So there would have to be some runtime overhead to check for Infinity, and any runtime overhead on arithmetic operations has the potential to be multiplied by a massive quantity of operations.

Interestingly, in Rust, both x % 0 and x / 0 crash the program, indicating that generating an extra automatic comparison with 0 (in order to crash if detected) was considered a worthwhile cost to pay, even for a language with a primary design goal of "have no runtime overhead."

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