Logic Programming and PROLOG
Logic Programming and PROLOG
Section 8.4
Appendix A.12
A database of facts:
inclass(john, cmsc330).
inclass(mary, cmsc330).
inclass(george, cmsc330).
inclass(jennifer, cmsc330).
inclass(john, cmsc311).
inclass(george, cmsc420).
inclass(susan, cmsc420).[.5ex]
takingboth(john) takingboth(Y)
yes Y=john.
no
PZ08B Programming Language design and Implementation -4th Edition 7
Copyright©Prentice Hall, 2000
Prolog execution
So Prolog is:
1. A database of facts.
2. A database of queries.
3. A sequential execution model: Search facts in
order looking for matches. If failure, back up to
last match and try next entry in database.
Data:
Integers: 1, 2, 3, 4
Reals: 1.2, 3.4, 6.7
Strings: 'abc', '123'
Facts: lower case names
Variables: Upper case names
Lists: [a, b, c, d]
Like ML: [ head | tail ]
REVERSE:
reverse([ ],[ ]).
reverse( [H | T ], L) :- reverse(T,Z), append(Z, [H], L).
Logical predicates:
P :- a, b.
P :- c,d.
P is true if a and b are true or if c and d are
true, or (a b) (c d)
(This is where the term logic programming comes from.)
But:
P :- a, !, b.
P :- c,d.
P is true if (a and b) are true or if (a is false and
(c and d are true))
(a b) (not(a) c d) ( See difference?)
Not definition:
not(X) :- X, !, fail.
not(_).
If X succeeds, then fail (! prevents backtracking), and
if X fails then the second definition always
succeeds.
Assignment:
X is 3+1 means arithmetic value
X = 3+1 means same expression
X=3+1, X=4 fails (X unifies to expression 3+1.
The expression 3+1 is not 4.)
X is 3+1, X=4 succeeds (X unifies to 4.)
root(A, B, C) = -B + sqrt(B*B-4*A*C)/(2*A)
Now consider:
P(c+d, Q(e+f)) = (c+d)*Q(e+f) = (c+d) * (e+f)2
P(c+d, Q(e+f)) = P(c+d, (e+f)2) = (c+d) * (e+f)2
Same result achieved two ways, substitute into P first or
into Q.
(c+d) * (e+f)2 represents both a substitution into P and
a substitution into Q.
• The P substitution is c+d for x, Q(e+f) for y.
• The Q substitution is e+f for z.
So we say c+d for x and Q(e+f) for y and e+f for z
unifies P and Q.
Example:
append([2,3],[4,5],L) L=[2,3,4,5] unifies clause.
append([1,2],L,M), reverse(M,[3,2,1])
L=[3], M=[1,2,3] unify these clauses.
Note in this last case, M came from reverse, L came from
append. Substitution works both ways and .
PZ08B Programming Language design and Implementation -4th Edition 18
Copyright©Prentice Hall, 2000