dart-lang / dart-lang/language

Records with (comparable) positional fields should implement Comparable

Open
#3,602 6 comments 6 reactions 0 assignees View on GitHub
feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

The following both should work as String and int can be compared to each other.
````dart
print(("a", 1) > ("a", 0)); // false
print(("a", 1).compareTo(("a", 0))); // 1
````

Records should be compared by comparing the fields from left to right until one value isn't equal to the other.

```dart
int compare<
A extends Comparable,
B extends Comparable,
X,
Y
>(A a, B b, X x, Y y) {
return (a, b).compareTo((x, y));
}
```

should return the same as

```dart
int compare<
A extends Comparable,
B extends Comparable,
X,
Y
>(A a, B b, X x, Y y) {
final axCompare = a.compareTo(x);
if (axCompare != 0) {
return axCompare;
}
return b.compareTo(y);
}
```

This would be really useful for sorting a list of records.

```dart
final list = [("a", 1), ("b", 1), ("a", 0), ("b", -1)];
list.sort();
print(list); // (a, 0), (a, 1), (b, -1), (b, 1)
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.