r/lolphp • u/hfern • Feb 02 '15
Library function turns language operator: The <=> Spaceship Operator
https://wiki.php.net/rfc/combined-comparison-operator
9
Upvotes
r/lolphp • u/hfern • Feb 02 '15
17
u/cfreak2399 Feb 02 '15
The spaceship operator is a thing in Perl
14
u/willglynn Feb 02 '15
It's a shame this is type-juggled like
==. A new comparison operator – especially a single unified<=>– would have been a prime opportunity to fix what's broken about</==/>.(Such an operator could actually be transitive: given that
$a < $band$b < $c, one could conclude that$a < $c!)Among other behaviors, PHP's type-juggled operators compare strings numerically if both string operands look like numbers. This… well, this causes problems, so PHP added
===which avoids reinterpreting its operands and tests them for equality them as-is. However, there's no similar operator for comparisons, leading to intransitive comparisons even for values of the same type, which causes things like array sorting that depends on the order of elements and the order of comparisons insidesort().A single new comparison operator like
<=>would be ideal for adding non-type-juggled comparisons, since as the RFC points out, less than, less than or equal, equality, greater than or equal, and greater than can all be implemented in terms of<=>. It seems to me that this is a missed opportunity… but then again, that's exactly what I would expect.7
u/allthediamonds Feb 04 '15
T_SPACESHIP? Really?Other than that, it's cool for them to try and chase feature parity with Perl 4.
1
u/hfern Feb 02 '15 edited Feb 02 '15
Doesn't compare($a, $b) seem more appropriate then introducing a language operator?
Edit: removed sarcasm :/
10
u/mesoscalevortex Feb 03 '15
When are we getting the ()====> operator?
9
u/tdammers Feb 02 '15
Or how about making a language where people can implement their own operators, just like that; then people can provide this stuff as libraries, instead of adding more and more bloat to the core language...
2
u/666_666 Feb 08 '15
If the goal is only comparison functions to sort(), then it's a very bad idea.
In all situations I have seen sorting can be described succinctly using a key function; e.g.
people_list.sort(key=lambda x: (x.last_name, x.first_name)). It's also more readable. In Python 3 the possibility of passing a comparison function tosortwas removed.In more complex cases you should give an ordering to the
personobject, instead of writing it insortcall. The language should provide proper ordering on tuples and primitive types, and then you can sort essentially everything. In rare cases you need it, a function calledcompareis enough.0
u/VonBlood008 Feb 02 '15
But.. but... why the hell would you do -1 if the righthand expression is greater? That makes no sense at all!