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

Proposal: case statements #16183

Closed
alrz opened this issue Jan 2, 2017 · 1 comment
Closed

Proposal: case statements #16183

alrz opened this issue Jan 2, 2017 · 1 comment

Comments

@alrz
Copy link
Contributor

alrz commented Jan 2, 2017

One of the main motivations of a pattern-matching statement (#6400) is to prevent additional indention that occurs within if statements. However, with revised scoping rules around declaration expressions, you can negate the whole expression and variables will be still in scope after the if block.

if(!(e is <pattern>)) return;
// use pattern variables

This would not be that convenient to use, besides, not all patterns are fallible. So that the is expression would always return true and therefore, is redundant.

With let as the read-only counterpart of var as proposed in #16182, it would be no longer available as a pattern-matching statement e.g. let X x = e; would not do pattern-match like #6400.

To prevent possible ambiguities and avoid backward-compat issues (#10624), I suggest we use case (analogous with case labels in switch) as the pattern-matching statement.

case <pattern> = e1 [[when e2] else return];

Note: An expression form of case is already being used in pattern-matching spec draft. This caused an ambiguity (or otherwise indistinguishable visual difference) with match labels — therefore, the grammar does not allow case expressions to be chained. I think it would be better to reuse match itself as a shorthand for a one-handed match expression.

var x = e1 match { case <pattern>: e2 };
var x = e1 match <pattern>: e2;

This is no longer ambigious and can be nested.

@YaakovDavis
Copy link

YaakovDavis commented Jan 25, 2017

Why not match statements? e.g.

match p to e1 when e2 else return;

BTW, conceptually, both p and e2 can have "holes", filling each other. e.g.:

match (a, 5) to (7, b);

I implemented a similar idea in a personal language. Though this "mutual filling" aspect is independent of the main discussion.

(Disclaimer: I don't like the when/else parts. IMO all matched variables should have default values in case the decomposition fails. Testing can be done in a separate statement.)

Regrading the 2nd topic, it correlates to another feature I proposed:
#15821

With that implemented, you could simply write the following, without special pattern-matching support:

var x = { switch(e1){ case pattern: return e2; ... } }

@alrz alrz closed this as completed Apr 23, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants