Prolog anonymous variable

半世苍凉 提交于 2019-11-29 09:34:51

Variables

The anonymous variable _ is the only variable where different occurrences represent different variables. Other variables that start with _ are not anonymous. Different occurrences refer to the same variable (within the same scope). However, many Prologs like SWI will warn you should a variable not starting with an underscore occur only once:

?- [user].
a(V).
Warning: user://1:9:
        Singleton variables: [V]

You have to rename that variable to _V to avoid that warning. This is a help for programmers to better spot typos in variable names. There are some more such restrictions in many systems.

a(_V,_V).
Warning: user://1:12:
        Singleton-marked variables appearing more than once: [_V]

Again, this is only a warning. If you want that a variable starting with _ should occur twice (without warning), write __ instead. But better stick to more meaningful names without a starting _.

Answers

What you get from Prolog's top level loop are answers ; and in particular answer substitutions. They serve to represent solutions (that's what we are really interested in). There are several ways how answer substitutions may be represented. The tutorial you are using seems to refer to a very old version of SWI. I would say that this version is maybe 15 to 20 years old.

?- append([1,2],X,Y).
X = _G189
Y = [1, 2|_G189]

However, the answer given is not incorrect: A new auxiliary variable _G189 is introduced.

Newer versions of SWI and many other systems try to minimize the output, avoiding auxiliary variables. So

?- append([1,2],X,Y).
Y = [1, 2|X].

is just as fine. It is the answer of a "newer" version (also some 6 years old). Note that this answer tells you much more than the first one: Not only does it show you the answer substitution more compactly, but it also tells you that there is exactly this one answer (and no more). See the dot . at the end? This means: There is no more here to answer. Otherwise there would be a ; for the next answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!