Re: [RFC] switch expression
| From: | Larry Garfield | Date: | Wed, 25 Mar 2020 14:59:43 +0000 |
| Subject: | Re: [RFC] switch expression | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-109294@lists.php.net to get a copy of this message | ||
On Wed, Mar 25, 2020, at 9:27 AM, Ilija Tovilo wrote:
> Hi Michał
>
>
>
> I’m sorry, unfortunately I missed your e-mail and RFC.
>
> Let me know if you’re still working on it and I’ll back off of course.
>
>
>
> Regards
I like the concept, and it looks like you're both on a similar track. Give or take details, I
would very much like to see something like it.
One possible improvement to either version is allowing an expression on the left side. That is,
rather than doing an equality match, do a boolean match. That would then allow:
$foo = switch($bar) {
case $bar < 5 => $bar * 3;
case $baz < 10 => $bar * 4;
default => $bar * 5;
};
That would sidestep the need for pattern matching, as you can do anything an expression can do. The
obvious caveat of course is figuring out how to reference the variable being switched on, if
it's not already a variable. My first thought there is to borrow the $$ variable name from
Sara's old function composition proposal, but there may be others. There's likely other
issues to discuss here but allowing expressions on the left would greatly improve the expressiveness
of the construct.
I'd prefer to not allow multi-line statements on the right, ie, blocks. That leads to too much
potential for long and ugly code, which a construct like this should be avoiding. Limiting it to a
single expression keeps it compact; if you have more involved logic, then put it in a function and
your expression is just... calling that function. Problem solved..
Side note: I did a limited user-space implementation of the same concept a while back:
https://hive.blog/php/@crell/type-matching-in-php
But I'd definitely rather see it in the native syntax.
--Larry Garfield