0

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

false
  • 10,264
  • 13
  • 101
  • 209
userJoe
  • 73
  • 2
  • 12
  • 1
    I am pretty sure that this was an example in my very first lesson in learning Prolog. Did you try anything? – Kijewski Nov 05 '16 at 19:23

1 Answers1

1

Assume the following tree, children in red

enter image description here

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.

Limmen
  • 1,407
  • 11
  • 17