← Cookbook Collections Beginner · Pooka 0.5.0

Sort by a key

Sort a shelf of books by year, backwards by year, or by author and then title. You only ever say how two books compare.

You will use

  • pooka/list: list.sort_by(values, compare)
  • int.compare and string.compare, which return an Order
  • pooka/order: order.reverse, and the Order.Equal variant for tie-breaks

The whole program

src/main.pooka
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

  1. Compare two at a time. list.sort_by asks one question over and over: given two books, which comes first? Answer with an Order: Less, Equal or Greater.
  2. Borrow a comparison. int.compare(a.year, b.year) already answers the question for numbers, and string.compare for text.
  3. Backwards is one word. order.reverse swaps Less and Greater, so the newest book comes first.
  4. 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.