我可以使用整数作为参数吗?

Bis*_*p19 1 prolog

我如何知道一个人X是否是一个Y的后代,给出了下降度?

我试过这个:

descendant(X, Y, 1) :- son(X, Y).
descendant(X, Y, Degree) :- son(X, Z) , descendant(Z, Y, Degree-1).
Run Code Online (Sandbox Code Playgroud)

son(X, Y)返回yes如果X是Y的儿子如果Degree == 1它返回正确的答案,但对于descendant(X, Y, 2),例如,应该返回yes如果X为Y,但回报的孙子no.

rep*_*eat 5

1)命名:是否 son(X,Y)意味着" X是的儿子Y" -或者反之亦然? son_of(X,Y)更好.

2)利用:我们不需要在这里做一般的算术......我们只需要数数.


因此,让我们开始一开始 ...

child_of(abel, adam).           % from source
child_of(abel, eve).
child_of(cain, adam).
child_of(cain, eve).
child_of(enoch, cain).
child_of(irad, enoch).
child_of(mehujael, irad).
child_of(methushael, mehujael).
child_of(lamech, methushael).
child_of(jabal, lamech).
child_of(jabal, adah).
child_of(jubal, lamech).
child_of(jubal, adah).
child_of(tubal_cain, lamech).
child_of(tubal_cain, zillah).
child_of(naamah, lamech).
child_of(naamah, zillah).
child_of(seth, adam).
child_of(seth, eve).
child_of(enos, seth).
child_of(kenan, enos).
child_of(mahalalel, kenan).
child_of(jared, mahalalel).
child_of(enoch, jared).
child_of(methuselah, enoch).
child_of(lamech, methuselah).
child_of(noah, lamech).
child_of(shem, noah).
child_of(ham, noah).
child_of(japheth, noah).

基于child_of/2我们首先定义ancestor_of/2- 这应该对你来说不是什么新鲜事!

ancestor_of(Y, Z) :-
   child_of(Z, Y).              %   If Z is  a    child of Y ...
                                % then Y is an ancestor of Z.
ancestor_of(X, Z) :-
   child_of(Z, Y),              %   If Z is  a    child of Y ...
   ancestor_of(X, Y).           %  and X is an ancestor of Y ...
                                % then X is an ancestor of Z.

接下来,我们添加一个指示距离的附加参数.

我们使用s/1术语来表示自然数,并添加一个新参数ancestor_of/2:

ancestor_of_dist(Y, Z, s(0)) :-      
   child_of(Z, Y).              %   If Z is  a    child of Y ... 
                                % then Y is an ancestor of Z with distance = 1."
ancestor_of_dist(X, Z, s(N)) :-      
   child_of(Z, Y),              %   If Z is  a    child of Y ... 
   ancestor_of_dist(X, Y, N).   %  and X is an ancestor of Y with distance N ...
                                % then X is an ancestor of Z with distance N+1.

那么......谁是祖父母?

?- ancestor_of_dist(X, Z, s(s(0))).
   X = adam, Z = enoch
;  X = eve, Z = enoch
;  X = cain, Z = irad
;  X = jared, Z = irad
;  X = enoch, Z = mehujael
;  ... 
;  X = lamech, Z = japheth
;  false.