序言.在查询中,如何在结果中不想要的变量上放置条件? [英] 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).
现在,我想检索所有 20 岁以上的人.此外,我只想收集他们的名字而不是他们的年龄.在这里,我想检索 mary
和 john
.
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
.
一般如何在 Prolog 中,更具体地说,在 SWI-Prolog 中如何做到这一点?
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 会给我 X
和 Y
的值,我不需要 Y
.
Prolog will give me the values for both X
and Y
and I do not want Y
.
我不能使用匿名变量 _
因为 Prolog 不能链接它的两个实例.以下给出了一个错误:
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?
推荐答案
为什么不定义谓词
ofintrest(X):- person(X,Y),Y>20.
查询
ofintrest(X).
如果你不想定义谓词,你也可以使用双重否定
If you don't want to define a predicate you could also use double negation
person(X,_) ,\+(\+ (person(X,Y), Y>20))
这篇关于序言.在查询中,如何在结果中不想要的变量上放置条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!