Reputation: 81
I have the following code:
edge(a,b,5).
edge(b,a,5).
edge(b,c,3).
edge(c,a,2).
edge(c,d,4).
edge(d,b,6).
edge(c,f,4).
edge(f,c,4).
edge(e,c,5).
edge(f,e,7).
edge(g,a,3).
edge(d,g,8).
edge(e,g,2).
edge(f,h,3).
edge(h,i,2).
edge(i,j,3).
edge(j,h,4).
edge(d,h,1).
edge(j,f,6).
%edge(l,k,-1).
%edge(k,l,4).
%edge(a,z,-2).
vertex(a).
vertex(b).
vertex(c).
vertex(d).
vertex(e).
vertex(f).
vertex(g).
vertex(h).
vertex(i).
vertex(j).
member(A, [A|_]) :- !.
member(A, [_|Y]) :- member(A, Y).
path(X,Y) :- pathHelper(X,Y,[],0).
pathHelper(X,X,L, W) :- write([X|L]), write(W).
pathHelper(X,Y,L, W) :- edge(X,Z,C),\+member(Z,L),F is W+C,pathHelper(Z,Y,[X|L], F).
I was wondering how to turn path into a function with 4 arguments so when called like path(a, h, L, W) gives
L = [a, b, c, d, h],
W = 13 ;
L = [a, b, c, f, h],
W = 15 ;
Upvotes: 0
Views: 69
Reputation: 976
Try to look into the concept of accumulator(they call it accumulator in prolog,Extra argument for result) it's interesting and btw it's not much work:
path(X,Y,Distance,Result):-
pathHelper(X,Y,[],0,Distance,Result).
pathHelper(X,X,L,W,W,P):-
reverse([X|L],P).
pathHelper(X,Y,L, W,Distance,Result):-
edge(X,Z,C),
\+member(Z,L),
F is W+C,
pathHelper(Z,Y,[X|L], F,Distance,Result).
Upvotes: 1