If I wanted to recursively go down a family tree in prolog and return only the children of every branch, how would I start that?
Thanks
If I wanted to recursively go down a family tree in prolog and return only the children of every branch, how would I start that?
Thanks
Assume the following tree, children in red
A simple solution could then be:
male(lennart).
male(mike).
male(donald).
male(usain).
male(joar).
male(adam).
male(dan).
male(simon).
female(hillary).
female(elise).
female(lisa).
female(lena).
parent(mike, lennart).
parent(mike, lena).
parent(lennart, donald).
parent(lennart, hillary).
parent(lennart, usain).
parent(lena, adam).
parent(lena, simon).
parent(adam, dan).
parent(donald, lisa).
parent(hillary, joar).
parent(hillary, elise).
child(lisa).
child(joar).
child(elise).
child(dan).
child(simon).
%% predicate rules
father(X,Y) :- male(X),parent(X,Y).
mother(X,Y) :- female(X),parent(X,Y).
son(X,Y) :- male(X),parent(Y,X).
daughter(X,Y) :- female(X),parent(Y,X).
family_children(X, X):-
child(X).
family_children(X, Child):-
parent(X,Y),
family_children(Y, Child).
Test run:
[debug] ?- family_children(mike, Child).
Child = lisa ;
Child = joar ;
Child = elise ;
Child = dan ;
Child = simon ;
false.
This is just a quick example of how it could be done, the example relies in the assumption that a child cannot have another child, but this could solution could easily be improved and you can add rules like cousin/2
, grandfather/2
, sister/2
, uncle/2
etc...
Hope you got some hang of the idea now, good luck.