Unification¶
"Love is the supreme unifying principle of life." - Martin Luther King, Jr.
Although Prolog can feel very "declarative", using Prolog effectively requires understanding how Prolog works under the hood. There are two fundamenatal technologies required to execute queries in Prolog; the first is unification.
Unification¶
Unification is the process of giving values to (undefined) variables so that two terms or formulas become literally equal.
For example, if Prolog is working on the goal
and it encounters the database fact
then Prolog use the fact to prove the goal by unifying match by setting
Unification is different from variable assignments in languages like Python or Java in two key ways:
-
First, Prolog variables start out uninitalized, but if they have value we cannot change it.
(Later on we'll see there are cases where "backtracking" resets variables to be uninitialized, which and then we can set a different value for the variable, but the general rule holds: if the variable has a value, we cannot reassign to the variable.)
So if we have already decided that
A = appleand later in the same run of the program we try to unify the querywith the database fact
this second unification will fail! Once we have decided that
A = applethere's no difference betweenpairs(A, ginger)andpairs(apple, ginger), and there's no way for unification to makepairs(apple, ginger)the same aspairs(banana, ginger)sinceappleandbananaare constants, not variables. -
More interestingly, unification is bidirectional. The two terms being unified can have variables on either or both sides, and unification will set as many variables as necessary to make the terms equal. For example, if we unify the query
with the database fact
then Prolog could decide
successfully turning both into
pairs(walnut,walnut)(since ifAis defined to be the same asX, andXis defined to bewalnut, thenAis automatically the same as walnut`).An even more interesting case arises if we unify the query
with the database fact
Here Prolog could set
leaving
Buninitalized; turning both intopairs(B,B)is enough to make them the same.
Previous: 4.1 Logic Programming
Next: 4.3 Depth-First Search