1
votes

I am doing a prolog question and need to make a single predicate (a rule) for grandfather/2 and grandmother/2 that uses the pre-existing father/2 mother/2 facts. I have got the rest of it working for example:

male(philip).
male(charles).
male(andrew).
male(william).
.....
female(diana).
female(camilla).
female(meghan).
female(kate).
....
married(charles, camilla).
married(harry, meghan).
married(mark, anne).
married(mike, zara).
....
father(philip, charles).
father(philip, andrew).
father(william, george).
father(william, charlotte).
....
mother(elizabeth, charles).
mother(kate, gerge).
mother(anne, zara).
mother(diana, william).

I've been stuck on getting the grandfather/2 and grandmother/2 bit to work for a while now, just wondering if anyone can help me, Thanks :).

1
What did you try? What is not working with that? - Willem Van Onsem
I tried grandfather(X, Y) :- father(X, Z), father(Z, Y). grandfather(X, Y) :- father(X, Z), mother(Z, Y). - Brody2019
what problems do you encounter with this? - Willem Van Onsem
when I try querying Prolog with: grandfather(philip,X) - to see who Philip is a grandfather to. grandfather(X,charlotte) - to see who Charlotte's grandfather is. I dont get anything back. - Brody2019
you're missing Luise :) - CapelliC

1 Answers

0
votes

The direction of the predicate father(A, B). is that A is the father of B. X is a grandfather of Z given there exists a person Y such that X is the father of Y and Y is a parent of Z.

It therefore might be better to first implement a predicate parent/2:

parent(X, Y) :-
    father(X, Y).
parent(X, Y) :-
    mother(X, Y).

grandfather(X, Z) :-
    father(X, Y),
    parent(Y, Z).

With the above facts however, you will not get any results, because you did not define enough facts for a grandparent relation.

You thus can add extra facts like:

father(philip, charles).
father(philip, andrew).
father(charles, william).
father(charles, harry).
father(william, george).
father(william, charlotte).

mother(elizabeth, charles).
mother(kate, gerge).
mother(anne, zara).
mother(diana, william).

This then gives us as grandfather/2 results:

?- grandfather(X, Y).
X = philip,
Y = william ;
X = philip,
Y = harry ;
X = charles,
Y = george ;
X = charles,
Y = charlotte ;
false.