Re: [RFC] [Discussion] Short Closures
| From: | Andrea Faulds | Date: | Mon, 07 Sep 2015 18:28:37 +0000 |
| Subject: | Re: [RFC] [Discussion] Short Closures | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-88104@lists.php.net to get a copy of this message | ||
Hi Levi,
Levi Morrison wrote:
If this RFC passes I'd like to see one that builds on it to remove the
{ return <expr> ;} boilerplate of the above definition:
function reduce ($initial) ~> $fn ~> $input {
$accumulator = $initial;
foreach ($input as $value) {
$accumulator = $fn($accumulator, $value);
}
return $accumulator;
}
I'm not saying it would be that syntax exactly but something like that
would be nice if this RFC passes.
That looks rather weird to me, but I like the concept.
I think a possible improvement might be a generalised syntax, similar to that used for constants, that lets you use any \Closure object to define a function or method. Thus:
function reduce = $initial ~> $fn ~> $input ~> {
// ...
};
This has that advantage that it isn't just useful for when you want to use the short syntax. You can also use it when you're obtaining a Closure in some novel way, perhaps a higher-order function:
// where "add" is a function that adds two numbers
function sum = reduce(0)("add");
With this, you don't have to write a wrapper function, or use a global variable, to define a proper top-level function.
Hope this is helpful.
--
Andrea Faulds
http://ajf.me/