Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Straw alternative for negative if-variables #3217

Closed
nex3 opened this issue Jul 14, 2023 · 1 comment
Closed

Straw alternative for negative if-variables #3217

nex3 opened this issue Jul 14, 2023 · 1 comment
Labels
request Requests to resolve a particular developer problem

Comments

@nex3
Copy link
Member

nex3 commented Jul 14, 2023

It seems that most of the value of #1201 is now covered by pattern matches and the if-case syntax, except for negative if-variables which don't really have any equivalent in the current syntax. That is, it's still awkward to write things like:

var list = someComputation();
if (list.length != 1) {
  // Early exit, throw an error, whatever
}

var element = list[0];
// Use element in some long computation

This gets progressively more unpleasant the more complex the condition is. The problem with slotting this nicely into the pattern matching metaphor is that patterns are almost universally positive assertions—there's not an obvious way to both say "if this value doesn't match this pattern" and also extract values when it does.

So I propose the following straw syntax idea for a way to handle this that works well with patterns:

var [element] = someComputation() else {
  // Early exit, throw an error, whatever
}

// Use element in some long computation 

That is: allow variable declarations with LHS patterns to follow their RHS with an else block, which runs when the pattern match fails. This block must cause control flow to leave the containing scope by ending with return, break, a Never-valued statement, etc. The destructured variables are defined in the following scope as normal, but not in the else block.

The core idea here is to mitigate the weirdness of negative if-variables by changing the focus from "an if statement with a side effect of defining/promoting variables if the check fails" to "a variable assignment with a side-effect of running some code if the pattern match fails". I'm not wedded to this specific syntax by any means, but I think that framing might better align with user expectations and the existing pattern matching support.

@nex3 nex3 added the request Requests to resolve a particular developer problem label Jul 14, 2023
@leafpetersen
Copy link
Member

I think this is covered here, closing in favor of that issue (feel free to re-open if I've missed something).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
request Requests to resolve a particular developer problem
Projects
None yet
Development

No branches or pull requests

2 participants