Eddy Freeman
Eddy Freeman

Reputation: 3309

Prolog Code Not Working

I have the following code in prolog to produce a path from one node to other but I can't see my results on the screen. I just get true as an answer. The last variable name doesn't bind to the results:

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

path(A,B,P):- 
               path_1(A,B,[A],P).

path_1(A,B,P,Path):- last_element(P,S),S=B.
path_1(A,B,P,Path):-
                  edge(A,X),\+member(X,P),append(P,[X],NewP), 
                  path_1(X,B,NewP,NewP).

last_element([X],X).
last_element([H|T],X):-
                     last_element(T,X).

I want to get something like: K=[a,b,d] etc.. when I run this code : path(a,d,K) but its not showing up. only true shows up.

Want to know why. thanks

Upvotes: 1

Views: 251

Answers (2)

Sufian Latif
Sufian Latif

Reputation: 13356

In your code, Path is not updated in the recursive rule. Change it like this:

path_1(A,B,P,Path):-
              edge(A,X),\+member(X,P),append(P,[X],NewP),
              path_1(X,B,NewP,P1), append([A], P1, Path).

And it runs well :)

When it is clear that there is an A-X edge and an X-B path, the A-B path should be A + X-B path.

Upvotes: 1

thanos
thanos

Reputation: 5858

The P variable in path/3 will be instantiated when the Path variable in path_1/4 is instantiated.
However, you never use Path in path_1/4 and therefore the variable does not bind to the results as you observed

Since you use swi-prolog you should get a warning like "Singleton variables: [Path]".
While sometimes it is ok to ignore such a warning, most of the times your code is not going to work as you expected

Upvotes: 0

Related Questions