Today’s Erlang Thursday starts to dig into the digraph
module, as promised last week, and takes a look at digraph:add_vertex/1.
First we create a new directed graph, so we have something we can add vertices to.
Graph = digraph:new(). % {digraph,20498,24595,28692,true}
We then add some vertices to the graph by using digraph:add_vertex/1
.
digraph:add_vertex(Graph). % ['$v'|0] digraph:add_vertex(Graph). % ['$v'|1] digraph:add_vertex(Graph). % ['$v'|2]
As we don’t specify any information about the vertex we want to add, Erlang will create a new vertex for us of the format ['$v', I]
, with an empty list as the label where I
is a non-negative integer.
We can also use digraph:add_vertex/2
to add a vertex if we wish to provide the vertex identifer, or provide vertex identifier and label in the case of digraph:add_vertex/3
. As with digraph:add_vertex/1
, digraph:add_vertex/2
uses the empty list as the label as well.
digraph:add_vertex(Graph, vertex1). % vertex1 digraph:add_vertex(Graph, vertex2, "Vertex 2"). % vertex2
We have now added 5 vertices, and can check what vertices we have in the digraph()
by using digraph:vertices/1.
digraph:vertices(Graph). % [['$v'|2],['$v'|1],['$v'|0],vertex2,vertex1]
If we decide we want to try to add a vertex ourselves of the format ['$v' | I]
, we can run into trouble if you call digraph:add_vertex/1
after it.
digraph:add_vertex(Graph, ['$v' | 3]). % ['$v'|3] digraph:add_vertex(Graph). % ['$v'|3] digraph:vertices(Graph). % [['$v'|2],['$v'|1],['$v'|0],['$v'|3],vertex2,vertex1] digraph:add_vertex(Graph, ['$v' | 4]). % ['$v'|4] digraph:vertices(Graph). % [['$v'|4], % ['$v'|2], % ['$v'|1], % ['$v'|0], % ['$v'|3], % vertex2,vertex1]
So we add a vertex by specifying the vertex()
we want to add, and then add a new vertex and let Erlang take care of creating that vertex, and we wind up “losing” a vertex, as one essentially gets overridden when we look at the end state of the digraph()
.
–Proctor