Skip to content

11.1 Print a graph as text

You print the whole graph as an adjacency list, or a short summary for logs.

You want to see a graph quickly, as text. A picture is too much, and a line per node is enough. For a large graph, you want a summary that stays short. You need this for:

  • the expected value of a test;
  • a log of the graph a program built;
  • an error message that shows the graph it is about.

The example graph steps models the nine steps that build and publish a small program. It has an edge a -> b if step b may start only after step a:

0: generate1: compile2: lint3: compileTests4: docs5: test6: package7: sign8: publish

A test of the build should check that the graph has exactly these edges, and the log of the build should show it in one line.

String full = Graphs.adjacencyListOf(steps); // every node, one line each:
// 0 -> [1]
// 1 -> [3, 4, 6]
// 2 -> [6]
// 3 -> [5]
// 4 -> [8]
// 5 -> [6]
// 6 -> [7]
// 7 -> [8]
// 8 -> []
String brief = steps.toString(); // one line, for logs and debuggers:
// Graph[nodes=9, edges=10] {0 -> [1], 1 -> [3, 4, 6], 2 -> [6], 3 -> [5], 4 -> [8],
// 5 -> [6], 6 -> [7], 7 -> [8], 8 -> []}
Full example
let full = graphs::adjacency_list_of(&steps); // every node, one line each:
// 0 -> [1]
// 1 -> [3, 4, 6]
// 2 -> [6]
// 3 -> [5]
// 4 -> [8]
// 5 -> [6]
// 6 -> [7]
// 7 -> [8]
// 8 -> []
let brief = steps.to_string(); // one line, for logs and debuggers:
// Graph[nodes=9, edges=10] {0 -> [1], 1 -> [3, 4, 6], 2 -> [6], 3 -> [5], 4 -> [8],
// 5 -> [6], 6 -> [7], 7 -> [8], 8 -> []}
Full example
const full = Graphs.adjacencyListOf(steps); // every node, one line each:
// 0 -> [1]
// 1 -> [3, 4, 6]
// 2 -> [6]
// 3 -> [5]
// 4 -> [8]
// 5 -> [6]
// 6 -> [7]
// 7 -> [8]
// 8 -> []
const brief = steps.toString(); // one line, for logs and debuggers:
// Graph[nodes=9, edges=10] {0 -> [1], 1 -> [3, 4, 6], 2 -> [6], 3 -> [5], 4 -> [8],
// 5 -> [6], 6 -> [7], 7 -> [8], 8 -> []}
Full example
string full = Graphs.AdjacencyListOf(steps); // every node, one line each:
// 0 -> [1]
// 1 -> [3, 4, 6]
// 2 -> [6]
// 3 -> [5]
// 4 -> [8]
// 5 -> [6]
// 6 -> [7]
// 7 -> [8]
// 8 -> []
// one line, for logs and debuggers:
string brief = steps.ToString();
// Graph[nodes=9, edges=10] {0 -> [1], 1 -> [3, 4, 6], 2 -> [6], 3 -> [5],
// 4 -> [8], 5 -> [6], 6 -> [7], 7 -> [8], 8 -> []}
Full example

The adjacency list has a line for every node, with its out-nodes in ascending order. It is the same for equal graphs, so tests can compare it with an expected text, as the tests of the examples in this guide do. The summary starts with the node and edge counts and lists at most 16 nodes and 64 out-nodes, so that it stays short however large the graph is. ... marks where it is cut. The steps are few enough for the summary to show them all.