Skip to content

Comparable

Lets a class of your own say how two of its values are ordered, so everything that sorts can sort them.

A class that implements Comparable has one member, compareTo. It takes another value of the same class and answers a number: negative when this one comes first, zero when neither comes first, positive when the other one does. From then on <, >, <=, >= and <=> work on those values, and every member that puts things in order reads that same answer — sorting a list, picking the smallest or the largest, keeping a queue in priority order. You write the ordering once, and nothing else in your program needs its own.

Good to know: a class that says nothing about its order cannot be ordered at all. The comparison is refused while your program is built, and the message names Comparable as the fix. Equality does not change: two values are == only when they are the same value, so asking whether two values have the same contents is compareTo answering zero.

Examples

One member and the comparisons work

<?nvs
// A class that says how two of its values are ordered can be compared with the
// usual operators. The one member you write is `compareTo`.
final class Distance implements Comparable
{
public int $metres;
public function constructor(int $metres)
{
$this->metres = $metres;
}
// Negative when this trip is the shorter one, zero when the two are the
// same length, positive when this one is longer.
public function compareTo(Distance $other): int
{
return $this->metres - $other->metres;
}
}
var $walk = new Distance(1200);
var $ride = new Distance(8400);
var $sameWalk = new Distance(1200);
if ($walk < $ride) {
echo "the walk is the shorter trip\n";
}
if ($ride >= $walk) {
echo "the ride is at least as long as the walk\n";
}
// Two trips of the same length: neither comes first, and `compareTo` says so
// with a zero.
if ($walk->compareTo($sameWalk) == 0) {
echo "the walk and the other walk are the same length\n";
}
// `<=>` hands you the number itself. Read its sign: below zero means the left
// trip comes first, above zero means the right one does.
echo 'walk against ride: ', $walk <=> $ride, "\n";
echo 'ride against walk: ', $ride <=> $walk, "\n";
Output
the walk is the shorter trip
the ride is at least as long as the walk
the walk and the other walk are the same length
walk against ride: -7200
ride against walk: 7200

Sorting a list and finding its ends

<?nvs
// A class that implements `Comparable` has a `compareTo` method. `Core\Arr::min`,
// `Core\Arr::max` and `Core\Arr::sort` use it to order a list of those objects.
final class Reading implements Comparable
{
public string $city;
public int $celsius;
public function constructor(string $city, int $celsius)
{
$this->city = $city;
$this->celsius = $celsius;
}
public function compareTo(Reading $other): int
{
return $this->celsius - $other->celsius;
}
}
array<Reading> $readings = [
new Reading('Lisbon', 24),
new Reading('Reykjavik', 6),
new Reading('Cairo', 37),
new Reading('Vienna', 19),
];
// `Core\Arr::min` and `Core\Arr::max` return the coldest and warmest reading. For
// an empty list both return `null`, so the code checks before it reads the city.
var $coldest = Core\Arr::min($readings);
var $warmest = Core\Arr::max($readings);
if ($coldest != null) {
echo 'coldest: ', $coldest->city, "\n";
}
if ($warmest != null) {
echo 'warmest: ', $warmest->city, "\n";
}
// `Core\Arr::sort` returns a sorted copy and leaves `$readings` as it is.
// The loop prints the copy, from the coldest city to the warmest.
array<Reading> $sorted = Core\Arr::sort($readings);
foreach ($sorted as Reading $reading) {
echo $reading->city, ' ', $reading->celsius, "\n";
}
Output
coldest: Reykjavik
warmest: Cairo
Reykjavik 6
Vienna 19
Lisbon 24
Cairo 37

A queue that always hands you the most urgent job

<?nvs
// `Core\Heap` orders its jobs with the `compareTo` method of the class. `pop`
// always returns the most urgent job. This is also true for a job pushed later.
final class Job implements Comparable
{
public string $name;
// Minutes left before this job is late. The fewer, the more urgent.
public int $minutesLeft;
public function constructor(string $name, int $minutesLeft)
{
$this->name = $name;
$this->minutesLeft = $minutesLeft;
}
public function compareTo(Job $other): int
{
return $this->minutesLeft - $other->minutesLeft;
}
}
// No comparison function is given, so the heap uses `Job::compareTo`.
var $queue = new Core\Heap<Job>();
$queue->push(new Job('send invoices', 45));
$queue->push(new Job('rebuild search index', 120));
$queue->push(new Job('charge expiring card', 10));
var $next = $queue->peek();
echo 'next up: ', $next->name, "\n";
// After the first job, the loop pushes a job with 2 minutes left. The next
// `pop` returns that job before the older ones.
var $worked = 0;
while (!$queue->isEmpty()) {
var $job = $queue->pop();
echo 'worked ', $job->name, ' with ', $job->minutesLeft, " minutes left\n";
$worked = $worked + 1;
if ($worked == 1) {
$queue->push(new Job('retry failed payout', 2));
}
}
Output
next up: charge expiring card
worked charge expiring card with 10 minutes left
worked retry failed payout with 2 minutes left
worked send invoices with 45 minutes left
worked rebuild search index with 120 minutes left