Search code examples
prologprolog-toplevel

Prolog. In a query, how to put a condition on a variable that I do not want in the results?


Imagine that I have the following knowledge base which gives for each person his first name and his age.

person(mary, 39).
person(john, 24).
person(sandy, 17).

Now, I want to retrieve all the persons that are older than 20 years. Furthermore, I just want to collect their first names and not their age. Here, I want to retrieve mary and john.

How to do this generally in Prolog and more specifically in SWI-Prolog?

If we use a variable which is not anonymous, like:

?- person(X, Y), Y > 20.

Prolog will give me the values for both X and Y and I do not want Y.

I cannot use the anonymous variable _ because Prolog cannot link its two instantiations. The following gives an error:

?- person(X, _), _ > 20.

So, how to do this?


Solution

  • Why don't you define a predicate

    ofintrest(X):- person(X,Y),Y>20.
    

    an query

    ofintrest(X).
    

    If you don't want to define a predicate you could also use double negation

    person(X,_) ,\+(\+ (person(X,Y), Y>20))