Taskcore
Implement ordering for a type
Also called implement compareTo, implement Comparable, implement Ord, implement __lt__, sort custom objects, order objects by fields, implement IComparable, default operator<=>.
Give a Version type with three numbers a natural ordering, with compareTo, __lt__, Ord, IComparable or the spaceship operator, and use it to sort version strings by number and not by text.
- Evidence
- Code in 9 languages
Task
Write a type Version with three numbers: major, minor and patch. Give it a natural ordering: compare the major numbers first, then the minor numbers, then the patch numbers, each as a number. Then use the order. The function sort_versions(versions) parses each string such as "1.10.0" into a Version, sorts the values with the natural ordering of the type, and returns them as strings again.
For example, sort_versions(["2.0.0", "1.9.9", "1.10.0"]) is ["1.9.9", "1.10.0", "2.0.0"]. A sort of the strings as text gives a different answer, because the character 1 comes before 9:
print(sorted(["1.10.0", "1.9.9", "1.2.0"]))
['1.10.0', '1.2.0', '1.9.9']
The list has 0 to 10,000 strings. Each number is from 0 to 1,000,000, with no sign and no leading zeros, so two equal versions are also equal strings. The tests also check the order directly: a < b must give the opposite answer of b < a, and a version compares equal to itself.
Solutions
| Language | Natural ordering | Sort call |
|---|---|---|
| Python | __lt__ and __eq__, with @functools.total_ordering |
sorted(...) |
| JavaScript | a static compare(a, b) by convention |
array.sort(Version.compare) |
| TypeScript | as JavaScript, with types | array.sort(Version.compare) |
| Java | record Version ... implements Comparable<Version> |
stream.sorted() |
| C# | record Version : IComparable<Version>, with <, >, <= and >= |
Order() |
| Go | a Compare method by convention |
slices.SortFunc(vs, Version.Compare) |
| Rust | #[derive(PartialEq, Eq, PartialOrd, Ord)] |
vec.sort() |
| C | a function version_compare |
qsort |
| C++ | auto operator<=>(const Version&) const = default; |
std::sort |
- Compare the fields in order of importance. Each solution compares the major numbers and goes to the next field only when they are equal. This is a lexicographic order of the fields, the same order as tuples in Python and the derived order in Rust.
- Python compares two tuples of the fields in
__lt__, and tuples compare item by item.total_orderingwrites<=,>and>=. Its documentation says: "The class must define one of lt(), le(), gt(), or ge()."1 Both methods returnNotImplementedfor other types, soVersion(1, 0, 0) < "1.0.0"raisesTypeError. - Java builds the order from
Comparator.comparingInt(Version::major).thenComparingInt(...), which returns a lexicographic-order comparator.2 The order is consistent with equals:compareToreturns 0 only when all three fields are equal, which is what the record'sequalscompares.Comparablesays that "e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false",3 and the comparator does. - C# implements
IComparable<Version>and the four comparison operators. The documentation says that a type that implementsIComparable<T>"should overload the op_GreaterThan, op_GreaterThanOrEqual, op_LessThan, and op_LessThanOrEqual operators to return values that are consistent with CompareTo(T)."4 By convention, any version is greater thannull. - Go has no operator overloading, so
<does not work on a struct. TheComparemethod chainscmp.Comparefor the three fields withcmp.Or, which returns the first result that is not zero.5slices.SortFunctakes the method expressionVersion.Compareas its comparison function. - Rust derives the order. "When derived on structs, it will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct’s members."6 The fields are declared as
major,minor,patch, so the derived order is the right one with no code. - C++ defaults
operator<=>. The compiler compares the members in the order of their declaration and rewritesa < bas(a <=> b) < 0, sostd::sortandstd::setwork. The defaulted<=>also gives a defaulted==.7 - C has no methods.
version_comparereturns a negative number, zero or a positive number, asqsortexpects. It uses(x > y) - (x < y)for each field, which cannot overflow. - JavaScript and TypeScript have no natural order for objects, and "If compareFn is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings".8
Version.comparesubtracts the fields and uses||to go to the next field when the result is zero. The subtraction is safe here because JavaScript numbers are exact up to 2^53.
Alternatives
- Generate the order. Python's
@dataclass(order=True)generates the four ordering methods, which "compare the class as if it were a tuple of its fields, in order."9 Rust'sderiveand C++'s defaulted<=>do the same, and Kotlin'scompareValuesBy(a, b, { it.major }, { it.minor }, { it.patch })builds the comparison from the fields. - A key function in place of an order.
sorted(versions, key=lambda s: tuple(map(int, s.split("."))))sorts the strings with noVersiontype. This is short, but other code cannot use the order, for example in a sorted set. - A comparator outside the type. When the type has no single obvious order, give no natural ordering, and pass a comparator to each sort.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
emptyandsingle: a sort of zero or one item returns it unchanged.numeric-not-text:10.0.0comes after9.0.0. A comparison of the strings gives the opposite order.duplicates: equal versions stay in the list, so the solutions use a sort and not a set.zero:0.0.0is a valid version and is the smallest one.limit:1000000.0.0is larger than999999.1000000.1000000, because the major number decides before the other fields count.
Pitfalls
- Subtraction in a comparison.
return a - b;is a common short form, but with 32-bit integers it overflows when the values are far apart, and the sign of the result is then wrong:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
Comparator<Integer> bySubtraction = (x, y) -> x - y;
System.out.println(bySubtraction.compare(Integer.MIN_VALUE, 1));
List<Integer> xs = new ArrayList<>(List.of(5, Integer.MIN_VALUE, -5, Integer.MAX_VALUE));
xs.sort(bySubtraction);
System.out.println(xs);
xs.sort(Integer::compare);
System.out.println(xs);
}
}
2147483647
[5, 2147483647, -2147483648, -5]
[-2147483648, -5, 5, 2147483647]
Integer.MIN_VALUE - 1 wraps around to the largest positive int, so the comparator says that the smallest number is greater than 1. Use Integer.compare, cmp.Compare, <=> or (x > y) - (x < y).
- An order that disagrees with equality. If
compareTocompares only the major and minor numbers,1.2.0and1.2.5are equal for aTreeSet, and the set keeps only one of them, althoughequalssays that they differ. Compare every field that equality compares. - The wrong field order. A comparison that starts with the patch number sorts
1.0.9after2.0.0. The derived orders of Rust and C++ follow the order of the declarations, so a change to the field order of the type changes the sort. - Only
<in C#. A class that implementsIComparable<T>and not the operators givesCompareToto sorts, buta < bdoes not compile. Define all four operators, and make them callCompareTo.
Related tasks
- Implement equality for a type gives a type the equality that this order must agree with.
- Sort the lines of a file sorts strings by their code points, which is the text order that this task must not use.
- Define a record type gets equality from the language; some languages also derive an order for records.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
from functools import total_ordering
@total_ordering
class Version:
"""A version MAJOR.MINOR.PATCH. The natural order compares the numbers, most important first."""
__slots__ = ("_parts",)
def __init__(self, major, minor, patch):
self._parts = (major, minor, patch)
@classmethod
def parse(cls, text):
major, minor, patch = (int(p) for p in text.split("."))
return cls(major, minor, patch)
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self._parts == other._parts
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self._parts < other._parts # tuples compare item by item
def __hash__(self):
return hash(self._parts)
def __str__(self):
return ".".join(str(p) for p in self._parts)
def __repr__(self):
return f"Version({self._parts[0]}, {self._parts[1]}, {self._parts[2]})"
def sort_versions(versions):
return [str(v) for v in sorted(Version.parse(s) for s in versions)]
test_version.py 38 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
import pytest
from version import Version, sort_versions
CASES = {
"simple": (["1.2.0", "1.0.0", "1.1.0"], ["1.0.0", "1.1.0", "1.2.0"]),
"fields-in-order": (["2.0.0", "1.9.9", "1.10.0"], ["1.9.9", "1.10.0", "2.0.0"]),
"patch": (["0.1.10", "0.1.2", "0.1.1"], ["0.1.1", "0.1.2", "0.1.10"]),
"empty": ([], []),
"single": (["3.4.5"], ["3.4.5"]),
"numeric-not-text": (["10.0.0", "9.0.0", "1.0.0"], ["1.0.0", "9.0.0", "10.0.0"]),
"duplicates": (["1.0.0", "0.9.0", "1.0.0"], ["0.9.0", "1.0.0", "1.0.0"]),
"zero": (["0.0.1", "0.0.0"], ["0.0.0", "0.0.1"]),
"limit": (["1000000.0.0", "999999.1000000.1000000"], ["999999.1000000.1000000", "1000000.0.0"]),
}
@pytest.mark.parametrize("name", CASES)
def test_sort_versions(name):
versions, want = CASES[name]
assert sort_versions(versions) == want
def test_order_rules():
a, b, c = Version(1, 2, 3), Version(1, 10, 0), Version(2, 0, 0)
assert a < b < c and a < c
assert not a < a and a <= a and a >= a
assert b > a and not b < a
assert Version(1, 2, 3) == a and hash(Version(1, 2, 3)) == hash(a)
assert max([a, c, b]) is c
def test_other_types_are_not_ordered():
with pytest.raises(TypeError):
Version(1, 0, 0) < "1.0.0"
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
#include "version.hpp"
#include <algorithm>
#include <charconv>
#include <stdexcept>
namespace version {
std::optional<Version> Version::parse(std::string_view text) {
int parts[3];
const char* p = text.data();
const char* end = text.data() + text.size();
for (int i = 0; i < 3; ++i) {
if (i > 0) {
if (p == end || *p != '.') return std::nullopt;
++p;
}
if (p == end || *p < '0' || *p > '9') return std::nullopt;
auto [next, ec] = std::from_chars(p, end, parts[i]);
if (ec != std::errc{}) return std::nullopt;
p = next;
}
if (p != end) return std::nullopt;
return Version{parts[0], parts[1], parts[2]};
}
std::string Version::to_string() const {
return std::to_string(major) + '.' + std::to_string(minor) + '.' + std::to_string(patch);
}
std::vector<std::string> sort_versions(const std::vector<std::string>& versions) {
std::vector<Version> vs;
vs.reserve(versions.size());
for (const auto& s : versions) {
auto v = Version::parse(s);
if (!v) throw std::invalid_argument("not a version: " + s);
vs.push_back(*v);
}
std::sort(vs.begin(), vs.end()); // uses operator<, which the compiler rewrites to <=>
std::vector<std::string> out;
out.reserve(vs.size());
for (const auto& v : vs) out.push_back(v.to_string());
return out;
}
} // namespace version
version.hpp 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
#ifndef VERSION_HPP
#define VERSION_HPP
#include <compare>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace version {
// A version MAJOR.MINOR.PATCH. The defaulted operator<=> compares the members
// in the order of their declaration, and it also gives a defaulted operator==.
struct Version {
int major = 0;
int minor = 0;
int patch = 0;
auto operator<=>(const Version&) const = default;
// parse reads a version such as "1.10.0", or returns no value.
static std::optional<Version> parse(std::string_view text);
std::string to_string() const;
};
// sort_versions sorts the versions by their natural order. It throws
// std::invalid_argument for a string that is not a version.
std::vector<std::string> sort_versions(const std::vector<std::string>& versions);
} // namespace version
#endif
test_version.cpp 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
#include "version.hpp"
#include <compare>
#include <iostream>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
using version::Version;
static int failures = 0;
static void check(std::string_view name, const std::vector<std::string>& versions,
const std::vector<std::string>& want) {
if (version::sort_versions(versions) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
static void expect(std::string_view name, bool ok) {
if (!ok) {
std::cerr << "check " << name << " failed\n";
failures++;
}
}
int main() {
check("simple", {"1.2.0", "1.0.0", "1.1.0"}, {"1.0.0", "1.1.0", "1.2.0"});
check("fields-in-order", {"2.0.0", "1.9.9", "1.10.0"}, {"1.9.9", "1.10.0", "2.0.0"});
check("patch", {"0.1.10", "0.1.2", "0.1.1"}, {"0.1.1", "0.1.2", "0.1.10"});
check("empty", {}, {});
check("single", {"3.4.5"}, {"3.4.5"});
check("numeric-not-text", {"10.0.0", "9.0.0", "1.0.0"}, {"1.0.0", "9.0.0", "10.0.0"});
check("duplicates", {"1.0.0", "0.9.0", "1.0.0"}, {"0.9.0", "1.0.0", "1.0.0"});
check("zero", {"0.0.1", "0.0.0"}, {"0.0.0", "0.0.1"});
check("limit", {"1000000.0.0", "999999.1000000.1000000"}, {"999999.1000000.1000000", "1000000.0.0"});
Version a{1, 2, 3}, b{1, 10, 0};
expect("less", a < b && b > a && a <= a && a >= a);
expect("three-way", (a <=> b) == std::strong_ordering::less);
expect("equal", a == Version{1, 2, 3} && a != b);
expect("parse", Version::parse("1.10.0") == Version{1, 10, 0});
expect("parse two parts", !Version::parse("1.2"));
expect("parse sign", !Version::parse("1.-2.0"));
std::set<Version> set{{2, 0, 0}, {1, 0, 0}, {1, 0, 0}};
expect("set", set.size() == 2 && *set.begin() == Version{1, 0, 0});
bool threw = false;
try {
version::sort_versions({"1.0.0", "x"});
} catch (const std::invalid_argument&) {
threw = true;
}
expect("bad input", threw);
if (failures == 0) {
std::cout << "all cases passed\n";
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
import java.util.Comparator;
import java.util.List;
/** A version MAJOR.MINOR.PATCH whose natural ordering compares the numbers, most important first. */
public record Version(int major, int minor, int patch) implements Comparable<Version> {
private static final Comparator<Version> ORDER =
Comparator.comparingInt(Version::major)
.thenComparingInt(Version::minor)
.thenComparingInt(Version::patch);
public static Version parse(String text) {
String[] p = text.split("\\.");
return new Version(Integer.parseInt(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]));
}
/** Consistent with equals: it returns 0 only when all three fields are equal. */
@Override
public int compareTo(Version other) {
return ORDER.compare(this, other);
}
@Override
public String toString() {
return major + "." + minor + "." + patch;
}
public static List<String> sortVersions(List<String> versions) {
return versions.stream().map(Version::parse).sorted().map(Version::toString).toList();
}
}
VersionTest.java 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class VersionTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("simple", List.of("1.2.0", "1.0.0", "1.1.0"), List.of("1.0.0", "1.1.0", "1.2.0")),
Arguments.of("fields-in-order", List.of("2.0.0", "1.9.9", "1.10.0"), List.of("1.9.9", "1.10.0", "2.0.0")),
Arguments.of("patch", List.of("0.1.10", "0.1.2", "0.1.1"), List.of("0.1.1", "0.1.2", "0.1.10")),
Arguments.of("empty", List.of(), List.of()),
Arguments.of("single", List.of("3.4.5"), List.of("3.4.5")),
Arguments.of("numeric-not-text", List.of("10.0.0", "9.0.0", "1.0.0"), List.of("1.0.0", "9.0.0", "10.0.0")),
Arguments.of("duplicates", List.of("1.0.0", "0.9.0", "1.0.0"), List.of("0.9.0", "1.0.0", "1.0.0")),
Arguments.of("zero", List.of("0.0.1", "0.0.0"), List.of("0.0.0", "0.0.1")),
Arguments.of(
"limit",
List.of("1000000.0.0", "999999.1000000.1000000"),
List.of("999999.1000000.1000000", "1000000.0.0")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void sortVersions(String name, List<String> versions, List<String> want) {
assertEquals(want, Version.sortVersions(versions), name);
}
@Test
void orderRules() {
Version a = new Version(1, 2, 3);
Version b = new Version(1, 10, 0);
assertTrue(a.compareTo(b) < 0 && b.compareTo(a) > 0);
assertEquals(0, a.compareTo(new Version(1, 2, 3)));
assertEquals(new Version(1, 2, 3), a);
assertEquals(a.compareTo(new Version(1, 2, 3)) == 0, a.equals(new Version(1, 2, 3)));
assertThrows(NullPointerException.class, () -> a.compareTo(null));
}
@Test
void sortedSet() {
TreeSet<Version> set = new TreeSet<>(List.of(new Version(2, 0, 0), new Version(1, 0, 0), new Version(1, 0, 0)));
assertEquals(2, set.size());
assertEquals(new Version(1, 0, 0), set.first());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
#include "version.h"
#include <ctype.h>
#include <stdlib.h>
static bool read_number(const char **p, long *out) {
if (!isdigit((unsigned char)**p)) {
return false;
}
char *end;
*out = strtol(*p, &end, 10);
*p = end;
return true;
}
bool version_parse(const char *text, Version *out) {
const char *p = text;
if (!read_number(&p, &out->major) || *p++ != '.') return false;
if (!read_number(&p, &out->minor) || *p++ != '.') return false;
if (!read_number(&p, &out->patch)) return false;
return *p == '\0';
}
// (x > y) - (x < y) is -1, 0 or 1, and it cannot overflow as x - y can.
static int compare_long(long x, long y) {
return (x > y) - (x < y);
}
int version_compare(const Version *a, const Version *b) {
int c = compare_long(a->major, b->major);
if (c != 0) return c;
c = compare_long(a->minor, b->minor);
return c != 0 ? c : compare_long(a->patch, b->patch);
}
struct item {
Version v;
const char *text;
};
static int compare_items(const void *x, const void *y) {
const struct item *a = x, *b = y;
return version_compare(&a->v, &b->v);
}
int sort_versions(const char **versions, size_t n) {
if (n == 0) {
return 0;
}
struct item *items = malloc(n * sizeof *items);
if (items == NULL) {
return -1;
}
for (size_t i = 0; i < n; i++) {
if (!version_parse(versions[i], &items[i].v)) {
free(items);
return -1;
}
items[i].text = versions[i];
}
qsort(items, n, sizeof *items, compare_items);
for (size_t i = 0; i < n; i++) {
versions[i] = items[i].text;
}
free(items);
return 0;
}
version.h 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
#ifndef VERSION_H
#define VERSION_H
#include <stdbool.h>
#include <stddef.h>
// A version MAJOR.MINOR.PATCH. C has no methods, so the natural order is a
// comparison function that qsort and bsearch can take.
typedef struct {
long major;
long minor;
long patch;
} Version;
// version_parse reads a version such as "1.10.0" into *out and returns true,
// or returns false if the text is not three numbers joined by dots.
bool version_parse(const char *text, Version *out);
// version_compare returns a negative number, zero or a positive number when
// *a is less than, equal to or greater than *b. It compares the numbers, most
// important first.
int version_compare(const Version *a, const Version *b);
// sort_versions sorts the n strings in place by the natural order of the
// versions that they hold. It returns 0, or -1 if a string is not a version
// or if memory runs out; the array is then unchanged.
int sort_versions(const char **versions, size_t n);
#endif
test_version.c 61 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
#include "version.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, const char **versions, const char *const *want, size_t n) {
if (sort_versions(versions, n) != 0) {
fprintf(stderr, "case %s failed: error\n", name);
failures++;
return;
}
for (size_t i = 0; i < n; i++) {
if (strcmp(versions[i], want[i]) != 0) {
fprintf(stderr, "case %s failed at %zu: got %s, want %s\n", name, i, versions[i], want[i]);
failures++;
return;
}
}
}
static void expect(const char *name, bool ok) {
if (!ok) {
fprintf(stderr, "check %s failed\n", name);
failures++;
}
}
#define CASE(name, n, in, want) check(name, (const char *[])in, (const char *const[])want, n)
#define L(...) {__VA_ARGS__}
int main(void) {
CASE("simple", 3, L("1.2.0", "1.0.0", "1.1.0"), L("1.0.0", "1.1.0", "1.2.0"));
CASE("fields-in-order", 3, L("2.0.0", "1.9.9", "1.10.0"), L("1.9.9", "1.10.0", "2.0.0"));
CASE("patch", 3, L("0.1.10", "0.1.2", "0.1.1"), L("0.1.1", "0.1.2", "0.1.10"));
check("empty", NULL, NULL, 0);
CASE("single", 1, L("3.4.5"), L("3.4.5"));
CASE("numeric-not-text", 3, L("10.0.0", "9.0.0", "1.0.0"), L("1.0.0", "9.0.0", "10.0.0"));
CASE("duplicates", 3, L("1.0.0", "0.9.0", "1.0.0"), L("0.9.0", "1.0.0", "1.0.0"));
CASE("zero", 2, L("0.0.1", "0.0.0"), L("0.0.0", "0.0.1"));
CASE("limit", 2, L("1000000.0.0", "999999.1000000.1000000"), L("999999.1000000.1000000", "1000000.0.0"));
Version a = {1, 2, 3}, b = {1, 10, 0}, c = {1, 2, 3};
expect("less", version_compare(&a, &b) < 0 && version_compare(&b, &a) > 0);
expect("equal", version_compare(&a, &c) == 0);
Version v;
expect("parse", version_parse("1.10.0", &v) && v.major == 1 && v.minor == 10 && v.patch == 0);
expect("parse two parts", !version_parse("1.2", &v));
expect("parse sign", !version_parse("1.-2.0", &v));
const char *bad[] = {"1.0.0", "x"};
expect("bad input", sort_versions(bad, 2) == -1 && strcmp(bad[0], "1.0.0") == 0);
if (failures == 0) {
printf("all cases passed\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
/// <summary>A version MAJOR.MINOR.PATCH. The record gives value equality, and IComparable gives the natural order.</summary>
public sealed record Version(int Major, int Minor, int Patch) : IComparable<Version>
{
public static Version Parse(string text)
{
var p = text.Split('.');
return new Version(
int.Parse(p[0], CultureInfo.InvariantCulture),
int.Parse(p[1], CultureInfo.InvariantCulture),
int.Parse(p[2], CultureInfo.InvariantCulture));
}
/// <summary>Compares the numbers, most important first. Any version is greater than null.</summary>
public int CompareTo(Version? other)
{
if (other is null) return 1;
int c = Major.CompareTo(other.Major);
if (c != 0) return c;
c = Minor.CompareTo(other.Minor);
return c != 0 ? c : Patch.CompareTo(other.Patch);
}
public static bool operator <(Version a, Version b) => a.CompareTo(b) < 0;
public static bool operator >(Version a, Version b) => a.CompareTo(b) > 0;
public static bool operator <=(Version a, Version b) => a.CompareTo(b) <= 0;
public static bool operator >=(Version a, Version b) => a.CompareTo(b) >= 0;
public override string ToString() => $"{Major}.{Minor}.{Patch}";
public static List<string> SortVersions(IReadOnlyList<string> versions) =>
versions.Select(Parse).Order().Select(v => v.ToString()).ToList();
}
VersionTests.cs 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
using System.Collections.Generic;
using Xunit;
public sealed class VersionTests
{
public static TheoryData<string, string[], string[]> Cases => new()
{
{ "simple", new[] { "1.2.0", "1.0.0", "1.1.0" }, new[] { "1.0.0", "1.1.0", "1.2.0" } },
{ "fields-in-order", new[] { "2.0.0", "1.9.9", "1.10.0" }, new[] { "1.9.9", "1.10.0", "2.0.0" } },
{ "patch", new[] { "0.1.10", "0.1.2", "0.1.1" }, new[] { "0.1.1", "0.1.2", "0.1.10" } },
{ "empty", new string[] { }, new string[] { } },
{ "single", new[] { "3.4.5" }, new[] { "3.4.5" } },
{ "numeric-not-text", new[] { "10.0.0", "9.0.0", "1.0.0" }, new[] { "1.0.0", "9.0.0", "10.0.0" } },
{ "duplicates", new[] { "1.0.0", "0.9.0", "1.0.0" }, new[] { "0.9.0", "1.0.0", "1.0.0" } },
{ "zero", new[] { "0.0.1", "0.0.0" }, new[] { "0.0.0", "0.0.1" } },
{ "limit", new[] { "1000000.0.0", "999999.1000000.1000000" }, new[] { "999999.1000000.1000000", "1000000.0.0" } },
};
[Theory]
[MemberData(nameof(Cases))]
public void SortVersions(string name, string[] versions, string[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Version.SortVersions(versions));
}
[Fact]
public void OrderRules()
{
var a = new Version(1, 2, 3);
var b = new Version(1, 10, 0);
var same = new Version(1, 2, 3);
Assert.True(a < b && b > a && a <= same && a >= same);
Assert.True(a.CompareTo(b) < 0 && b.CompareTo(a) > 0);
Assert.Equal(0, a.CompareTo(new Version(1, 2, 3)));
Assert.Equal(new Version(1, 2, 3), a);
Assert.True(a.CompareTo(null) > 0);
}
[Fact]
public void SortedSet()
{
var set = new SortedSet<Version> { new(2, 0, 0), new(1, 0, 0), new(1, 0, 0) };
Assert.Equal(2, set.Count);
Assert.Equal(new Version(1, 0, 0), set.Min);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
/** A version MAJOR.MINOR.PATCH. JavaScript has no natural order for objects, so the class gives a compare function. */
export class Version {
#major;
#minor;
#patch;
constructor(major, minor, patch) {
this.#major = major;
this.#minor = minor;
this.#patch = patch;
Object.freeze(this);
}
static parse(text) {
const [major, minor, patch] = text.split(".").map(Number);
return new Version(major, minor, patch);
}
/** Returns a negative number, zero or a positive number, as Array.prototype.sort expects. */
static compare(a, b) {
return a.#major - b.#major || a.#minor - b.#minor || a.#patch - b.#patch;
}
compareTo(other) {
return Version.compare(this, other);
}
equals(other) {
return other instanceof Version && Version.compare(this, other) === 0;
}
toString() {
return `${this.#major}.${this.#minor}.${this.#patch}`;
}
}
export function sortVersions(versions) {
return versions
.map((s) => Version.parse(s))
.sort(Version.compare)
.map((v) => v.toString());
}
version.test.js 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Version, sortVersions } from "./version.js";
const cases = [
["simple", ["1.2.0", "1.0.0", "1.1.0"], ["1.0.0", "1.1.0", "1.2.0"]],
["fields-in-order", ["2.0.0", "1.9.9", "1.10.0"], ["1.9.9", "1.10.0", "2.0.0"]],
["patch", ["0.1.10", "0.1.2", "0.1.1"], ["0.1.1", "0.1.2", "0.1.10"]],
["empty", [], []],
["single", ["3.4.5"], ["3.4.5"]],
["numeric-not-text", ["10.0.0", "9.0.0", "1.0.0"], ["1.0.0", "9.0.0", "10.0.0"]],
["duplicates", ["1.0.0", "0.9.0", "1.0.0"], ["0.9.0", "1.0.0", "1.0.0"]],
["zero", ["0.0.1", "0.0.0"], ["0.0.0", "0.0.1"]],
["limit", ["1000000.0.0", "999999.1000000.1000000"], ["999999.1000000.1000000", "1000000.0.0"]],
];
for (const [name, versions, want] of cases) {
test(name, () => {
assert.deepEqual(sortVersions(versions), want);
});
}
test("order rules", () => {
const a = new Version(1, 2, 3);
const b = new Version(1, 10, 0);
assert.ok(a.compareTo(b) < 0 && b.compareTo(a) > 0);
assert.equal(a.compareTo(new Version(1, 2, 3)), 0);
assert.ok(a.equals(new Version(1, 2, 3)) && !a.equals(b));
assert.deepEqual(["1.10.0", "1.2.0"].sort(), ["1.10.0", "1.2.0"]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
/** A version MAJOR.MINOR.PATCH. JavaScript has no natural order for objects, so the class gives a compare function. */
export class Version {
#major: number;
#minor: number;
#patch: number;
constructor(major: number, minor: number, patch: number) {
this.#major = major;
this.#minor = minor;
this.#patch = patch;
Object.freeze(this);
}
static parse(text: string): Version {
const [major, minor, patch] = text.split(".").map(Number);
return new Version(major, minor, patch);
}
/** Returns a negative number, zero or a positive number, as Array.prototype.sort expects. */
static compare(a: Version, b: Version): number {
return a.#major - b.#major || a.#minor - b.#minor || a.#patch - b.#patch;
}
compareTo(other: Version): number {
return Version.compare(this, other);
}
equals(other: unknown): boolean {
return other instanceof Version && Version.compare(this, other) === 0;
}
toString(): string {
return `${this.#major}.${this.#minor}.${this.#patch}`;
}
}
export function sortVersions(versions: string[]): string[] {
return versions
.map((s) => Version.parse(s))
.sort(Version.compare)
.map((v) => v.toString());
}
version.test.ts 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Version, sortVersions } from "./version.ts";
const cases: [string, string[], string[]][] = [
["simple", ["1.2.0", "1.0.0", "1.1.0"], ["1.0.0", "1.1.0", "1.2.0"]],
["fields-in-order", ["2.0.0", "1.9.9", "1.10.0"], ["1.9.9", "1.10.0", "2.0.0"]],
["patch", ["0.1.10", "0.1.2", "0.1.1"], ["0.1.1", "0.1.2", "0.1.10"]],
["empty", [], []],
["single", ["3.4.5"], ["3.4.5"]],
["numeric-not-text", ["10.0.0", "9.0.0", "1.0.0"], ["1.0.0", "9.0.0", "10.0.0"]],
["duplicates", ["1.0.0", "0.9.0", "1.0.0"], ["0.9.0", "1.0.0", "1.0.0"]],
["zero", ["0.0.1", "0.0.0"], ["0.0.0", "0.0.1"]],
["limit", ["1000000.0.0", "999999.1000000.1000000"], ["999999.1000000.1000000", "1000000.0.0"]],
];
for (const [name, versions, want] of cases) {
test(name, () => {
assert.deepEqual(sortVersions(versions), want);
});
}
test("order rules", () => {
const a = new Version(1, 2, 3);
const b = new Version(1, 10, 0);
assert.ok(a.compareTo(b) < 0 && b.compareTo(a) > 0);
assert.equal(a.compareTo(new Version(1, 2, 3)), 0);
assert.ok(a.equals(new Version(1, 2, 3)) && !a.equals(b));
assert.deepEqual(["1.10.0", "1.2.0"].sort(), ["1.10.0", "1.2.0"]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
// Package version gives a Version type with a natural order. Go has no
// operator overloading, so the order is a Compare method by convention.
package version
import (
"cmp"
"fmt"
"slices"
"strconv"
"strings"
)
// Version is MAJOR.MINOR.PATCH. It is comparable, so == works on it.
type Version struct {
Major, Minor, Patch int
}
// Parse reads a version such as "1.10.0".
func Parse(s string) (Version, error) {
p := strings.Split(s, ".")
if len(p) != 3 {
return Version{}, fmt.Errorf("version %q: want 3 parts", s)
}
var n [3]int
for i, part := range p {
v, err := strconv.Atoi(part)
if err != nil {
return Version{}, fmt.Errorf("version %q: %w", s, err)
}
n[i] = v
}
return Version{n[0], n[1], n[2]}, nil
}
// Compare returns -1, 0 or +1. It compares the numbers, most important first.
func (v Version) Compare(o Version) int {
return cmp.Or(
cmp.Compare(v.Major, o.Major),
cmp.Compare(v.Minor, o.Minor),
cmp.Compare(v.Patch, o.Patch),
)
}
func (v Version) String() string {
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
// SortVersions sorts the versions by their natural order.
func SortVersions(versions []string) ([]string, error) {
vs := make([]Version, 0, len(versions))
for _, s := range versions {
v, err := Parse(s)
if err != nil {
return nil, err
}
vs = append(vs, v)
}
slices.SortFunc(vs, Version.Compare)
out := make([]string, len(vs))
for i, v := range vs {
out[i] = v.String()
}
return out, nil
}
version_test.go 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
package version
import (
"slices"
"testing"
)
var cases = []struct {
name string
versions []string
want []string
}{
{"simple", []string{"1.2.0", "1.0.0", "1.1.0"}, []string{"1.0.0", "1.1.0", "1.2.0"}},
{"fields-in-order", []string{"2.0.0", "1.9.9", "1.10.0"}, []string{"1.9.9", "1.10.0", "2.0.0"}},
{"patch", []string{"0.1.10", "0.1.2", "0.1.1"}, []string{"0.1.1", "0.1.2", "0.1.10"}},
{"empty", []string{}, []string{}},
{"single", []string{"3.4.5"}, []string{"3.4.5"}},
{"numeric-not-text", []string{"10.0.0", "9.0.0", "1.0.0"}, []string{"1.0.0", "9.0.0", "10.0.0"}},
{"duplicates", []string{"1.0.0", "0.9.0", "1.0.0"}, []string{"0.9.0", "1.0.0", "1.0.0"}},
{"zero", []string{"0.0.1", "0.0.0"}, []string{"0.0.0", "0.0.1"}},
{"limit", []string{"1000000.0.0", "999999.1000000.1000000"}, []string{"999999.1000000.1000000", "1000000.0.0"}},
}
func TestSortVersions(t *testing.T) {
for _, c := range cases {
got, err := SortVersions(c.versions)
if err != nil || !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, %v; want %v", c.name, got, err, c.want)
}
}
}
func TestOrderRules(t *testing.T) {
a, b := Version{1, 2, 3}, Version{1, 10, 0}
if a.Compare(b) != -1 || b.Compare(a) != 1 || a.Compare(a) != 0 {
t.Fatal("Compare is not antisymmetric")
}
if (a.Compare(Version{1, 2, 3}) == 0) != (a == Version{1, 2, 3}) {
t.Fatal("Compare is not consistent with ==")
}
if _, err := Parse("1.2"); err == nil {
t.Fatal("Parse accepted 2 parts")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
use std::fmt;
/// A version MAJOR.MINOR.PATCH. The derived Ord compares the fields in the order
/// of their declaration, so the most important field comes first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Version {
pub major: u32,
pub minor: u32,
pub patch: u32,
}
impl Version {
pub fn new(major: u32, minor: u32, patch: u32) -> Self {
Version { major, minor, patch }
}
/// Reads a version such as "1.10.0". Returns None if the text is not three numbers.
pub fn parse(text: &str) -> Option<Self> {
let mut it = text.split('.').map(|p| p.parse::<u32>().ok());
let v = Version::new(it.next()??, it.next()??, it.next()??);
if it.next().is_some() {
return None;
}
Some(v)
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
/// Sorts the versions by their natural order. Panics on a string that is not a version.
pub fn sort_versions(versions: &[&str]) -> Vec<String> {
let mut vs: Vec<Version> = versions
.iter()
.map(|s| Version::parse(s).expect("a version MAJOR.MINOR.PATCH"))
.collect();
vs.sort();
vs.iter().map(Version::to_string).collect()
}
tests/version_test.rs 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/implement-ordering-for-a-type/.
use std::cmp::Ordering;
use std::collections::BTreeSet;
use algo_implement_ordering_for_a_type::{sort_versions, Version};
#[test]
fn cases() {
let cases: Vec<(&str, Vec<&str>, Vec<&str>)> = vec![
("simple", vec!["1.2.0", "1.0.0", "1.1.0"], vec!["1.0.0", "1.1.0", "1.2.0"]),
("fields-in-order", vec!["2.0.0", "1.9.9", "1.10.0"], vec!["1.9.9", "1.10.0", "2.0.0"]),
("patch", vec!["0.1.10", "0.1.2", "0.1.1"], vec!["0.1.1", "0.1.2", "0.1.10"]),
("empty", vec![], vec![]),
("single", vec!["3.4.5"], vec!["3.4.5"]),
("numeric-not-text", vec!["10.0.0", "9.0.0", "1.0.0"], vec!["1.0.0", "9.0.0", "10.0.0"]),
("duplicates", vec!["1.0.0", "0.9.0", "1.0.0"], vec!["0.9.0", "1.0.0", "1.0.0"]),
("zero", vec!["0.0.1", "0.0.0"], vec!["0.0.0", "0.0.1"]),
("limit", vec!["1000000.0.0", "999999.1000000.1000000"], vec!["999999.1000000.1000000", "1000000.0.0"]),
];
for (name, versions, want) in cases {
assert_eq!(sort_versions(&versions), want, "case {name}");
}
}
#[test]
fn order_rules() {
let a = Version::new(1, 2, 3);
let b = Version::new(1, 10, 0);
assert_eq!(a.cmp(&b), Ordering::Less);
assert_eq!(b.cmp(&a), Ordering::Greater);
assert_eq!(a.cmp(&Version::new(1, 2, 3)), Ordering::Equal);
assert!(a < b && a <= a && b > a);
assert_eq!(std::cmp::max(a, b), b);
assert_eq!(Version::parse("1.2"), None);
assert_eq!(Version::parse("1.2.3.4"), None);
}
#[test]
fn sorted_set() {
let set: BTreeSet<Version> = [Version::new(2, 0, 0), Version::new(1, 0, 0), Version::new(1, 0, 0)].into();
assert_eq!(set.len(), 2);
assert_eq!(set.first(), Some(&Version::new(1, 0, 0)));
}
References
- functools, Python standard library, total_ordering
- Comparator (Java SE 21 & JDK 21), API documentation, comparingInt; thenComparingInt
- Comparable (Java SE 21 & JDK 21), API documentation, Interface Comparable; compareTo
- IComparable<T> Interface, .NET API reference, Remarks; Notes to Implementers
- cmp package, Go standard library, func Compare; func Or
- Ord trait, Rust standard library, Derivable; How can I implement Ord?
- Default comparisons, cppreference.com, Three-way comparison
- Array.prototype.sort(), JavaScript reference, MDN, Description
- dataclasses, Python standard library, Module contents, order
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 8C752V Edit this page History Report an error Markdown