You will use
pooka/list:list.sort_by(values, compare)int.compareandstring.compare, which return anOrderpooka/order:order.reverse, and theOrder.Equalvariant for tie-breaks
The whole program
module main
import pooka/int
import pooka/io
import pooka/list
import pooka/order
import pooka/string
class Book(title: String, author: String, year: Int)
show(books: List(Book)) -> Nil {
list.each(books, fn(book: Book) {
io.println(int.to_string(book.year) + " " + book.title)
Nil
})
}
main() {
let shelf = [
Book("The Hobbit", "Tolkien", 1937),
Book("Moominsummer Madness", "Jansson", 1954),
Book("A Wizard of Earthsea", "Le Guin", 1968),
Book("Comet in Moominland", "Jansson", 1946)
]
io.println("Oldest first:")
show(
list.sort_by(shelf, fn(a: Book, b: Book) { int.compare(a.year, b.year) })
)
io.println("\nNewest first:")
show(list.sort_by(shelf, fn(a: Book, b: Book) {
order.reverse(int.compare(a.year, b.year))
}))
io.println("\nBy author, then title:")
show(list.sort_by(shelf, fn(a: Book, b: Book) {
match string.compare(a.author, b.author) {
order.Order.Equal -> string.compare(a.title, b.title)
other -> other
}
}))
}
Run it
$ pooka run
Oldest first:
1937 The Hobbit
1946 Comet in Moominland
1954 Moominsummer Madness
1968 A Wizard of Earthsea
Newest first:
1968 A Wizard of Earthsea
1954 Moominsummer Madness
1946 Comet in Moominland
1937 The Hobbit
By author, then title:
1946 Comet in Moominland
1954 Moominsummer Madness
1968 A Wizard of Earthsea
1937 The Hobbit
How it works
- Compare two at a time.
list.sort_byasks one question over and over: given two books, which comes first? Answer with anOrder:Less,EqualorGreater. - Borrow a comparison.
int.compare(a.year, b.year)already answers the question for numbers, andstring.comparefor text. - Backwards is one word.
order.reverseswapsLessandGreater, so the newest book comes first. - Break ties with a match. When the authors are
order.Order.Equal, compare the titles instead; otherwise keep the authors' answer. The two Jansson books end up side by side, in title order.
Try next: list.sort sorts lists of numbers or strings directly. Sorting is stable, so books that compare equal keep their original order.