I have entered these statements into the prolog interpreter and am confused by the results. Shouldn't they return the same thing; true?
1 ?- 7 = 5 + 2.
false.
2 ?- 7 is 5 + 2.
true.
Solution. The / operator is used for division whereas % operator is used to find the remainder.
== is for value equality. It's used to know if two objects have the same value. is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical.
State the difference between = and ==. It is the assignment operator used for assigning a value to a variable. It is the equality operator used to check if a variable is equal to another variable or literal. E.g. int a = 10; assigns 10 to variable a. E.g. if (a == 10) checks if variable a is equal to 10 or not.
+ is an arithmetic operator while += is an assignment operator.. When += is used, the value on the RHS will be added to the variable on the LHS and the resultant value will be assigned as the new value of the LHS..
No, because =/2
does not mean assign in Prolog, but rather unify. And the unification algorithm does not know anything at all about arithmetic, just structure. So you can do some interesting things with arithmetic expressions in Prolog that are quite difficult to pull off in other languages:
?- X = 5 + 2.
X = 5+2.
It looks like nothing happened there, but what actually happened is X was given the value "5 + 2" as a structure. Put another way:
?- A + B = 5 + 2.
A = 5,
B = 2.
Or even:
?- X = 5 + 2, X =.. [Op|_].
X = 5+2,
Op = (+).
That last one might make more sense with the whole list though:
?- X = 5 + 2, X =.. Y.
X = 5+2,
Y = [+, 5, 2].
This is an effect of the remarkable "univ" operator, =../2
, which is able to convert between Lisp-like lists and Prolog syntax, enabling you to do interesting construction and decomposition of structures in a generic fashion.
Now, is/2
, on the other hand, does know about arithmetic. It unifies its left argument with the result of arithmetic simplification of its right. Do note that it only works in one direction:
?- 7 is 5 + 2.
true.
?- 5 + 2 is 7.
false.
You could say that =/2
is interested in structure and is/2
is interested in numeric equality. But it does mean that it's unusually easy to teach Prolog algebra:
simplify(X * Y + X * Z, X * (Y + Z)). % distributive property
simplify(X, X).
?- simplify(A * 3 + A * 4, Q).
Q = A* (3+4)
Now, this isn't perfect (note that we got 3+4 and not 7) and it's still a lot of work to make it really smart:
?- simplify(3 * A + 4 * A, Q).
Q = 3*A+4*A.
But that's a problem for another day.
Nutshell:
=/2
triggers unificationis/2
triggers arithmetic evaluationIf 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