Re: [RFC] Short-match
| From: | Claude Pache | Date: | Thu, 17 Dec 2020 16:39:37 +0000 |
| Subject: | Re: [RFC] Short-match | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-112540@lists.php.net to get a copy of this message | ||
> Le 17 déc. 2020 à 17:23, Sara Golemon <pollita@php.net> a écrit :
>
> On Wed, Dec 16, 2020 at 6:50 PM someniatko <someniatko@gmail.com> wrote:
>>
>>
match is an expression, where as if-else construction is
>> not. This
>> allows for combining it with a potential future feature of single line
>> functions and methods. For example (hypothetical syntax is used):
>>
>> ```
>> $getNumber = fn(int $number) => match {
>> $number < 0 => NumberKind::NEGATIVE,
>> $number == 0 => NumberKind::ZERO,
>> $number > 0 => NumberKind::POSITIVE,
>> };
>> ```
>>
>
> That does read attractively, yes. This is the example that should have
> been offered first as it shows the expression nature shining.
>
> To contrast that with what would be possible now in an expressive
> functional form:
>
> $getNumber = fn(int $number) => [
> -1 => NumberKind::NEGATIVE,
> 0 => NumberKind::ZERO,
> 1 => NumberKind::POSITIVE,
> ][$number <=> 0];
>
> The match form *certainly* reads more naturally than the spaceship indexing
> form even though both take up equal space.
>
> -Sara
If you mean a version of if that works in expressions, there already exists a standard
operator for that. Once its historical associativity goof is definitely fixed, you will be able to
write:
```
$getNumberKind = fn(int $number) =>
$number > 0 ? NumberKind::POSITIVE :
$number == 0 ? NumberKind::ZERO :
$number < 0 ? NumberKind::NEGATIVE :
throw new \TypeError;
```
There is a semantic advantage of match over ? : , though, namely its
exhaustivity: You don’t need to add a “panic” default case in order to catch logic errors.
—Claude