Thomas Gielfeldt wrote on 24/02/2015 16:17:
Hi internals.

I've made PR proposing a feature request: A new interface Sortable.

https://github.com/php/php-src/pull/1116

If possible, I would like to create and RFC describing this in more detail,
and perhaps get a voting on.

I think the reason this interface is proving hard to simplify is that you're putting too much of the responsibility on the implementing object. Most containers don't need or want to reimplement an entire quicksort algorithm, or be responsible for tracking the various types of comparison.

Ideally, you could start by writing an OO implementation of QuickSort which takes as its input an abstract "Collection" instead of an array, and look at what methods you end up wanting to call on that Collection. That might end up rather complex in practice, though, because the underlying data structures do make a difference to an efficient implementation.

However, the types of sort differ primarily in the way values are compared, so if the engine passed in an appropriate comparison callback, the interface needs only one method:

public function sort(callable $comparison_callback, boolean $preserve_keys)
where $comparison_callback is:
function($l_key, $l_value, $r_key, $r_value): int

The only flag that the object might want to care about is whether to preserve keys (asort, uasort, ksort, uksort), because it could allow optimisations rather than reindexing after the sort has completed. For everything else, it should just be repeatedly asking the engine "which of these two items should come first?" By passing both keys and values, ksort() can be implemented with the same callback signature, the only disadvantage being that the user callbacks to usort() and uksort() would need to be wrapped, with the engine basically emulating the following:

// For usort($object, $usort_callback)
$comparison_callback = function($l_key, $l_value, $r_key, $r_value) use ($usort_callback) { return $usort_callback($l_value, $r_value); };
// For ksort($object, $ksort_callback)
$comparison_callback = function($l_key, $l_value, $r_key, $r_value) use ($ksort_callback) { return $ksort_callback($l_key, $r_key); };

Regards,
--
Rowan Collins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to