not member rule in prolog doesn't work as expe

2019-07-28 18:32发布

问题:

I'm trying to write a simple maze search program in prolog, before I add a room to visited list I'm checking whether it is already a member of the visited list. However, I can't get this to work, even if I use the code from the book:

d(a,b).
d(b,e).
d(b,c).
d(d,e).
d(c,d).
d(e,f).
d(g,e).


go(X, X, T).
go(X, Y, T) :-
    (d(X,Z) ; d(Z, X)),
    \+ member(Z,T),
    go(Z, Y, [Z|T]).

What do I do wrong?

回答1:

Your program seems to be ok. I guess the problem is that you are calling go/3 with the third argument uninstantiated. In that case it will member(X, T) will always succeed, thus failing the clause.

You might call your predicate with the empty list as the third parameter: e.g.

?- go(a, g, []).
true

If you want to return the path consider adding another parameter to go, like this:

go(From, To, Path):-
  go(From, To, [], Path).

go(X, X, T, T).
go(X, Y, T, NT) :-
    (d(X,Z) ; d(Z, X)),
    \+ member(Z,T),
    go(Z, Y, [Z|T], NT).


标签: prolog