Here is what I have understood about Prolog variables.
A single underscore stands for anonymous variable, which is like a new variable each time it occurs.
A variable name starting with underscore like _W is not an anonymous variable. Or, the variable names generated inside Prolog, like _G189, is not considered anonymous:
?- append([1,2],X,Y).
X = _G189
Y = [1, 2|_G189]
Could you please help me understand?
By the way, I got the above example from some tutorials, but when I run it in SWI-Prolog version 6, I get the following:
?- append([1,2],X,Y).
Y = [1, 2|X].
Thanking you.
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 _
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With