The problem that I face, is a bit trivial. I want to use logical not in Prolog, but it seems that not/1
is not the thing that I want:
course(ai). course(pl). course(os). have(X,Y) :- course(X),course(Y),not(X = Y).
I query:
have(X,Y), write(X-Y), nl , fail.
And I do not get the result I want :(
not(X) is the way to implement negation in Prolog; however not(X) does not mean that X is false, it means that X can't be proven true. For example, with the database: man('Adam').
The not predicate is used to negate some statement, which means, when a statement is true, then not(statement) will be false, otherwise if the statement is false, then not(statement) will be true. If X and Y match, then different(X,Y) fails, Otherwise different(X,Y) succeeds.
A single underscore ( _ ) denotes an anonymous variable and means "any term". Unlike other variables, the underscore does not represent the same value everywhere it occurs within a predicate definition. A compound term is composed of an atom called a "functor" and a number of "arguments", which are again terms.
sign prevents backtracking of the clauses to the right of it to the left, it's like a one-way gate so that it won't backtrack beyond the cut.
In place of not(X = Y)
you need to write \+ X = Y
or X \= Y
. But consider to use dif(X,Y)
instead. dif/2
is present in B, SWI, YAP, SICStus. To see the difference:
?- X = b, dif(a, X). X = b. ?- X = b, \+ a = X. X = b.
So up to now everything seems to be fine. But what, if we simply exchange the order of the two goals?
?- \+ a = X, X = b. false. ?- dif(a, X), X = b. X = b.
(\+)/1
now gives us a different result, because there is an answer for a = X
, the goal \+ a = X
will fail.
(\+)/1
is thus not negation, but means not provable at this point in time.
A safe approximation of dif/2
is possible in ISO Prolog, too.
In both SWI-Prolog and GNU Prolog, the following should work:
have(X, Y) :- course(X), course(Y), X \= Y.
In SWI-Prolog, you can also use dif/2
, which can be more convenient since you can use it earlier in the predicate:
have(X, Y) :- dif(X, Y), course(X), course(Y).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With