Prolog programming - simple negative query
My database is:
eat(magi,limo).
eat(nona,banana).
How do I ask: "Who's not eating limo?" T开发者_如何学JAVAhis:
eat(X,not(limo)).
Doesn't work. :(
First of all limo
is a symbol and you can't negate symbols. What you want to do is negate the predicate, i.e. not(eat(X, limo))
.
However this still does not give you nona
as a result. Why not? Well there are infinitely many values X for which eat(X, limo)
will be false. The system needs more information than "X does not eat limo" to know which one you want. Instead we need to ask for an X
such that "X eats something, but X does not eat limo". This leads us to the following query:
eat(X,Y), not(eat(X, limo)).
Which gives us nona
as the solution for X
.
eat(X, Y), Y \= limo, writeln(X), false.
精彩评论