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?