In: Computer Science
Most of the input from the terminal to the prompt "?-" are queries.
Question →
?-mother (mary. joe).
This query may be read "Is mary mother of Joe?" Queries end with a period.
Rules
?- [user].
child(X,Y) :- parent(Y,X).
% X is a child of Y if Y is a parent of X. %
mother(X,Y) :- parent(X,Y), female(X).
% X is a mother of Y if X is a female parent of Y
father(X,Y) :- parent(X,Y), male(X).
% X is a father of Y if X is a male parent of Y
son(X,Y) :- child(X,Y), male(X).
% X is a son of Y is X is a male child of Y
son(X,Y) :- child(X,Y), male(Y).
% X is a son of Y if X is a male child of Y.
So it is true that Mary is the mother of Joe
given Sibling(X.Y): Sibling(w.y)
?- [user].
sibling(X,Y) :- parent(Z,X), parent(Z,Y).
// A sibling is someone with the same parent
close-relation(X,Y) :- child(X,Y).
close-relation(X,Y) :- sibling(X,Y).
close-relation(X,Y) :- parent(X,Y).
// A close relation is either a child, or a sibling, or a parent.
When more than one rule is given for a goal, Prolog tries the various rules in the given order.
?- close-relation(anne,charles).
TRUE, so the second rule succeeds
· To extend program
?- close-relation(X,charles).
X = william ;
X = harry ;
X = charles ;
X = charles ;
X = anne ;
X = anne ;
X = andrew ;
X = Mary ;
X = Joe ;
FALSE
Prolog first goes through the answers given by the "child" rule, then the answers given by the "sibling" rule, then the answers given by the "parent" rule.The goal "sibling(charles,X)'' succeeds twice for each sibling of Charles as well as for himself, once for their common parent Mary and once for their common parent Joe.
?- [user].
ancestor(X,X).
ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).
The ancestor relationship is defined recursively in two rules:
Base case: Every man is his own ancestor.
Recursive case:If X is a parent of an ancestor of Y, then X is an ancestor of Y.
A literal with variables and no body, such as "ancestor(X,X)"is a statement that the form is true for all values of the variable ie, for any X "ancestor(X,X)" is true.
?- ancestor(charles,charles).
yes
The query matches the base rule "ancestor(X,X)".