How to represent directed cyclic graph in Prolog with direct access to neighbour verticies

為{幸葍}努か 提交于 2019-11-29 11:24:06

If your graph has less vertices than max arity allowed by your Prolog (for instance SWI-Prolog has unlimited arity), you could represent the edges as indices of arguments:

could be

G = graph(a-[2],b-[3],c-[1,4],d-[2]).

then use arg(Edge, G, Vert-Edges) to access neighbours.

Of course any Prolog will let you describe the graph using facts. This is also the preferred way for very large graphs.

:- dynamic edge/2.

edge(a,b).
edge(b,c).
edge(c,a).
edge(c,d).
edge(d,b).

edit The edge/2 relational representation also get the (potentially large) benefits of automatic indexing.

more edit I totally forgot RDF and Semantic Web. Really powerful, we are going toward that.

In addition to the representation that @chac suggests, you can also consider using attributed variables (if your Prolog system supports it), especially if you need to attach further attributes to vertices or edges during your calculations. In this representation, you would use a unique variable for each vertex, attach (with put_attr/3) an attribute like "name" to it if necessary, and attach an additional attribute like "edges" which may for example be a list of vertices, or a list of terms edge(E,Vertex), where E is again a variable to which you can attach further attributes if you need to keep track of information that affects edges.

There is library(ugraphs) in many Prolog systems like YAP, SWI, SICStus, Ciao. (Please feel free to add further references here!) There, graphs are represented as a list of pairs Vertex-Neighbours. At first sight you might get the impression that this is not a very efficient representation. After all, access to a single vertex is proportional to the list's length. However, direct access to a vertex is rarely of interest. Most of the time a graph will be processed in one fell swoop - which often amortizes access costs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!