Re: [RFC] Combined Comparison Operator

From: Date: Thu, 13 Feb 2014 05:07:19 +0000
Subject: Re: [RFC] Combined Comparison Operator
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On 13/02/2014, at 17:39, Davey Shafik <[email protected]> wrote:

> On 2/12/14, 11:25 PM, Yasuo Ohgaki wrote:
>> Hi Davey,
>> 
>> On Thu, Feb 13, 2014 at 12:58 PM, Davey Shafik <[email protected]> wrote:
>> 
>>> I've written up an RFC/Patch to gauge interest and get feedback on the
>>> addition of a combined comparison (aka: spaceship) operator.
>>> 
>>> You can see the RFC at: https://wiki.php.net/rfc/
>>> combined-comparison-operator
>>> 
>>> This adds a new operator "(expr) <=> (expr)" that returns 0 if both
>>> operands are equal, 1 if the left is greater, and -1 if the right is
>>> greater.
>>> 
>>> It works with all types (just as well as <, <=, >=, > work) and is great
>>> for usort() callbacks for example.
>>> 
>>> Code available here (against 5.6): https://github.com/dshafik/
>>> php-src/compare/add-spaceship-operator
>>> 
>>> I'd love to get this into 5.6, not sure if we hit feature freeze yet.
>>> Also, not sure if it needs 2/3 majority, but assumed so as pow did?
>>> 
>>> Thoughts?
>>> 
>>> If there is interest, I'll start adding tests. They should be fairly
>>> trivial.
>>> 
>> 
>> Interesting shortcut operator.
>> I feel closure function is for the task.
>> I would vote 0, but close to -1 since it's only useful for sorting.
>> Is there any other use cases?
>> 
>> Regards,
>> 
>> --
>> Yasuo Ohgaki
>> [email protected]
>> 
> 
> Yasuo,
> 
> Sorting is definitely it's most compelling use. It cuts down on potentially quite a bit of
> code:
> 
> function ($left, $right) {
>    if ($left[1] == $right[1]) {
>         return 0;
>    }
> 
>    if ($left[1] > $right[1]) {
>         return 1;
>    }
> 
>    if ($left[1] < $right[1]) {
>        return -1;
>    }
> }
> 
> or (as per the RFC):
> 
> function ($left, $right) {
>    return $left[1] <=> $right[1];
> }
> 
> -- 
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php

The only real case I see for this is to save some boilerplate when dealing with arrays. Strings have
strcmp(), numbers have subtraction and when you’re sorting objects, you probably want to be doing
the comparison on some string/numeric property.

If you really need the -1/0/1 return value (sorting functions don’t), then wrap the
strcmp/subtraction in a trivial sign() function.
---
Simon Welsh
Admin of http://simon.geek.nz/



Thread (20 messages)

« previous php.internals (#72544) next »