Is it a good idea to explore if-let more seriously?


I’ve been using Swift for a while now, which has a lot of syntactic sugar around its Optional types: nil- coalescing operators, if let (+ a new pun if let foo to mean if let foo = foo) as well as an early exiting control flow guard let.

Swift also has an ML style pattern matching using its switch statements, but we almost always stick with the baked in if let-like sugars in Swift due to its ergonomics.
I think if let sugar should be considered in the context of the whole family around it.

But things might turn out differently in ReScript, as Swift differentiates statements with expressions.


I actually not offen using it in rust, because it always let me ignore the else arm if the if arm return nothing.

I made a proposal here:


I, as a person who came from JavaScript world, can hardly understand what the code does. I don’t think that we should add more complexity to the language.


I think it is not so idiomatic…

I’ll bring the example here for the context.

 // imaginary syntax
 let testFetchWithResult = async () =>
   if let Ok(response1) = await FetchResult.fetch("")
      and Some(url) = nextFetch(response1)
      and Ok(response2) = await FetchResult.fetch(url) {
     Js.log2("FetchResult response2", response2->Fetch.Response.status)

OK, is it much different from the let-op bindings available in F# and introduced in OCaml recently? Here’s a rough alternative:

let testFetchWithResult = async () => {
  let+Result response1 = await FetchResult.fetch("")
  let+Option url = nextFetch(response1)
  let+Result response2 = await FetchResult.fetch(url)
  Js.log2("FetchResult response2", response2->Fetch.Response.status)

I remember @Hongbo was strictly against let-ops in ReScript because they are over-[ab]used in some project he has experience with and they shadow a lot of potential problems compared to explicit pattern matching. I can’t find that thread though.

OK, ok, I see my “example” has the mess with mixing Result/Option types. It might be solved by wrapping the Option into Result… Nevertheless, the if let expression indeed looks lighter and more clear from semantic point of view (if you look at it as a switch pattern matching variation), but the syntax looks too nested and clunky. Perhaps it is because I didn’t use such expressions in practice yet.