给出以下知识库:
cityinCountry(paris, france ) . /* Paris is a city in France*/
cityinCountry(berlin, germany).
cityinCountry(cairo, egypt).
cityinCountry(munich, germany).
为什么cityinCountry(_City, germany).
返回True
,而cityinCountry(City, germany).
返回berlin;慕尼黑
?
我对变量的定义表明它们由以大写字母或下划线(_)开头的标识符表示。然而我的两个例子表现不同。有人可以解释一下吗?
最佳答案
它仍然是一个变量,但是通过在查询中使用这个名称,您就告诉 Prolog(或者至少是 Prolog 的实现)您不想显示它的值。例如。 cityInCountry(_City, Country)
将打印预期的四个结果,但仅显示 Country
值。
奇怪的是,我找不到这方面的明确文档,例如在 http://www.swi-prolog.org/pldoc/man?section=singleton 。它给出的唯一区别是
A singleton variable is a variable that appears only one time in a clause. It can always be replaced by _, the anonymous variable. In some cases, however, people prefer to give the variable a name. As mistyping a variable is a common mistake, Prolog systems generally give a warning (controlled by style_check/1) if a variable is used only once. The system can be informed that a variable is meant to appear once by starting it with an underscore, e.g.,
_Name
.
我能找到的最接近的是 http://www.cse.unsw.edu.au/~billw/dictionaries/prolog/dontcare.html :
This indicates what the _ variable is actually representing, but has the feature that the binding of
_Anybody
typically doesn't get reported when Prolog finds a solution.
但是 _Anybody
位于规则主体内,无论如何都不会在现代 Prolog 实现中报告。
关于Prolog 变量名以下划线开头,然后大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54909665/