Skip to content

2.2 Put the nodes in dependency order

You get a topological order, in which every node comes before its out-nodes.

You have tasks that run one after the other, and some tasks need others to be finished first. You want an order that respects all of these needs. As a graph, each task is a node, and an edge a -> b says that a must come before b. The order you want lists every node before its out-nodes. Such an order is called a topological order. You need this for:

  • a build, in which every step runs after the steps it needs;
  • an installation, in which every package is installed after the packages it requires;
  • a spreadsheet, in which every cell is computed after the cells it refers to.

The example graph steps models the steps that build and publish a small program. It has an edge a -> b if step b may start only after step a. The array names holds the names of the steps. In which order can the steps run? The picture after shows the steps in the order found, one below the other: every edge points downward.

The steps of the build
The steps in topological order
0: generate1: compile2: lint3: compileTests4: docs5: test6: package7: sign8: publish
0: generate1: compile2: lint3: compileTests4: docs5: test6: package7: sign8: publish
Output
  • Step in topological order
IntList order = TopOrder.of(steps); // [2, 0, 1, 4, 3, 5, 6, 7, 8]
List<String> runOrder = order.intStream().mapToObj(step -> names[step]).toList();
// runOrder: [lint, generate, compile, docs, compileTests, test, package, sign,
// publish]
Full example
let order = top_order::of(&steps)?; // [2, 0, 1, 4, 3, 5, 6, 7, 8]
let run_order: Vec<&str> = order.iter().map(|&step| names[step as usize]).collect();
// run_order: ["lint", "generate", "compile", "docs", "compileTests", "test",
// "package", "sign", "publish"]
Full example
const order = TopOrder.of(steps); // [2, 0, 1, 4, 3, 5, 6, 7, 8]
const runOrder = Array.from(order, (step) => names[step]);
// runOrder: [lint, generate, compile, docs, compileTests, test, package, sign,
// publish]
Full example
ImmutableArray<int> order = TopOrder.Of(steps); // [2, 0, 1, 4, 3, 5, 6, 7, 8]
List<string> runOrder = [.. order.Select(step => names[step])];
// runOrder: [lint, generate, compile, docs, compileTests, test, package, sign,
// publish]
Full example

TopOrder.oftop_order::ofTopOrder.ofTopOrder.Of returns the node IDs in topological order, and the code turns them into names. Every step comes after the steps it needs: compile comes after generate, and package comes after compile, lint and test. publish comes last.