I'm learning the basics of Prolog and I was wondering why the following line prints X = 1
instead of true
?
?- X=1,1=X.
X = 1.
--
The first X=1
in my command is an assignment, and the second one will be a check of equality.
I'm learning the basics of Prolog and I was wondering why the following line prints X = 1
instead of true
?
?- X=1,1=X.
X = 1.
--
The first X=1
in my command is an assignment, and the second one will be a check of equality.
There are no assignments or equality tests in your query, only unification of terms. The query succeeds by unifying the variable X
with 1
and that's what the top-level reports: it tells which variable bindings makes the query true.
After the first goal in the conjunction, X = 1
, succeeds, the second goal is the unification 1 = 1
, which trivially succeeds.
P.S. Also note that Prolog systems differ in the way they report successful queries. Some print true
, others print yes
(the traditional way that successful queries are reported).
When the answer is true and a value is bound to variable at the top level, the value of the variable is displayed, which implies the result was true.
Here are some examples.
test_01 :-
X = 1,
X = 1.
test_02 :-
X = 1,
X = 2.
test_03(X) :-
X = 1,
X = 1.
test_04(X) :-
X = 1,
X = 2.
and when the examples are run from the top level using SWI-Prolog
?- test_01.
true.
?- test_02.
false.
?- test_03(X).
X = 1.
?- test_04(X).
false.
Here are some examples that are done only in the top level
?- X=1.
X = 1.
?- 1=1.
true.
?- 1=0.
false.
?- 1==0.
false.
The first X=1 in my command is an assignment, and the second one will be a check of equality.
X=1
is not an assignment it is a unification of the integer 1 to the variable X. The second X=1
is not a check of the equality, it is another unification of X to 1, but since X is bound to 1 by this time, it is really a different unification.
To do equality checking in Prolog use ==
, e.g.
?- 1 == 1.
true.
?- 1 == 2.
false.
Also ,
is the logical and, so if
?- X = 1.
X = 1.
then 1 is bound to X and is true and similar for the second line in your question.
However the code has to be also viewed as
?- true,true.
true.
as opposed to
?- true,false.
false.
While ;
is logical or
?- true;true.
true ;
true.
?- true;false.
true ;
false.
?- true;false;true.
true ;
true.
?- false;true.
true.
?- false;false.
false.
Notice that the first 3 answers have 2 results, but the last two answers have 1 result.