mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[stdlib] Add `unreachable` check instead of `constrained[False]`

Open Benny-Nottonson opened this issue 9 months ago • 2 comments

As mentioned in #2547, there should realistically be an unreachable function, to indicate when a segment of code can never be reached.

For example

fn one_or_two[value: Int]() -> Int:
    if value == 1:
        return 1
    elif value == 2:
        return 2
    unreachable()

The above code demonstrates a great use case, where the alternative now would be:

fn one_or_two[value: Int]() -> Int:
    constrained[value == 1 or value == 2]()
    if value == 1:
        return 1
    return 2

This is problematic in my opinion as it creates two issues:

  1. You are now checking value == 1 two separate times, the only way to avoid this is creating an unnecessary variable.
  2. You are reducing readability and harming code structure by leading with the entire body of a conditional.

More information and further suggestions found at https://github.com/modularml/mojo/issues/2547

Signed-off-by: benny-nottonson [email protected]

Benny-Nottonson avatar May 06 '24 02:05 Benny-Nottonson

contrained[value == 1 or value == 2]()

I assume you mean constrained?

Brian-M-J avatar May 06 '24 17:05 Brian-M-J

contrained[value == 1 or value == 2]()

I assume you mean constrained?

my mistake, fixed

Benny-Nottonson avatar May 06 '24 17:05 Benny-Nottonson