Well you could use an accumulator:
get_to(A,B,L) :-
get_to(A,B,[A],L).
get_to(A,B,L,L2) :-
path(A,B),
append(L,[B],L2).
get_to(A,B,L,L3) :-
path(A,C),
append(L,[C],L2),
get_to(C,B,L2,L3).
Where L
is an array storing the nodes in the path.
In case the graph looks like:
path(1,2).
path(1,3).
path(3,4).
path(4,6).
path(6,5).
path(5,7).
This will result in:
?- get_to(1,7,L).
L = [1, 3, 4, 6, 5, 7]
A problem with this approach is however that the append
operation takes linear time resulting in a significant overhead. You can however try to construct the path in reverse...
get_to(A,B,L) :-
get_to(A,B,[B],L).
get_to(A,B,L,[A|L]) :-
path(A,B).
get_to(A,B,L,L2) :-
path(C,B),
get_to(A,C,[C|L],L2).
resulting - evidently - in the same path, but much faster...
?- get_to(1,7,L).
L = [1, 3, 4, 6, 5, 7] .