Anthony Ferrara wrote on 01/09/2015 06:53:
function partial(callable $cb) {
return $left ~> $right ~> $cb($left, $right);
}
The thing that is most unreadable to me in this is the associativity.
Someone from, say, a Haskell background might be used to mentally
grouping X -> Y -> Z into a series of steps but to an untrained eye it
looks almost like there's a list of terms with ~> as the separator. As I
understand it, an expanded form would be:
return ($left) ~> { return ($right) ~> { return $cb($left, $right) } };
...which is a bit easier to mentally group, but not much prettier than
current PHP syntax.
What about something a bit more "enclosed" but still short. A
for-loop-style construct occured to me:
# lambda(params; expression)
lambda($a, $b; $a * $b)
lambda($x; { while(foo()) { $x ++; } return $x; })
The curly braces don't look very natural in that last example, but I'm
not sure what else to use. Maybe just use the existing function() syntax
if you want a block rather than an expression?
A nice expansion of this would be to have an explicit use clause without
any extra keywords:
# lambda(params; bound vars; expression)
$double = lambda($a;; 2*$a)
$x=3; $triple = lambda($a; $x; $x * $a)
Taking one of the RFC's examples:
function sumEventScores($events, $scores) {
$types = array_map(lambda($event;; $event['type']), $events);
return array_reduce($types, lambda($sum, $type; $scores; $sum +
$scores[$type]));
}
The next example benefits less if we allow only expressions, but you
could still write this:
function reduce(callable $fn) {
return lambda($initial; $fn;
function($input) use ($fn, $initial) {
$accumulator = $initial;
foreach ($input as $value) {
$accumulator = $fn($accumulator, $value);
}
return $accumulator;
}
);
}
I'll leave it to others to judge if this is better or worse than the
current proposal, just playing with ideas...
Regards,
Rowan Collins
--
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php