Re: Make sorting stable
| From: | Christoph M. Becker | Date: | Wed, 04 Mar 2020 22:12:55 +0000 |
| Subject: | Re: Make sorting stable | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-108857@lists.php.net to get a copy of this message | ||
On 04.03.2020 at 19:11, Nikita Popov wrote:
> 1. As Tyson suggests, we can throw a warning if a boolean is returned from
> the comparison callback (probably with a check to only throw it once per
> sort), to make it obvious what the cause is.
>
> 2. We can fix this transparently by doing something like this internally:
>
> $result = $compare($a, $b);
> if ($result !== false) {
> return (int) $result; // Normal behavior
> }
>
> // Bad comparison function, try the reverse order as well
> return -$compare($b, $a);
>
> That is, we will recover the full three-way comparison result from the
> "greater than" result, by checking for both $a > $b and $b > $a.
Given that we have internal classes which deliberately have such
comparison behavior (i.e. returning 0 or 1, to signal that there is no
order defined), e.g. Closures[1], I tend to prefer raising a warning
instead of trying to recover.
[1]
<https://github.com/php/php-src/blob/php-7.4.3/Zend/zend_closures.c#L372>
--
Christoph M. Becker