Prologue - Recursive Family Tree

I am trying to write a Prolog program in which the male successors of the British Royalty will be printed in order. My attempt:

son(elizabeth, charles).
son(charles, william).
son(charles, henry).
son(elizabeth, andrew).
son(elizabeth, edward).
son(edward, severn).
successor(X, Y) :- son(X, Y).
successor(X, Y) :- son(X, C), successor(C, Y).

The successor function doesn't quite do what I want: the current output is this:

successor(elizabeth, Y).
Y = charles ;
Y = andrew ;
Y = edward ;
Y = william ;
Y = henry ;
Y = severn ;
false.

The first rule displays all three immediate children, then the second rule prints all descendants. But the descendants of the first child must appear before the second immediate child, for example:

successor(elizabeth, Y).
Y = charles ;
Y = william ; % william and henry should come before andrew
Y = henry ;
Y = andrew ;
Y = edward ;
Y = severn ;
false.

This is my first Prolog program, and I don’t understand how to express the right relationship. Can someone give me an idea or pointers to resources that would be useful to me?

+3
source share
3 answers

, Prolog , , . , , , , , , . . , :

successor(X, Y) :- son(X, Z), (Y = Z; successor(Z, Y)).

, Prolog successor(X, Y) :

  • Z, X:
    • Y Z, Z .
    • ; , Y successor/2 , Z.

, , Art of Prolog. , () . , 1994 , eBay.

+4

:

, .

(, successor/2) PROLOG 1- , .. . , PROLOG , - , successor/2 , . , (..);

successor(X, Y) :- son(X, C), successor(C, Y).
successor(X, Y) :- son(X, Y).

, PROLOG :

?- successor(elizabeth, Y).
Y = william ;
Y = henry ;
Y = severn ;
Y = charles ;
Y = andrew ;
Y = edward.

.. .

, , , . ; , -. () , , PROLOG. , successor/2:

successor(Parent, [Son|SonDescendents]) :-
    son(Parent, Son),
    successor(Son, SonDescendents).

- , .

successor(NonParent, []) :-
    \+ son(NonParent, _).

, , ().

:

?- successor(elizabeth, S).
S = [charles, william] ;
S = [charles, henry] ;
S = [andrew] ;
S = [edward, severn] ;
false.

. PROLOG:

,

The Craft of Prolog, '

Prolog, Clocksin Mellish

+2

Your rule set looks good to me, it gives you the correct results, it just prints them as it displays them, which makes the order wrong. Work through the results on paper, and you are likely to get a similar result.

+1
source

Source: https://habr.com/ru/post/1725237/


All Articles