'if let' expression

Has the idea of an ‘if let’ expression, like in Rust, ever been discussed for Elm?
https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html

It could look like this:

type Num
    = None
    | Zero
    | Num Int


greaterThanFive : Num -> Bool
greaterThanFive val =
    if let Num n = val then
        n > 5

    else
        False
1 Like

I don’t think it has been discussed before. That said, do you gain anything from writing it that way instead of like this? It’s only one line longer.

type Num
    = None
    | Zero
    | Num Int


greaterThanFive : Num -> Bool
greaterThanFive val =
    case val of 
        Num n ->
            n > 5

        _ -> 
             False
8 Likes

I don’t think there is an advantage in having this syntax in elm because we are forced to have an else branch to have total functions. It’s thus roughly the same than doing pattern matching. This is not the case in Rust where you can have early returns, where this syntax is mostly useful.

3 Likes

Yeah true, I mostly use it for early returns.

Also note that if let is already valid syntax, though it doesn’t do what’s proposed in this thread.

if let sum = 1 + 2 in sum == 3 then
    "Math works!"
else
    "I don’t even…"
4 Likes

I think it would be strange to add syntax specifically to make it easier/nicer to do something that is generally discouraged.
This syntax is just a nicer way of doing:

  greaterThanFive : Num -> Bool
  greaterThanFive val =
      case val of 
          Num n ->
              n > 5

          _ -> 
               False

But generally it’s discouraged to write functions that don’t handle all variants of a type. So it would be strange to have special syntax for such a rare case.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.