Sorting: By a key
● Beginner3 min
sort_by(key) sorts by what key gives for each item: a field, or any number or text worked out from it.
type Player {
name: String
score: Int
}
fn main() {
const players = [Player(name: "Zoe", score: 70), Player(name: "Asha", score: 90), Player(name: "Omar", score: 70)]
print(players.sort_by(.score).map(.name))
print(players.sort_by(p => -p.score).map(.name))
print(players.sort_by(.name).map(.name))
}The program ran and printed:
kavach run by-key.kav
["Zoe", "Omar", "Asha"]["Asha", "Zoe", "Omar"]["Asha", "Omar", "Zoe"]
sort_by(.score)sorts by a field. Equal scores keep their order: Zoe stays before Omar. This is a stable sort.p => -p.scoresorts the highest score first.- The key can be a number, text, a character, a
Bool, or a tuple of them.
Bools sort false first, and tuples item by item:
fn main() {
print([true, false, true, false].sort())
print([(2, "b"), (1, "z"), (2, "a")].sort())
}The program ran and printed:
kavach run bools.kav
[false, false, true, true][(1, "z"), (2, "a"), (2, "b")]
A record has no single natural order, so neither sort() nor a record key is allowed; the compiler asks for a key it can order:
type Player {
name: String
score: Int
}
fn main() {
const players = [Player(name: "Zoe", score: 70), Player(name: "Asha", score: 90)]
print(players.sort())
}The compiler refused the program:
kavach run records.kav
error: `[Player]` has no method `sort`type Point {
x: Int
y: Int
}
fn main() {
const points = [Point(x: 2, y: 1), Point(x: 1, y: 5)]
print(points.sort_by(p => p))
}The compiler refused the program:
kavach run record-key.kav
error: `sort_by`'s key needs values with an order (numbers, text, characters, `Bool`, or tuples of them), and `Point` has none