Returning a list from a recursive predicate in Prolog

594 views Asked by At

I've written a predicate called find_path(S,T,Visited,Path) that can search my undirected graph and find a path from node S to node T and then return a list of edge values (the edge value is the 3rd value in the edge fact). The predicate I wrote seems to work fine, however it only returns a boolean value for the result of the search, without the list of edge values. Can someone please offer a suggestion of how I can accomplish this? Thanks in advance.

Here is my code and an image of the undirected graph I am using

enter image description here

find_path(S,T,Visited,Path) :-
    not(member(S,Visited)),         % Check that S hasnt already been visited
    direct_path(S,T,edge(S,T,D))    % Check if theres a direct path from S to T.
    ->  append(Path,[D],X)          % If so, append the edge value to Path list and end
    ;   append(Visited,[S],Y),          % If not, add S to Visited
        direct_path(S,A,edge(S,A,B)),   %   Find any edge containing S
        append(Path,[D],X),             %   Add the edge value to the path list
        find_path(A,T,Y,X).             %   Recursively call find_path again, with the new Start value

direct_path(S,T,edge(S,T,D)) :- edge(S,T,D); edge(T,S,D).

edge(1,2,7). 
edge(1,3,9). 
edge(1,6,14). 
edge(2,3,10). 
edge(2,4,15). 
edge(3,4,11). 
edge(3,6,2). 
edge(4,5,6). 
edge(5,6,9).
0

There are 0 answers