PrologEZ
Foundations · Lesson 5 of 43

Rules

Deriving new knowledge with :- (if), commas (and) and semicolons (or).

Facts are things we state. Rules let Prolog derive new facts. A rule has a head and a body, separated by :- which you read as "if":

head :- condition1, condition2, ... .

The comma means and. Here is a family database, and a rule defining grandparent/2:

parent(tom, bob).
parent(tom, liz).
parent(bob, ann).
parent(bob, pat).
parent(pat, jim).

male(tom). male(bob). male(jim).
female(liz). female(ann). female(pat).

% G is a grandparent of C if G is a parent of some P, and P is a parent of C.
grandparent(G, C) :- parent(G, P), parent(P, C).
?- grandparent(tom, Who)
?- grandparent(Who, jim)

Variables in a rule are local to that rule. P above links the two conditions: whatever person makes parent(G, P) true must also be the one in parent(P, C). Prolog searches for a value of P that satisfies both.

More rules, and a new operator

A \= B means "A and B cannot be made equal", handy to say "two different people".

sibling(A, B) :- parent(P, A), parent(P, B), A \= B.
father(F, C) :- parent(F, C), male(F).
mother(M, C) :- parent(M, C), female(M).
?- sibling(ann, Who)
?- father(Who, ann)
?- mother(Who, Kid)

That last query asked for every mother–child pair. liz has no children in this data, so only pat (mother of jim) qualifies.

"Or": several clauses, or a semicolon

Writing several rules with the same head gives you or: Prolog tries each in turn.

person(X) :- male(X).
person(X) :- female(X).

% a semicolon inside one body also means "or"
related(X, Y) :- parent(X, Y) ; parent(Y, X).
?- person(X)
?- related(bob, Who)

Exercise: Define an aunt

The family facts and sibling/2 are already loaded for you. Write a rule aunt(A, N): A is an aunt of N if A is female and a sibling of one of N's parents.