Re: Re: [RFC] Arrow functions / short closures
| From: | Theodore Brown | Date: | Fri, 15 Mar 2019 21:44:26 +0000 |
| Subject: | Re: Re: [RFC] Arrow functions / short closures | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-104761@lists.php.net to get a copy of this message | ||
On Fri, March 15, 2019 at 4:45 AM Josh Di Fabio <joshdifabio@gmail.com> wrote:
> I'd certainly be on board with the fn() syntax, but the backslash
> syntax has definitely grown on me. To me, all of the examples in
> Theodore's email are very readable and I find that the backslash makes
> it very easy to identify arrow functions when grokking.
>
>
array_filter($numbers, \$n => $n % 2);
> vs.
> array_filter($numbers, fn($n) => $n % 2);
>
> When grokking these two pieces of code, I immediately see \$n => $n % >
> 2
> as a single unit, whereas in the latter example I instinctively
> (and incorrectly) interpret "fn($n)" as an expression.
>
> When parens are required, the difference is obviously reduced, but I
> think I still prefer the backslash syntax since the LHS doesn't grok
> as a function call.
>
> reduce($numbers, \($x, $y) => $x + $y);
> vs.
> reduce($numbers, fn($x, $y) => $x + $y);
>
> That said, I'd personally take either syntax gladly.
You have a good point about fn() looking like an expression.
That said, since it would be a keyword IDEs will highlight it
differently which should help avoid confusion.
Regarding the backslash syntax, I forgot to check how it looks with
by-reference passing and returning before I sent my email. Here are
those examples:
```php
fn(&$x) => $x;
fn&($x) => $x;
// vs.
\(&$x) => $x;
\&($x) => $x;
// unclear if passing or returning by reference
\&$x => $x;
// and worst of all...
fn&(&$x) => $x;
// vs.
\&(&$x) => $x;
```
I have to admit that the fn prefix is a little more readable for
these use cases (though I've never actually seen a real function
using by-reference passing and returning at the same time).
-Theodore Brown