# [DISCUSSION] Match expression

- Thread: https://externals.io/message/109590
- Original archive: https://news-web.php.net/php.internals/109590
- Started by Ilija Tovilo on 2020-04-12T00:16:04+00:00
- Messages: 36
- RFC: Match expression (Declined) — https://externals.io/rfc/match_expression.md
- RFC: Switch expression (Withdrawn) — https://externals.io/rfc/switch_expression.md
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/109590.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #109590 — Ilija Tovilo — 2020-04-12T00:16:04+00:00

URL: https://externals.io/message/109590#109590

Hi internals

I'd like to announce the match expression RFC that replaces the switch
expression RFC I announced a few weeks ago.
New: https://wiki.php.net/rfc/match_expression
Old: https://wiki.php.net/rfc/switch_expression

Due to the feedback I decided to take the RFC in a slightly different
direction. The main objections were:

1. It didn't behave like the traditional switch so it shouldn't use
the switch keyword
2. It didn't fix type coercion
3. The RFC was poorly structured

In hindsight I understand why I had a hard time writing the RFC. I
tried making a case against the switch statement while really not
addressing the switch statement at all. The new RFC proposes a match
expression that fixes all the objections raised against the switch
statement. Additionally, match arms can now contain statement lists
which allows you to use the match expression anywhere the switch
statement would have been used previously.

While some people have suggested statement lists aren't necessary I
don't think it makes sense to raise objections against the switch
statement without offering an alternative.

I also experimented with pattern matching but decided against it. The
exact reason is described in the RFC.

I'm now confident this is the right approach. I hope you will be
happier with this proposal.

Happy Easter!

---

## #109591 — G. P. B. — 2020-04-12T00:58:37+00:00

URL: https://externals.io/message/109590#109591 · In reply to: #109590

> Hi internals
>
> I'd like to announce the match expression RFC that replaces the switch
> expression RFC I announced a few weeks ago.
> New: https://wiki.php.net/rfc/match_expression
> Old: https://wiki.php.net/rfc/switch_expression
>
> Due to the feedback I decided to take the RFC in a slightly different
> direction. The main objections were:
>
> 1. It didn't behave like the traditional switch so it shouldn't use
> the switch keyword
> 2. It didn't fix type coercion
> 3. The RFC was poorly structured
>
> In hindsight I understand why I had a hard time writing the RFC. I
> tried making a case against the switch statement while really not
> addressing the switch statement at all. The new RFC proposes a match
> expression that fixes all the objections raised against the switch
> statement. Additionally, match arms can now contain statement lists
> which allows you to use the match expression anywhere the switch
> statement would have been used previously.
>
> While some people have suggested statement lists aren't necessary I
> don't think it makes sense to raise objections against the switch
> statement without offering an alternative.
>
> I also experimented with pattern matching but decided against it. The
> exact reason is described in the RFC.
>
> I'm now confident this is the right approach. I hope you will be
> happier with this proposal.
>
> Happy Easter!
>
> --
> 
> 
>

Hello Ilija,

I think this is a step in the right direction compared to your previous
attempt.
Your reasoning for not including pattern matching in this RFC also makes
sense.
Moreover, this could be added at a future time when it may make more sense.

One small decision that I personally disagree with is the usage of `=>`
compared to using the colon as the switch statement does.
As for me => means assigning a value to a key which isn't the case here
IMHO.
Also, combining this with less/greater or equal than binary operators makes
for a rather confusing line in my eyes.
E.g. Zend/tests/match/004.phpt in your PR, I don't really see the separation
from where condition and where 'case' starts:

Best regards

George P. Banyard

---

## #109592 — Ilija Tovilo — 2020-04-12T09:48:22+00:00

URL: https://externals.io/message/109590#109592 · In reply to: #109591

Hi George

I appreciate your feedback.

> One small decision that I personally disagree with is the usage of `=>` compared to using the colon as the switch statement does.

I picked the `=>` symbol because IMO the extra spacing and wider
symbol visually separates the two sides better. The difference isn't
huge, I don't have a strong preference either way.

> Also, combining this with less/greater or equal than binary operators makes for a rather confusing line in my eyes.

I guess that depends on the lhs. For example, using the ternary
operator has the opposite effect.

```
match (true) {
    // =>
    $cond ? $foo : $bar => $val, // Better
    $val >= 42 => $val, // Worse

    // :
    $cond ? $foo : $bar: $val, // Worse
    $val >= 42: $val, // Better
}
```

Regards,
Ilija

---

## #109593 — txigreman@hotmail.com — 2020-04-12T09:56:29+00:00

URL: https://externals.io/message/109590#109593 · In reply to: #109590

> Hi internals
>
> I'd like to announce the match expression RFC that replaces the switch
> expression RFC I announced a few weeks ago.
> New: https://wiki.php.net/rfc/match_expression
> Old: https://wiki.php.net/rfc/switch_expression
>
> Due to the feedback I decided to take the RFC in a slightly different
> direction. The main objections were:
>
> 1. It didn't behave like the traditional switch so it shouldn't use
> the switch keyword
> 2. It didn't fix type coercion
> 3. The RFC was poorly structured
>
> In hindsight I understand why I had a hard time writing the RFC. I
> tried making a case against the switch statement while really not
> addressing the switch statement at all. The new RFC proposes a match
> expression that fixes all the objections raised against the switch
> statement. Additionally, match arms can now contain statement lists
> which allows you to use the match expression anywhere the switch
> statement would have been used previously.
>
> While some people have suggested statement lists aren't necessary I
> don't think it makes sense to raise objections against the switch
> statement without offering an alternative.
>
> I also experimented with pattern matching but decided against it. The
> exact reason is described in the RFC.
>
> I'm now confident this is the right approach. I hope you will be
> happier with this proposal.
>
> Happy Easter!
Hello Ilija,

I really like much more this new approach. Only a pair of questions:

Would be posible for blocks to require a return statement instead of raising an error?

$y = match($x) {
    0 => ‘a’,
    1 => {
        foo();

        return 'b’; // OK
    }
    2 => {
        var();
    } // Error, return statement is required
}

Would be feasible for the fallthrought problem to use “continue” when you really want to chain “cases”?

match ($x) {
    0 => {
        // Only for 0
        continue; // Same as omitting a break in a traditional switch
    },
   1 => {
       // Same for 0 and 1
    }
}

Regards,
Iván Arias.

---

## #109594 — Ilija Tovilo — 2020-04-12T12:47:47+00:00

URL: https://externals.io/message/109590#109594 · In reply to: #109593

Hi Iván

> Would be posible for blocks to require a return statement instead of raising an error?

It would be possible for the blocks to return values (though not with
the return keyword). I've created a small prototype a few weeks ago:

```
$result = match ($x) {
    0 => {
        echo 'Foo';
        echo 'Bar';
        'Baz'
    },
    ...
};
```

https://github.com/php/php-src/compare/master...iluuu1994:block-expression
Heavily inspired by Rust:
https://doc.rust-lang.org/reference/expressions/block-expr.html

While this would perfectly solve the problem perfectly it feels a
little foreign in PHP. Either way, this is something that can be
discussed an implemented in a separate RFC.

> Would be feasible for the fallthrought problem to use “continue” when you really want to chain “cases”?

Yes, that would be feasible. I personally just don't see a huge
benefit of fallthrough. If we ever implemented pattern matching it
could become unfeasible again (or at least require additional sanity
checks):

```
match ($value) {
    Foo { foo: $foo } => {
        fallthrough;
    }
    Bar { bar: $bar } => {
        // $bar is unbound
    }
 }
```

Ilija

---

## #109595 — Rowan Tommins — 2020-04-12T14:04:15+00:00

URL: https://externals.io/message/109590#109595 · In reply to: #109590

>Hi internals
>
>I'd like to announce the match expression RFC that replaces the switch
>expression RFC I announced a few weeks ago.
>New: https://wiki.php.net/rfc/match_expression
>Old: https://wiki.php.net/rfc/switch_expression

Hi Ilija,

Thanks for continuing to work on this, I think the new syntax feels much more natural when introduced with a new keyword.


> Additionally, match arms can now contain statement lists
>which allows you to use the match expression anywhere the switch
>statement would have been used previously.

I quite strongly disagree with this part, however. I don't think it's necessary for the new keyword to be a replacement for every switch statement, any more than switch replaces every if statement or vice versa, and doing so adds a lot of complexity to the proposal.

In languages where expression blocks with an implicit return are a standard feature, the combination works naturally, but without that we have to add a bunch of special rules:

- Can match arms contain other flow control, such as "return" or "continue"? What if we later want to give those special meaning?
- Can I mix a bare value and a block as arms of the same match, or does the whole construct need to be in either "expression form" or "statement form"? Will this restriction be easy to explain to users?
- Can I omit the trailing semicolon even in "expression form", i.e. if my branches have no braces around, as long as I don't use the result? What will the error message look like if I get this rule wrong?

I also think the use of => and , feels natural when pairing an input to an output, but odd when pairing a test to a block of imperative code. In the "expression form" (no braces, right hand side is an expression evaluated if the branch matches), it matches array syntax (right hand side is an expression immediately evaluated as a value) and short closure syntax (right hand side is an expression evaluated when function is executed). 

In the "statement form", its closest relative would be if-elseif-else, but only if we wrote those like this:

if ($score==10) => {
    echo "Congratulations";
},
elseif ($score==9) => {
    echo "Nearly there";
},
else => {
    echo "Keep trying";
}


Switch statements are different again, but their ancestor is not if blocks but goto labels, which explains both the syntax and the fall-through behaviour:

goto "case_$score" else "default"; // imaginary dynamic goto becomes "switch ($score)"
case_10:
    echo"Congratulations";
    goto end; // becomes "break"
case_9:
    echo "Nearly there";
    goto end;
default:
    echo "Keep trying";
    goto end;
end: // becomes closing brace of switch block


The inability to nest ternary ?: without parentheses makes the single expression form particularly useful in PHP, so I'd love to see the RFC focus on that.

We can always add statement blocks in later, either as a special case as currently proposed, or because we're adding them elsewhere, and perhaps with a way to return a value rather a requirement not to use it.

Regards,

-- 
Rowan Tommins
[IMSoP]

---

## #109596 — txigreman@hotmail.com — 2020-04-12T14:18:08+00:00

URL: https://externals.io/message/109590#109596 · In reply to: #109594

> > […]
>
>It would be possible for the blocks to return values (though not with
>the return keyword). I've created a small prototype a few weeks ago:
>
>```
>$result = match ($x) {
>    0 => {
>        echo 'Foo';
>        echo 'Bar';
>        'Baz'
>    },
>    ...
>};
>```
>
>https://github.com/php/php-src/compare/master...iluuu1994:block-expression
>Heavily inspired by Rust:
>https://doc.rust-lang.org/reference/expressions/block-expr.html
>
>While this would perfectly solve the problem perfectly it feels a
>little foreign in PHP. Either way, this is something that can be
>discussed an implemented in a separate RFC.

My only concern about blocks is that I fell a bit odd that they can only be used
under some circustances. I think I would prefer to simply do not include them
for now, and discuss these “block expressions” in another RFC as they seem to
be an independent language feature.

Regards,
Iván Arias.

---

## #109597 — Mike Schinkel — 2020-04-12T15:04:50+00:00

URL: https://externals.io/message/109590#109597 · In reply to: #109590

I love everything about this, except for one deal killer.

I love the use of =>.  And I love the blocks. 
 
Plus I love that it can fully replace switch because of how using switch can easily allow an developer's oversight to introduce subtle bugs.

The deal killer IMO is this:

"match was added as a keyword (reserved_non_modifiers). This means it can't be used in the following contexts anymore:

	• namespaces
	• class names
	• function names
	• global constants"

-Mike


> 
> 
> Hi internals
> 
> I'd like to announce the match expression RFC that replaces the switch
> expression RFC I announced a few weeks ago.
> New: https://wiki.php.net/rfc/match_expression
> Old: https://wiki.php.net/rfc/switch_expression
> 
> Due to the feedback I decided to take the RFC in a slightly different
> direction. The main objections were:
> 
> 1. It didn't behave like the traditional switch so it shouldn't use
> the switch keyword
> 2. It didn't fix type coercion
> 3. The RFC was poorly structured
> 
> In hindsight I understand why I had a hard time writing the RFC. I
> tried making a case against the switch statement while really not
> addressing the switch statement at all. The new RFC proposes a match
> expression that fixes all the objections raised against the switch
> statement. Additionally, match arms can now contain statement lists
> which allows you to use the match expression anywhere the switch
> statement would have been used previously.
> 
> While some people have suggested statement lists aren't necessary I
> don't think it makes sense to raise objections against the switch
> statement without offering an alternative.
> 
> I also experimented with pattern matching but decided against it. The
> exact reason is described in the RFC.
> 
> I'm now confident this is the right approach. I hope you will be
> happier with this proposal.
> 
> Happy Easter!

---

## #109598 — Larry Garfield — 2020-04-12T19:18:07+00:00

URL: https://externals.io/message/109590#109598 · In reply to: #109590

> Hi internals
> 
> I'd like to announce the match expression RFC that replaces the switch
> expression RFC I announced a few weeks ago.
> New: https://wiki.php.net/rfc/match_expression
> Old: https://wiki.php.net/rfc/switch_expression
> 
> Due to the feedback I decided to take the RFC in a slightly different
> direction. The main objections were:
> 
> 1. It didn't behave like the traditional switch so it shouldn't use
> the switch keyword
> 2. It didn't fix type coercion
> 3. The RFC was poorly structured
> 
> In hindsight I understand why I had a hard time writing the RFC. I
> tried making a case against the switch statement while really not
> addressing the switch statement at all. The new RFC proposes a match
> expression that fixes all the objections raised against the switch
> statement. Additionally, match arms can now contain statement lists
> which allows you to use the match expression anywhere the switch
> statement would have been used previously.
> 
> While some people have suggested statement lists aren't necessary I
> don't think it makes sense to raise objections against the switch
> statement without offering an alternative.
> 
> I also experimented with pattern matching but decided against it. The
> exact reason is described in the RFC.
> 
> I'm now confident this is the right approach. I hope you will be
> happier with this proposal.
> 
> Happy Easter!

This is a substantial improvement over the previous RFC, thank you!

1) The use of => is fine with me.  I'm not bothered by it, but I'm also open to other options like : if there's a strong consensus otherwise.

2) I am also still against block statements in the right-hand side, largely for the same reasons as Rowan.  They're unnecessary and lead to confusion.  In my mind, match expressions are more like a multi-branch ternary than a switch statement.

When I say unnecessary, I mean that very literally.  Because it can take any expression, that means it can simply execute a pre-defined function or anonymous function.

function b() {
  // Something multi-line and complicated.
}

$c = function ($x) {
  // Something multi-line and complicated.
};

match ($x) {
  1 => 'A',
  2 => b(),
  3 => $c($x),
};

That not only alleviates the need to support multi-line blocks, it keeps the match statement itself clearer to understand at-a-glance, and encourages the definition of named, testable, small blocks of code (ie, functions whether anonymous or not), which is a net win on its own.  The overall effect is the same.

And if you really, really need to inline the block for some reason, this is ugly but syntactically valid:

match ($x) {
  1 => 'A',
  2 => b(),
  3 => function() use ($whatever) {
    // Something multi-line and complicated.
  }(),
};

(Incidentally, the same "factor complex expressions out to a function an everyone is better off" applies to the left hand side, too.  That's a good thing.)

I would strongly recommend removing the block statement support, as it just muddies the water.

3) I'm fine with match() always being strict comparison, regardless of the type mode.  However, it should probably be made more explicit in the RFC that it is unaffected by the type mode.

4) Possible addition: Make the match input optional, defaulting to "true".  That is:

match (true) {
  $x < 5 => 'A',
  $x > 10 => 'B',
  $x ==7 => 'C',
  default => 'D',
}

Can be shortened to:

match {
  $x < 5 => 'A',
  $x > 10 => 'B',
  $x ==7 => 'C',
  default => 'D',
}

Since it's an expression it still has all the values available from the scope, so it's just as capable and saves a little typing in that case.

--Larry Garfield

---

## #109599 — Ilija Tovilo — 2020-04-12T20:16:02+00:00

URL: https://externals.io/message/109590#109599 · In reply to: #109595

Hi Rowan

> Can match arms contain other flow control, such as "return" or "continue"?

Yes and yes. They behave exactly the same as in the switch. This
should definitely be described in the RFC.

> Can I mix a bare value and a block as arms of the same match, or does the whole construct need to be in either "expression form" or "statement form"?

Yes, you can mix blocks and expressions given you don't use the return
value of the whole match expression.

> Can I omit the trailing semicolon even in "expression form"

Yes. To clarify what's going on here: There's no statement variant of
the match expression. PHP already allows using any expression as a
statement.
https://github.com/php/php-src/blob/422c8390a01ce9b6f612e0183bd0e4500c0608be/Zend/zend_language_parser.y#L446

That's why you can do something like `10 + 20;`. PHP will just discard
the result value. The same thing is happening here. The only
difference is that I added a rule to the grammar to allow dropping the
semicolon in this case because I noticed that I kept forgetting to add
it in my tests.

> We can always add statement blocks in later

I think we'll never completely agree on this point, and that's fine.
As mentioned in my announcement IMO it doesn't make sense criticizing
the switch statement but then not offering an alternative.

Thanks for your input!

Ilija

---

## #109600 — Ilija Tovilo — 2020-04-12T20:39:20+00:00

URL: https://externals.io/message/109590#109600 · In reply to: #109598

Hi Larry

> That not only alleviates the need to support multi-line blocks, it keeps the match statement itself clearer to understand at-a-glance, and encourages the definition of named, testable, small blocks of code (ie, functions whether anonymous or not), which is a net win on its own.

I'm generally not a fan of this approach. I think it's unrealistic to
expect users to move code into a separate function just because it
takes two lines of code instead of one. People can't be forced into
writing clean code and my fear here is that they will just revert back
to using what is more convenient.

> I'm fine with match() always being strict comparison, regardless of the type mode. However, it should probably be made more explicit in the RFC that it is unaffected by the type mode.

That's a good point, I will add it to the RFC.

> Possible addition: Make the match input optional, defaulting to "true".

This has been proposed before. I do like it but I'm not sure if other people do.

> I would strongly recommend removing the block statement support, as it just muddies the water.

As mentioned in my e-mail to Rowan, we'll probably never agree on this
point. At the end of the day, you might be getting a feature you don't
have to use. It barely adds any complexity to the language but will
make other users happy.

Thanks for you input!

Ilija

---

## #109601 — Rowan Tommins — 2020-04-12T22:03:53+00:00

URL: https://externals.io/message/109590#109601 · In reply to: #109599

>
> > […]
> Yes and yes. They behave exactly the same as in the switch. This
> should definitely be described in the RFC.


You didn't quote the second part of that question, which admittedly was 
a bit rhetorical, but important: allowing these rules out using either 
of those keywords in future extensions of this syntax. That means if we 
want to add a way to get a value out of a statement block, we can't use 
"return"; and if we want to add explicit fallthrough, we can't use 
"continue".

Also note that in switch, "continue" and "break" are actually synonyms, 
both jumping to the end of the switch block (see also 
https://wiki.php.net/rfc/continue_on_switch_deprecation). I'm not sure 
that's actually all that intuitive or useful in the proposed match 
statement.


> > […]
> Yes, you can mix blocks and expressions given you don't use the return
> value of the whole match expression.


Again, you skipped the second part of the question - will this make 
sense to users? What error message will they get if they write this:

$x = match($y) { 1 => "Hello", 2 => "Goodbye", 3 => { throw new 
Exception; } };

(If https://wiki.php.net/rfc/throw_expression passes, then "3 => throw 
new Exception" without the braces will presumably be valid, but that 
just makes it even more confusing, IMO.)


> > […]
> Yes.


So this would be valid PHP?

$x = match($y) { 1 => "Hello", 2 => "Goodbye" } echo $y;


> To clarify what's going on here: There's no statement variant of
> the match expression [...]


I don't think users will see it that way. An "expression" where you 
can't use the result (but can use flow control like "throw" and 
"return") feels very much like a statement, regardless of how the parser 
defines it.


> ... because I noticed that I kept forgetting to add it in my tests.


I think needing to add a special case to the grammar is a sign that the 
proposed syntax doesn't fit well with the rest of the language. Did you 
ever forget to put the semicolon when using it in expression context, or 
only when using statement blocks?


> As mentioned in my announcement IMO it doesn't make sense criticizing
> the switch statement but then not offering an alternative.


I don't think this is true. If you were proposing "foreach", you might 
criticize the "for" statement, but that doesn't mean you'd extend 
"foreach" so that it could replace every single "for" statement.

To reiterate, I think the match expression - with no statement blocks - 
stands up really well as a replacement for those switch statements where 
you're deciding on a value, and for nested ternaries (which are pretty 
much unused in PHP due to the broken precedence).

Other proposals can replace other uses of switch, or switch can live on 
with more limited use - after all, we even have a "goto" statement in 
PHP, for those rare occasions where *none* of the built-in flow control 
is good enough.


To respond to something you said to Larry:

> People can't be forced into
> writing clean code and my fear here is that they will just revert back
> to using what is more convenient.


That's their loss! Whether or not "match" supports blocks, some people 
won't use it, just as some people write unnecessarily complicated if 
statements because they don't spend the time structuring them with 
elseif or switch.

My concern is that if match supports blocks, but the syntax and 
behaviour is unintuitive, we'll be stuck with another feature that 
nobody likes very much but we can't easily replace. Worse, the RFC might 
lose support based on that part, and we'd miss out on getting a really 
nice new expression.


Regards,

-- 
Rowan Tommins (né Collins)
[IMSoP]

---

## #109602 — Ilija Tovilo — 2020-04-13T08:38:10+00:00

URL: https://externals.io/message/109590#109602 · In reply to: #109601

Hi Rowan

> That means if we want to add a way to get a value out of a statement block,
> we can't use "return"; and if we want to add explicit fallthrough, we can't
> use "continue".

And we probably shouldn't do that. return means return from the
function, it makes little sense to change it in one specific context.
We'd either need a different keyword (like pass) or some syntax that
doesn't require a keyword at all (like the block expressions I've
mentioned). The same goes for continue. A keyword like fallthrough
would be much more fitting.

> Again, you skipped the second part of the question - will this make sense to
> users? What error message will they get if they write this:
>
> $x = match($y) { 1 => "Hello", 2 => "Goodbye", 3 => { throw new
> Exception; } };

It's described in the RFC:

//> Fatal error: Match expressions that utilize the result value can't
contain statement lists

> So this would be valid PHP?
>
> $x = match($y) { 1 => "Hello", 2 => "Goodbye" } echo $y;

No. A semicolon is needed. Here the semicolon belongs to the
assignment, not the match. The parsing would be done somewhat like
this:

* Expression statement <- Requires a semicolon
    * Assignment
        * $x
        * match

The only case where expression statement doesn't require a semicolon is here:

* Expression statement <- Doesn't require a semicolon
    * match

Because match is found directly under the expression statement.

> I think needing to add a special case to the grammar is a sign that the
> proposed syntax doesn't fit well with the rest of the language.

I find it odd that people keep referring to Rust but apparently have
no clue how it works. This is precisely what they do.

https://doc.rust-lang.org/reference/statements.html#expression-statements

ExpressionStatement :
      ExpressionWithoutBlock ;
    | ExpressionWithBlock

A lot of our last conversation is repeating and very little new has
been said. The only productive thing is to move on. I think this RFC
satisfies your needs. It has some extra parts you don't need, and
that's fine.

Thanks again for taking the time to read the RFC and provide your feedback!

Ilija

---

## #109603 — Rowan Tommins — 2020-04-13T10:45:18+00:00

URL: https://externals.io/message/109590#109603 · In reply to: #109602

>It's described in the RFC:
>
>//> Fatal error: Match expressions that utilize the result value can't
>contain statement lists


Thanks, I missed that. Reasonably clear, I guess, although I imagine there'll be questions on Stack Overflow asking what a "statement list" is.



> > […]
>
>No. A semicolon is needed. Here the semicolon belongs to the
>assignment, not the match. 
...
>The only case where expression statement doesn't require a semicolon is
>here:
>
>* Expression statement <- Doesn't require a semicolon
>    * match


Right, so I go back to my earlier point that there are basically two forms of match proposed:

- one where you can use it anywhere an expression is expected, with no statement blocks
- one which can be used as a standalone statement, which can contain statement blocks, and which doesn't need a trailing semicolon


> > […]
>the
> > […]
>
>I find it odd that people keep referring to Rust but apparently have
>no clue how it works. This is precisely what they do.
>
>https://doc.rust-lang.org/reference/statements.html#expression-statements


I didn't mention Rust, and am fully aware that I don't know how its syntax works. What I said was that the proposed syntax doesn't fit into PHP easily.

Two things stand out to me following that link:


Firstly, block expressions are a foundational part of the Rust language, not a special case used in only one place. They're used as the basis for everything from if statements to async blocks, all of which evaluate to a value. That's a really neat design feature, but not something that exists in PHP.

It also makes the semicolon rule somewhat more natural: it makes *all* the control flow blocks in Rust feel more natural to developers coming from other languages. It's not an ad hoc rule for one expression, it's a general rule across the language.



Secondly, the page you linked calls out an ambiguity caused by omitting the semicolon, which would apply equally in PHP:

match($x) { 1 => ['foo', 'bar'] }
[0];

It then explains the important restriction of only omitting the semicolon if the result is void/null rather than a concrete value. An equivalent in PHP would be to only allow omitting the semicolon if every arm of the match is a statement list, further distinguishing the expression and statement forms.



> I think this RFC
>satisfies your needs. It has some extra parts you don't need, and
>that's fine.

Just to be clear, that may be fine with you, but if I had a vote, I would probably vote no to the current proposal, because I actively dislike the proposed syntax and semantics of statement blocks. They "poison the barrel" for me. That's a real shame, because I really like the core of the proposal.


Regards,

-- 
Rowan Tommins
[IMSoP]

---

## #109604 — Ilija Tovilo — 2020-04-13T11:28:41+00:00

URL: https://externals.io/message/109590#109604 · In reply to: #109603

> Firstly, block expressions are a foundational part of the Rust
> language, not a special case used in only one place.

From a previous e-mail:

> It would be possible for the blocks to return values (though not with
> the return keyword). I've created a small prototype a few weeks ago:
>
> https://github.com/php/php-src/compare/master...iluuu1994:block-expression
> Heavily inspired by Rust:
> https://doc.rust-lang.org/reference/expressions/block-expr.html
>
> While this would perfectly solve the problem perfectly it feels a
> little foreign in PHP. Either way, this is something that can be
> discussed an implemented in a separate RFC.

We can't do everything at once. The current block syntax is completely
compatible with that suggestion. All we'd have to do is relax the
restriction of only allowing blocks when the result isn't used.

> it makes *all* the control flow blocks in Rust feel more natural to
> developers coming from other languages.

Same thing here. If you don't use the result value, it looks just like
the switch. That's why I'd feel odd to require a semicolon.

> the page you linked calls out an ambiguity caused by omitting the
> semicolon

This code is parsed like this:

```
match($x) { 1 => ['foo', 'bar'] }
[0];
```

* statement list
    * match expr
    * array literal

Note that we can't have ambiguous grammar since Bison would
immediately expose it.

> It then explains the important restriction of only omitting the
> semicolon if the result is void/null rather than a concrete value.

That's true. Unfortunately we don't have this info at compile time.
That's why we throw away the expression result just like with any
other expression statement.

> I would probably vote no to the current proposal

I understand. Everybody is entitled to their opinion. If the vote
fails that doesn't mean we'll just completely give up. I would
reiterate and try again. Sadly, it's very hard to get a feel for how
many people have which opinion through the mailing list.

Ilija

---

## #109606 — Rowan Tommins — 2020-04-13T14:49:36+00:00

URL: https://externals.io/message/109590#109606 · In reply to: #109604

> > […]
> We can't do everything at once.


Then why not introduce the match expression first, and add block 
expressions (as a general concept) later? That way, we don't need all 
the special restrictions on when to use them, and can work out a 
consistent set of rules for them which can apply language-wide, rather 
than being constrained later by decisions we make half-implementing them 
now.

The ability to use them with short closure syntax would be very 
interesting, if the scoping/capture rules could be agreed.


> > […]
> Same thing here. If you don't use the result value, it looks just like
> the switch. That's why I'd feel odd to require a semicolon.


Not really. In Rust, it's about making a whole bunch of control 
structures, which are already consistent with each other, more user 
friendly (but still consistent). In your proposal, it's about making one 
specific control structure look slightly more like other syntaxes in the 
same language, by adding a special case which applies nowhere else.

To be specific, in PHP, there is no "omitted semicolon" at the end of 
"if ($x) { y(); }" - that is just how the syntax is defined. There's no 
need to have a parser rule to allow it to look like C or Java, because 
it already does.


> This code is parsed like this:
>
> ```
> match($x) { 1 => ['foo', 'bar'] }
> [0];
> ```
>
> * statement list
>      * match expr
>      * array literal
>
> Note that we can't have ambiguous grammar since Bison would
> immediately expose it.


I'm not sure what you mean by "we can't have ambiguous grammar" - the 
code above *is* ambiguous, in that it could be defined to mean one of 
two things; what you've shown is which definition your implementation 
defines.

That resolution makes sense for that example, but consider some others:

// As proposed, parsed as two meaningless expression-statements; as a 
normal expression, would select and then invoke a callable
match($x) { 1 => 'print', 2 => 'var_dump' }
($x);

// Invalid under the proposed rule, but a valid method call if match was 
always a normal expression
match($x) { 1 => new Foo, 2 => new Bar }
->doSomething();


To be fair, the same limitation exists for closures, where this is invalid:

function($x) { echo $x; } ("Hello");

and you have to write this instead:

(function($x) { echo $x; }) ("Hello");


So I guess the above would follow the same rule to force expression context:

(match($x) { 1 => 'print', 2 => 'var_dump' })($x);

(match($x) { 1 => new Foo, 2 => new Bar })->doSomething();

The only downside is that omitting the parentheses wouldn't be an error, 
as with the closure case, it would just silently do nothing, which might 
be rather confusing. Dropping the special semicolon handling would mean 
it either did the expected thing or gave a parse error straight away.


Regards,

-- 
Rowan Tommins (né Collins)
[IMSoP]

---

## #109607 — David Rodrigues — 2020-04-13T15:08:57+00:00

URL: https://externals.io/message/109590#109607 · In reply to: #109606

With all the humility of the world and without wanting to be exhaustive
about this, my only question is why can't we keep it as a switch, instead
of creating a new keyword?

$x = switch ($y) {
    case 0: return 1;
    case 1: return 20;
    // default: return null;
};

I say this because, in the future, we could do something similar for if():

$x = if ($y instanceof Foo) {
    return $y->bar();
} else if ($y instanceof Bar) {
    return $y->foo();
}; // else { return null; }

Or even for loopings:

$x = foreach ($items as $item) {
    yield $item;
}; // $x == $items

So we would not need to create a new keyword for each equivalent type when
used as an expression.

The only reason would be something like "switch has no return support", but
this could happen exclusively in this scope, just as "use ()" exists only
in functions and not in methods, which are basically the same thing,
however, in different scopes. Likewise, "break 2" would be impossible in
this case, so just issue an error saying "break n is not supported in this
situation".


Atenciosamente,
David Rodrigues


Em seg., 13 de abr. de 2020 às 11:49, Rowan Tommins <rowan.collins@gmail.com>
escreveu:

> 
> > […]
>
>
> Then why not introduce the match expression first, and add block
> expressions (as a general concept) later? That way, we don't need all
> the special restrictions on when to use them, and can work out a
> consistent set of rules for them which can apply language-wide, rather
> than being constrained later by decisions we make half-implementing them
> now.
>
> The ability to use them with short closure syntax would be very
> interesting, if the scoping/capture rules could be agreed.
>
>
> > […]
>
>
> Not really. In Rust, it's about making a whole bunch of control
> structures, which are already consistent with each other, more user
> friendly (but still consistent). In your proposal, it's about making one
> specific control structure look slightly more like other syntaxes in the
> same language, by adding a special case which applies nowhere else.
>
> To be specific, in PHP, there is no "omitted semicolon" at the end of
> "if ($x) { y(); }" - that is just how the syntax is defined. There's no
> need to have a parser rule to allow it to look like C or Java, because
> it already does.
>
>
> > […]
>
>
> I'm not sure what you mean by "we can't have ambiguous grammar" - the
> code above *is* ambiguous, in that it could be defined to mean one of
> two things; what you've shown is which definition your implementation
> defines.
>
> That resolution makes sense for that example, but consider some others:
>
> // As proposed, parsed as two meaningless expression-statements; as a
> normal expression, would select and then invoke a callable
> match($x) { 1 => 'print', 2 => 'var_dump' }
> ($x);
>
> // Invalid under the proposed rule, but a valid method call if match was
> always a normal expression
> match($x) { 1 => new Foo, 2 => new Bar }
> ->doSomething();
>
>
> To be fair, the same limitation exists for closures, where this is invalid:
>
> function($x) { echo $x; } ("Hello");
>
> and you have to write this instead:
>
> (function($x) { echo $x; }) ("Hello");
>
>
> So I guess the above would follow the same rule to force expression
> context:
>
> (match($x) { 1 => 'print', 2 => 'var_dump' })($x);
>
> (match($x) { 1 => new Foo, 2 => new Bar })->doSomething();
>
> The only downside is that omitting the parentheses wouldn't be an error,
> as with the closure case, it would just silently do nothing, which might
> be rather confusing. Dropping the special semicolon handling would mean
> it either did the expected thing or gave a parse error straight away.
>
>
> Regards,
>
> --
> Rowan Tommins (né Collins)
> [IMSoP]

---

## #109609 — David Rodrigues — 2020-04-13T17:01:11+00:00

URL: https://externals.io/message/109590#109609

But when we do:

function x() {
   $a = function () { return 123; }
}

We know that "return" here is for the current function () scope, and not
for the parents one. So "return" inside inlined-switch should be used to
specify the switch return itself. Seems clear to me.


Atenciosamente,
David Rodrigues


Em seg., 13 de abr. de 2020 às 12:32, Reindl Harald <h.reindl@thelounge.net>
escreveu:

>
>
> Am 13.04.20 um 17:08 schrieb David Rodrigues:
> > […]
>
> because when someone changes behavior where return is expected to return
> from a function/method someone could break his fingers?
>
> return means "stop function or include" and not "stop switch statement"

---

## #109610 — Larry Garfield — 2020-04-13T17:31:45+00:00

URL: https://externals.io/message/109590#109610 · In reply to: #109607

> With all the humility of the world and without wanting to be exhaustive
> about this, my only question is why can't we keep it as a switch, instead
> of creating a new keyword?

That was the original proposal.  The main issue came down to it being too much different functionality crammed into one bit of syntax, where lots of subtle little context would change the meaning and what you had to do.  That's difficult for users, and for the parser.

Fundamentally, this is not a switch statement.  I think it is an error to equate it to or relate it to a switch statement.  It's a more powerful, multi-branch version of the ternary operator, and should be conceptualized as such.  And conceptualized that way, I really want it. :-)

Piggybacking off of if makes slightly more sense than off of switch, but it then involves a lot more syntax and a lot more typing, plus the confusion about when it needs a semi-colon and when it doesn't.  

A new keyword creates a mental separation that is beneficial to users, and allows it to be implemented with a minimum of syntax and no conditional syntax (where certain sigils are needed only in some situations and are an error in others).


> Em seg., 13 de abr. de 2020 às 11:49, Rowan Tommins <rowan.collins@gmail.com>
> escreveu:
> 
> > […]

I really feel like this is the best solution.  Multi-line expressions are not a logical one-off part of match().  They may or may not be a good idea for PHP generally, in which case they should be proposed and thought through generally.  If they do end up being a good move generally, they'll apply to match naturally just like everywhere else; if not, then they wouldn't confuse people by being a one-off part of match() and nowhere else.

The various discussion about parse logic when the semicolon is there or not only highlights that it is not a fully-developed concept.  There's a lot more thought and design that needs to go into multi-line expressions that is not in scope for a match expression; embedding statements inside an expression is just weird...

Please, pull that part out.  It's the most (only?) controversial part right now.  I suspect (note: no data) that the RFC would pass almost unanimously without it (which is good; I want this RFC to pass).  With it, it may pass or not, but it would be a weaker proposal.

At the very least bump it to an secondary add-on vote.

--Larry Garfield

---

## #109611 — Ilija Tovilo — 2020-04-13T20:11:39+00:00

URL: https://externals.io/message/109590#109611 · In reply to: #109610

> Please, pull that part out.

Guys. You've made your opinions loud and clear. But I'm not just
building this for you, I'm also building it for others and myself.

> With it, it may pass or not, but it would be a weaker proposal.

Maybe, maybe not. You're assuming people will share your opinion but
that is not just a given. We probably won't find out until this is put
to a vote.

Ilija

---

## #109612 — Ilija Tovilo — 2020-04-13T21:51:48+00:00

URL: https://externals.io/message/109590#109612 · In reply to: #109606

Hi Rowan

> Then why not introduce the match expression first, and add block
> expressions (as a general concept) later?

Mainly because I fear it won't pass and we'll end up with a
handicapped match expression that can't be used half the time.

> That way, we don't need all the special restrictions on when to use them

I think that's a little overblown. We're talking about ~5 lines here.

> the code above *is* ambiguous

Whether or not some code is ambiguous depends on the grammar that
defines how it's interpreted. "1 + 2 * 3" can be ambiguous if the
precedence isn't clearly defined. Bison will check that your grammar
is unambiguous, otherwise you'll get a shift/reduce or reduce/reduce
error (as in there's multiple ways to parse your code). The suggested
grammar defines that the semicolon can be dropped under exactly one
circumstance: When the match is the first and thus only element of an
expression statement. This is what Rust does too. This clearly needs
to be described better in the RFC.

> The only downside is that omitting the parentheses wouldn't be an error,
> as with the closure case, it would just silently do nothing, which might
> be rather confusing.

That is true. Since array subscripts and function calls don't allow
arbitrary lhs expressions the code wouldn't work without parentheses
but at least you'd get a parser error.

Ilija

---

## #109613 — Andrea Faulds — 2020-04-13T23:39:22+00:00

URL: https://externals.io/message/109590#109613 · In reply to: #109590

Hi Ilja,

Ilija Tovilo wrote:
> Hi internals
> 
> I'd like to announce the match expression RFC that replaces the switch
> expression RFC I announced a few weeks ago.
> New: https://wiki.php.net/rfc/match_expression

I like this proposal in general, I've wanted something like Haskell and 
Rust's case/match statements for years but never got round to proposing 
them. I do have some comments and concerns however:

* While I like the Rust-like feature of being able to use it both as a
   statement and as an expression, I share others' concern that it is
   inconsistent with PHP's existing statements. I would suggest either
   an RFC to apply this to other statements, or to take it out for now.

* It is a shame you don't suggest taking this opportunity to add pattern
   matching. We already have destructuring assignment syntax in PHP,
   albeit only for arrays, so why not support pattern-matching for arrays
   in `match` right now? I guess variable scope might be awkward (matched
   values would leak into function scope), but it is for other statements
   already. If we do not add pattern matching right now, perhaps we can
   design the syntax so it doesn't prevent adding it later? Using a
   keyword prefix (e.g. `let`) in future means we end up with two kinds
   of arm (one with === behaviour, one with pattern-matching behaviour),
   but wouldn't it be simpler to have just one?

* Relatedly, it is a shame not to have guards. `switch (true)` is not a
   very nice idiom, `match (true)` is worse (no handling of truthiness),
   and neither provides the full power that patterns + guards together
   provide, where you can neatly combine pure value matching with
   arbitrary boolean checks. Sure, you can write `($foo === BAR) =>`,
   but you might as well use an if-statement then. I shouldn't let
   perfect be the enemy of the good, but I think there's so much more
   that could be done here. Note that even the limited possible patterns
   without inventing new syntax (a plain variable, and an array pattern)
   are more useful if guards are available.

* It is unfortunate if we have to add another reserved word… I don't
   know if there'd be a way to do this with `switch` that isn't
   confusable with the existing statement, though.

Thanks,
Andrea

---

## #109640 — Ilija Tovilo — 2020-04-14T17:23:27+00:00

URL: https://externals.io/message/109590#109640

Hi Andrea

I realize there's a lot of noise in the mailing list right now, I'll
keep this my only e-mail for today.

> I share others' concern that it is inconsistent with PHP's
> existing statements

Can you elaborate on what exactly the concerns are? Note that even if
we added block expressions to the language there are still certain
sanity checks we'd likely need to make, so the differentiation between
statement/expression would still not go away. For example:

```
match ($y) {
    1 => {
        echo 'Foo';
        echo 'Bar';
        // This is fine
    },
}

$x = match ($y) {
    1 => {
        echo 'Foo';
        echo 'Bar';
        // Error, block must return a value.
    },
};
```

At the moment there are very limited use cases for the block
expression. The only ones I can think of are the match expression,
arrow functions and maybe normal functions. And as that would
introduce two ways to return a value from a function it's questionable
whether we should even allow that or not.

```
$arrowFn = fn() => {
    echo 'Foo';
    'Bar'
};

// Questionable. You're saving a few characters
function getFoo() {
    echo 'Foo';
    $this->foo
}
```

> It is a shame you don't suggest taking this opportunity to add
> pattern matching.

My main concern here is just complexity. There's so much to consider.
We need to think well about each pattern, how it should work, what it
should look like, how it should be implemented, etc. Furthermore
pattern matching usually isn't restricted to the match expression.
There's often pattern matching for `if`, `while`, `foreach`, function
params, normal assignment, etc. So I don't think it should be mixed
with this RFC. IMO if we implement pattern matching we should make it
available for all of these cases.

```
let [string $x, 10] = ['foo', 20]; // Error: Unmatched pattern

if (let Foo { bar: $bar } = $foo) {}

while (let 1..<10 = $x) {}
```

> Using a keyword prefix (e.g. `let`) in future means we end
> up with two kinds of arm (one with === behaviour, one with
> pattern-matching behaviour), but wouldn't it be simpler to
> have just one?

I personally don't think so. Consider this case:

```
$x = 10;
$y = 20; // This variable is unused

match ($x) {
   $y => { // Always true
      echo $y; // Outputs 10
   },
}
```

`$y` is an identifier pattern and it always matches and assigns the
given value to the variable. This is rather confusing. A keyword like
`let` would make it more obvious that you're using a pattern. I'd also
suspect that it's more common to pass expressions to the lhs of a
match statement than patterns so it makes sense that this is the
default.

Also, imagine you want to equate multiple dynamic values with each other:

```
$x = ...;
$y = ...;
$z = ...;

match ($x) {
    $y => ...,
    $z => ...,
}

// If we only have pattern matching
match (true) {
    true if $x === $y => ...,
    true if $x === $z => ...,
}
```

Without allowing dynamic lhs expressions this becomes pretty awkward.

> Relatedly, it is a shame not to have guards

I don't think guards are awfully useful without pattern matching.
What's the benefit over this?

```
match ($x) {
    1 => {
        if ($foo === BAR) {
            ...
        } else {
            ...
        }
    },
}

// vs

match ($x) {
    1 if $foo === 'Bar' => {
        ...
    },
    1 => {
        ...
    },
}
```

That just makes it harder to generate a jump table. It does reduce
nesting a bit but the same could be said for if statements in loops
where we don't have guards.

> It is unfortunate if we have to add another reserved word

My previous draft was mainly criticized because of the usage of the
`switch` keyword.

Ilija

---

## #109643 — Andrea Faulds — 2020-04-14T20:48:23+00:00

URL: https://externals.io/message/109590#109643 · In reply to: #109640

Hi Ilija,

Ilija Tovilo wrote:
> > […]
> 
> Can you elaborate on what exactly the concerns are?

Well, I don't think we have any other expressions that are also 
statements with very slightly different syntax, and in this RFC you 
propose that the expression and statement forms have different behaviour 
(expression doesn't support blocks) despite looking the same. So it's 
neither consistent with other statements and expressions, nor is it 
internally consistent.
> > […]
> 
> My main concern here is just complexity. There's so much to consider.
> We need to think well about each pattern, how it should work, what it
> should look like, how it should be implemented, etc. Furthermore
> pattern matching usually isn't restricted to the match expression.
> There's often pattern matching for `if`, `while`, `foreach`, function
> params, normal assignment, etc. So I don't think it should be mixed
> with this RFC. IMO if we implement pattern matching we should make it
> available for all of these cases.

We already have a limited kind of pattern matching in PHP, destructuring 
assignment for arrays. You can use it on the left-hand side of any 
assignment, and also in `foreach`. This pattern can even fail to match, 
but you get an `E_NOTICE` instead of a Throwable.

It might be nice to have it in some other places, but it isn't 
necessary. Haskell itself only has it in function definitions, 
assignments and `case` expressions IIRC, and the former two uses are 
essentially sugar over use of `case` anyway.

Why not take what we have here and support it in `match` too, but with 
slightly stricter rules so that cases that would otherwise trigger an 
 `E_NOTICE` lead to choosing a different branch? It would make both our 
existing pattern-matching and `match` more powerful! Consider 
interacting with some JSON API:

match (json_decode($response)) {
     ['error' => ['code' => $code, 'msg' => $msg] => {
         throw new Exception($msg, $code);
     },
     ['result' => $result] => {
         return $result;
     },
     // No default, so if the JSON doesn't fit this expected format, an 
error is thrown! :)
}

This is just a quick example that came to mind, which doesn't really use 
the full potential available here.

Another kind of existing pattern matching is arguably `catch` in 
exception handling, so maybe we could also have `SomeClass $obj` as a 
pattern, though that syntax would lead to questions of whether things 
like `?SomeClass`, `int` and `SomeClass|SomeClass2` should work…

> > […]
> 
> I personally don't think so. Consider this case:
> 
> ```
> $x = 10;
> $y = 20; // This variable is unused
> 
> match ($x) {
>     $y => { // Always true
>        echo $y; // Outputs 10
>     },
> }
> ```
> 
> `$y` is an identifier pattern and it always matches and assigns the
> given value to the variable. This is rather confusing. A keyword like
> `let` would make it more obvious that you're using a pattern. I'd also
> suspect that it's more common to pass expressions to the lhs of a
> match statement than patterns so it makes sense that this is the
> default.

It would be a bit surprising if you are new to the `match` statement and 
had not used something similar in another language, indeed. But how 
often do people use `switch` with cases like this that don't use a 
constant or literal value? It's not even supported in some popular 
languages like C, and in the rare case that you need this behaviour, a 
guard can be used:

match ($x) {
     default if ($x === $y) => {
         echo $y;
     }
}

By the way, having one kinds of arm would mean you don't have to think 
about the two kinds when reading code like this:

match ($x) {
     $y => {
        // …
     },
     let $y => {
        // …
     },
}

> 
> Also, imagine you want to equate multiple dynamic values with each other:
> 
> ```
> $x = ...;
> $y = ...;
> $z = ...;
> 
> match ($x) {
>      $y => ...,
>      $z => ...,
> }
> 
> // If we only have pattern matching
> match (true) {
>      true if $x === $y => ...,
>      true if $x === $z => ...,
> }
> ```

True, that is less elegant. But when would you need to do that?

Thanks,
Andrea

---

## #109645 — Ilija Tovilo — 2020-04-15T11:03:58+00:00

URL: https://externals.io/message/109590#109645

Hi Andrea

> Well, I don't think we have any other expressions that are also
> statements with very slightly different syntax

The syntax isn't actually different. We don't have different grammar
for the match statement and expression. There's only one. Think of it
more like a type check. In other languages you couldn't use the result
value of a `void` function (PHP is a little different here since
`void` functions return `null`). Similarly using the result of `{ ...
}` doesn't make sense (as it has none) so we throw a compilation
error. Alternatively we could return `null` here too but I'd really
prefer not to.

> We already have a limited kind of pattern matching in PHP

While that's true I don't think the array pattern should be
implemented in the same way. There's a lot to think about here. For
example:

```
// Traditional array destructuring
[$a, $b] = [1, 2, 3];
//> $a === 1
//> $b === 2
```

This is usually not how array patterns work. The array size is critical:

```
let [$a, $b, $c] = [1]; // Unmatched pattern error
let [$a] = [1, 2]; // Unmatched pattern error

let [$a, $b, $c] = [1, 2, 3]; // Ok
let [$a, ...] = [1, 2]; // Ok
```

There are more things to think about like allowing
`ArrayAccess&Countable`, order, `[$x, ...$y]`, etc. If we get the
details wrong it might be hard to correct them later. Another
challenge is emitting efficient opcodes. Consider this example:

```
let [1, 2, $c] = $value;

// Is roughly equivalent to:

if (
    !is_array($value)
    || count($value) !== 3
    || !isset($value[0])
    || $value[0] !== 1
    || !isset($value[1])
    || $value[1] !== 2
    || !isset($value[2])
) {
    throw new UnmatchedPatternError();
}

$c = $value[2];
```

Since PHP (often) doesn't have enough type information at compile time
the number of opcodes can explode very quickly due to many runtime
checks. I don't know how we would best tackle this yet. Another issue
is scoping that is pretty hard to solve in PHP.

```
$x = 10;

match ([1, 2]) {
    let [$x, 3] => ...,
    default => ...,
}

// $x is now 1 even though the pattern did not match
```

The values shouldn't be assigned until after the pattern has matched
which means more complexity and less efficiency.
I hope you can see now why I'm hesitant here.

> It would be a bit surprising if you are new to the `match` statement

So surprising in fact I'm willing to bet 90% would get it wrong the
first time (if uninstructed, of course).

> True, that is less elegant. But when would you need to do that?

Anytime you would've written code like this:

```
if ($x === $foo) {
    $y = ...;
} elseif ($x === $bar) {
    $y = ...;
}
```

This is not uncommon at all. With match + arbitrary lhs expressions
you can replace it with:

```
$y = match ($x) {
    $foo => ...,
    $bar => ...,
};
```

The switch probably wouldn't have been used here because it's even
more verbose than the if (and more error prone).

```
switch ($x) {
    case $foo:
        $y = ...;
        break;
    case $bar:
        $y = ...;
        break;
}
```

Ilija

---

Next page: https://externals.io/message/109590.md?page=2
