Logic Programming Tutorial 1: Prolog Warm-Up
Logic Programming Tutorial 1: Prolog Warm-Up
You should be able to do all of the unstarred exercises before the tutorial session.
You should also be able to do exercises with a single star (*) but these may require
more thought. Exercises with two stars (**) are harder and may involve material
we haven’t covered; try them if you have time.
1. Unification
Without using a computer, find the most general unifiers of the following
unification problems (or determine that they are not unifiable).
p or q :- p.
p or q :- q.
1
Alternatively, Prolog provides syntax for using disjunction within goals. Specif-
ically, if G1 and G2 are goals, we may write G1;G2 for the disjunction of the
two goals.
p or q :- p ; q.
Prolog will try to solve the first goal and if that fails (or if we backtrack) it
will then try the second goal. This syntax is helpful because sometimes we
can use this to avoid writing helper predicates to deal with disjunction.
Define predicate called parent disj/2 whose meaning is the same as parent/2
but uses disjunction. Compare its behavior (with and without tracing) to the
two-clause version.
4. Symmetry
The predicates friend/2 and neighbor/2 are not symmetric and they prob-
ably should be: if X is a friend or neighbor of Y then Y should be a friend or
neighbor of X as well.
One way to do this is simply to add rules such as
friend(X,Y) :- friend(Y,X).
neighbor(X,Y) :- neighbor(Y,X).
Add these rules, and write a query that searches for the catchphrases of Mil-
house’s friend’s parent’s neighbor. Try to find all solutions. Is there a potential
problem with this approach? How might we avoid this problem?
5. (*) Goal ordering
Define predicates aunt/2 and uncle/2 in terms of male, female, parent and
sibling. Observe the behavior of aunt(X,bart), with or without tracing.
Experiment with different goal orderings. Which goal ordering seems to be
the most efficient for the above query?
6. (**) Negation and inequality
The classmate and sibling predicates we defined above may give undesired
answers. Try solving classmate(X,X) or sibling(X,X) to see examples of
this problem.
To avoid this problem, we want to eliminate the pairs (X,X) from the classmate
relation to make it irreflexive. More generally, we often want to use negation
to make exceptions to rules.