14

How to store the list of visited nodes in a path on a graph in Prolog

 2 years ago
source link: https://www.codesd.com/item/how-to-store-the-list-of-visited-nodes-in-a-path-on-a-graph-in-prolog.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to store the list of visited nodes in a path on a graph in Prolog

advertisements

I am studying Prolog and I am finding some difficulty interpreting the slide proposed by my professor.

Starting from the classic program that say if exist a path between two node of a graph, this one:

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

path(X,Y) :- edge(X,Y).

path(X,Y) :- path(X,Z),
             edge(Z,Y).

He introduce a new version that use the predicate: path(X,Y,Path) that is TRUE if in the graph exist a path between X and Y and if Path is the list of visited nodes

So he give me the following new version of the previous program:

/* BASE CASE: exist an edge between X and Y, so the Path is
              the couple [X,Y]
*/
path(X,Y,[X,Y]) :- edge(X,Y).

path(X,Y,P) :- path(X,Z,P1),
               edge(Z,Y),
               lastelem(P,Y,P1).

The base case is pretty simple: if exist an edge that connect X and Y it is true that exist a path from X to Y and the list of the visited node is [X,Y]

I have some problems with the second rule: if X and Y are not connect by only a single edge, so that there is a path between X and Y, have to exist a path between X and an other node Z (and P1 is the list of the visited node in this path) an an edge that connect Z to the final node Y.

This is pretty simple...the problem is with the last predicate lastelem/3 that it is not provided in the slide (so I don't know exactly what it do):

lastelem(P,Y,P1).

I think that it generate P inserting Y in P1 or something like it...

Do you have some more precise idea about it and a possible implementation of this predicate?


There's no need to re-invent the wheel by writing recursive code yourself.

Simply define a binary relation edge/2 ...

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

... and use the meta-predicate path/4!

?- path(edge,Path,From,To).
  Path = [To]       , From = To
; Path = [a,b]      , From = a, To = b
; Path = [a,b,c]    , From = a, To = c
; Path = [a,b,c,d]  , From = a, To = d
; Path = [a,b,c,d,e], From = a, To = e
; Path = [b,c]      , From = b, To = c
; Path = [b,c,d]    , From = b, To = d
; Path = [b,c,d,e]  , From = b, To = e
; Path = [a,e]      , From = a, To = e
; Path = [c,d]      , From = c, To = d
; Path = [c,d,e]    , From = c, To = e
; Path = [d,e]      , From = d, To = e
; Path = [f,e]      , From = f, To = e
; false.

Tags prolog

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK