Erlang Thursday – digraph:add_edge/4

Today’s Erlang Thursday is on digraph:add_edge/4.

digraph:add_edge/4 takes a graph as its first argument, the originating (eminating) vertex as its second arugment, the destination (incident) vertex as its third argument, and a label.

Graph = digraph:new().
% {digraph,20498,24595,28692,true}
Vertex1 = digraph:add_vertex(Graph, foo).
% foo
Vertex2 = digraph:add_vertex(Graph, bar).
% bar
Edge1 = digraph:add_edge(Graph, Vertex1, Vertex2, {foo, bar}).
% ['$e'|0]
digraph:edges(Graph).
% [['$e'|0]]
Edge2 = digraph:add_edge(Graph, Vertex2, Vertex1, {bar, foo}).
% ['$e'|1]
digraph:edges(Graph).
% [['$e'|1],['$e'|0]]

The digraph module also contains digraph:add_edge/5 which allows you to specify the edge identifier, in this case we want the edge to be myEdge.

digraph:add_edge(Graph, myEdge, Vertex2, Vertex1, myLabel).
% myEdge
digraph:edges(Graph).
% [['$e'|1],['$e'|2],['$e'|3],myEdge,['$e'|0]]

As well as digraph:add_edge/3 which allows you to not specify the edge or the label.

digraph:add_edge(Graph, Vertex2, Vertex1).
% ['$e'|2]
digraph:add_edge(Graph, Vertex2, Vertex1).
% ['$e'|3]
digraph:edges(Graph).
% [['$e'|1],['$e'|2],['$e'|3],['$e'|0]]

And if you note in the examples for digraph:add_edge/3 and digraph:add_edge/5 we added a number of edges with the same eminate and incident vertices, and it was happy to create those edges for us.

We can also create acyclic digraphs by using digraph:new/1, and specifying that we want the digraph() to be acyclic.

Graph2 = digraph:new([acyclic]).
% {digraph,20498,24595,28692,false}
VertexA = digraph:add_vertex(Graph2, foo).
% foo
VertexB = digraph:add_vertex(Graph2, bar).
% bar
EdgeAB = digraph:add_edge(Graph2, VertexA, VertexB, {foo, bar}).
% ['$e'|0]
EdgeBA = digraph:add_edge(Graph2, VertexB, VertexA, {bar, foo}).
% {error,{bad_edge,[foo,bar]}}

When we try to add an edge that will create a cycle in an acyclic directed graph, we get a return of a bad_edge error with the two edges specified.

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *