Are `if-let` constructs going to be supported?

I will use this solution, thank you very much. I suppose this:

firstChar->Js.Re.exec_

is a single argument closure applied to someline? Can I write it:

Js.Re.exec_(firstChar, _)

Yeah. There’s a use-case for this notation even when your language is not pure. Async, for example.

1 Like

You’re right. The second way works too.

I was able to write it using Option.flatMap, and the ReScript code looks much nicer, but the generated Javascript code looks much uglier.
Should I open a bug against rescript-compiler?

What does “ugly” mean to you?

It means “harder to understand”. This is my diff:

I wish the compiler could detect the pattern and compile it to the previous JavaScript.

I see. Don’t know how to make it more readable, though. The only idea how to make it a little bit better is to apply Prettier. You can do it using the Build System Configuration | ReScript Language Manual configuration.

Can offer my +1 that if let syntax is often very useful in rust; and is something I miss when writing ReScript. As mentioned above, it works best when you have a simple binary enum check (“If Some(x), do this; else do nothing”) or if you want to make a condition destructuring:

type t = Foo(int) | Bar(int) | Baz(int)

let fn = (x: t) => {
  //Bar is our happy case
  if let Bar(payload) = x {
    return Some(payload)
  } else {
    return None
  }
}

obviously doens’t provider any functionality that isn’t already provided by switch, but I think it’s often nice to have :slight_smile:

1 Like

I fail to see how this latter example is obviously better than the more uniform and flexible form of a switch. It’s not even shorter in any sense.

switch x {
| Bar(payload) => Some(payload)
| _ => None
}

Even with an implied _ => () branch, I find it hard to justify the introduction of such a complex feature just to save a single line of code in rare circumstances (in the codebase I’m currently working on there are two instances of this in 25k lines of ReScript). Simplicity is a virtue in language design, and this really isn’t that.

Edit: For some more numbers: I also work in Rust, with this codebase having 65k lines of Rust code and 333 instances of if let. I ascribe that to Rust being much more imperative in nature, not just in the design of the language itself, but also in the idioms that have emerged. if let makes much more sense in Rust, but still I find it awkward to use in many cases because it lacks quite a bit of flexibility compared to using match.

8 Likes