Re: [VOTE] Combined Comparison (Spaceship) Operator

From: Date: Mon, 02 Feb 2015 16:35:29 +0000
Subject: Re: [VOTE] Combined Comparison (Spaceship) Operator
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-81599@lists.php.net to get a copy of this message
Hey Nikita, > On 2 Feb 2015, at 16:32, Nikita Popov <nikita.ppv@gmail.com> wrote: > > On Mon, Feb 2, 2015 at 4:27 PM, Andrea Faulds <ajf@ajf.me> wrote: > Hey Nikita, > > > On 2 Feb 2015, at 13:49, Nikita Popov <nikita.ppv@gmail.com> wrote: > > > > I've voted -1 because I think this should be a function and not an operator. > > compare($a, $b) is more obvious than $a <=> $b and it's not like writing comparison > > functions is such a super common use case that it needs the extra brevity of an operator. A function > > can furthermore be used as a callback, while an operator requires a wrapping closure. > > There’s no actual use for the bare comparison operation as a callback, though: usort($foo, > ‘compare’); would just be a slow version of sort($foo); > > It may not be applicable to a direct sort() call, but it's useful for higher level APIs. > With a function you can create APIs of the form function foo(..., $comparator = > 'compare') { ... }, which will default to the "standard" > comparison function without having to specially handle it all over the place. Yes, that’s true. I’d previously suggested adding a function to get a closure of an operator. But actually, perhaps we should just follow PHP’s traditional string typing of callables, and make ‘+’, ‘-‘, ‘<‘, ‘<=>’ etc. be valid callables? Thus: function doesThing($a, $b, callable $callback = ‘+’) { return $callback($a, $b); } doesThing(1, 2); // 3 Thoughts? (I realise this is slightly OT.) -- Andrea Faulds http://ajf.me/

« previous php.internals (#81599) next »