In this sense the prolog is quite simple. First define the basic characteristics of father, mother, etc ... In your case:
We define what a mother and father are:
mother(X, Y) :- parent(X, Y), female(X).
father(X, Y) :- parent(X, Y), male(X).
We define what grandpa and grandma are:
grandfather(X,Y) :- parent(X,Z), parent(Z,Y), male(X)
grandmother(X,Y) :- parent(X,Z), parent(Z,Y), female(X)
What have we done?
Let's analyze the predicate of mother(X,Y)
:
This is analyzed as follows: to know if X
is mother of Y
we have said that X
has to be parent
of Y (her father / mother) and X
has to be female
(female)
To finish your example, we define the relationships exposed in your statement:
We define who is male and female:
male(pedro).
male(jose).
female(clara).
female(ana).
-
Clara is the mother of Pedro
mother(clara, pedro).
-
Pedro is the father of jose
father(pedro, jose).
-
ana is the mother of clara
mother(ana, clara).
-
jose is the father of clara
mother(jose, clara).
When we have everything defined, we ask ourselves the questions, to do so, we use ? -
followed by the question:
-
Is José's grandmother clear?
? - grandmother(clara,jose). -- yes
-
Is Pedro Blanco's grandfather?
? - grandfather(pedro,clara). -- yes
So the final code would be:
female(clara).
female(ana).
male(pedro).
male(jose).
parent(clara, pedro).
parent(pedro, jose).
parent(ana, clara).
parent(jose, clara).
mother(X, Y) :- parent(X, Y), female(X).
mother(clara, pedro).
mother(ana, clara).
father(X, Y) :- parent(X, Y), male(X).
father(pedro, jose).
father(jose, clara).
grandmother(X,Y) :- parent(X,Z), parent(Z,Y), female(X).
grandfather(X,Y) :- parent(X,Z), parent(Z,Y), male(X).
? - grandmother(clara,jose).
? - grandfather(pedro,clara).
Where BOTH are true
since there is a cycle in the definition.
Ana
Clara
Pedro
Jose (who is also Clara's father)