John Smith
John Smith

Reputation: 33

Prolog ancestor clause using lists

I am struggling to get my head around this basic Prolog concept.

I understand that the basic clause for determining the ancestor of a person is as follows:

ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).

However, I am trying to get my head around how this works for a prolog program that implements lists to determine children of a parent, i.e:

parent_of(simon, [matthew, andrea, joanne]).

To determine wether or not somebody is the father of somebody, I am using this which works perfectly:

father_of(X, Y) :- parent_of(X, List), my_member(Y, List), male(X).

However, I cant seem to figure out how to get this to work for the ancestor clause above.

Upvotes: 3

Views: 397

Answers (1)

CapelliC
CapelliC

Reputation: 60024

member/2 it's the simpler relation between an element and a list:

ancestor_of(X, Y) :- parent_of(X, Ys), member(Y, Ys).
ancestor_of(X, Y) :- parent_of(X, Zs), member(Z, Zs), ancestor_of(Z, Y).

I've added a relation to test the transitive rule

parent_of(simon, [matthew, andrea, joanne]).
parent_of(andrea, [bill, joan]).

yields

?- ancestor_of(andrea,A).
A = bill ;
A = joan ;
false.

?- ancestor_of(simon,A).
A = matthew ;
A = andrea ;
A = joanne ;
A = bill ;
A = joan ;
false.

?- ancestor_of(X,bill).
X = andrea ;
X = simon ;
false.

Upvotes: 4

Related Questions