On Fri, Sep 8, 2017 at 11:41 PM, Andrea Faulds <[email protected]> wrote:
> Hi everyone!
>
> Here's an RFC for a small, simple, self-contained feature with no
> backwards-compatibility breaks and which in fact doesn't even touch the
> language's syntax (it's 50%+1 eligible!) but which could make PHP a bit
> more expressive and consistent, especially with potential later features.
> It even has a test designed to impose minimal maintenance burden while
> testing a fairly large possibility space!
>
> Anyway, the RFC in question is this: https://wiki.php.net/rfc/opera
> tor_functions
>
> Please tell me what you think and suggest any potential improvements or
> anything you think might have been an omission.
>
> Thanks!
I like the general idea here, but have some comments.
My main observation is that this proposal is only really useful in
combination with a form of partial application. Passing operators to
array_reduce() is cute, but it's not a major application, especially as we
already have built-in functions for the two common operations (array_sum
and array_product).
Where operators-as-functions really shine is in cases where only one of the
operands is bound. You acknowledge this in the RFC, and provide a few
examples using a (not yet existing) partialApply() function:
// Select only the positive numbers
$positiveSubset = array_filters($numbers, partialApply('>', 0));
However, this code is subtly broken. Partial application (at least without
specifying a more specific behavior) operates from left to right, so this
code would be equivalent to:
// Select only the positive numbers
$positiveSubset = array_filters($numbers, function($n) { return 0 > $n;
});
As such, it would return all negative numbers, not all positive numbers.
This is a general issue of partial application in combination with
operators: For the operations that do not commute, you nearly always want
to bind the right operand, not the left.
For my own purposes, I define an operator() function as follows:
https://github.com/nikic/iter/blob/master/src/iter.fn.php#L60
This function either accepts a single argument such as operator('+'), in
which case it is essentially equivalent to this proposal. Or it accepts two
arguments, in which case the right operand will be bound, such as
operator('>', 0).
I wonder if providing such a function might not be a better solution to
this problem. It also has the additional advantage that it can be easily
polyfilled in older PHP versions.
Nikita