Reputation: 2005
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.
Upvotes: 12
Views: 7146
Reputation: 22803
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 evaluationUpvotes: 18