问题
What is the difference between this:
X \= Y
and this piece of code:
dif(X, Y)
I thought that they should behave the same, but they do not. Here's the example:
n_puta(L, N, X) :- nputa(L, N, 0, X).
nputa([], N, C, _) :- N = C.
nputa([G|R], N, C, X) :- G = X, nputa(R, N, Y, X), C is Y - 1.
nputa([G|R], N, C, X) :- dif(G,X), nputa(R, N, C, X).
And here are some calls:
?- n_puta([a,a,b,b,b], 2, X).
X = a ;
false.
?- n_puta([a,a,b,a,b,b], 3, X).
X = a ;
X = b ;
false.
X should be the atom that occurs exactly N times in the list L. If I replace dif(G, X)
with G \= X
, I don't get the expected result. Can someone tell me what is the difference between these two operators? Can I use anything else except dif(G, X)
?
This example works prefectly in SWI-Prolog, but doesn't work in Amzi! Prolog.
回答1:
dif/2
and (\=)/2
are the same as long as their arguments are ground. But only dif/2
is a pure relation that works correctly also with variables and can be used in all directions. Your example clearly shows that you should use dif/2
in this case, because you use your predicate not only to test, but also to generate solutions. The most widely used Prolog systems all provide dif/2
.
来源:https://stackoverflow.com/questions/16560058/difference-between-x-y-and-difx-y