【问题标题】:Prolog and ancestor relationshipProlog和祖先关系
【发布时间】:2012-01-25 20:19:51
【问题描述】:

我必须编写一个小的序言程序来检查给定的人是否是第二个人的祖先。 这些是事实和规则:

mother(tim, anna).
mother(anna, fanny).
mother(daniel, fanny).
mother(celine, gertrude).
father(tim, bernd).
father(anna, ephraim).
father(daniel, ephraim).
father(celine, daniel).

parent(X,Y) :- mother(X,Y).
parent(X,Y) :- father(X,Y).

测试一个人是否是另一个人的祖先很容易:

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

但现在我必须编写一个方法祖先(X,Y,Z),它也打印出两个人之间的关系。它应该是这样的

?- ancestor(ephraim, tim, X).
false.
?- ancestor(tim, ephraim, X).
X = father(mother(tim)).

这就是问题所在:我不知道该怎么做。

【问题讨论】:

    标签: prolog


    【解决方案1】:

    您可以使用累加器来调整@Scott Hunter 的解决方案:

    mother(anna, fanny).
    mother(daniel, fanny).
    mother(celine, gertrude).
    father(tim, bernd).
    father(anna, ephraim).
    father(daniel, ephraim).
    father(celine, daniel).
    
    ancestor(X, Y, Z) :- ancestor(X, Y, X, Z).
    ancestor(X, Y, Acc, father(Acc)) :- father(X, Y).
    ancestor(X, Y, Acc, mother(Acc)) :- mother(X, Y).
    ancestor(X, Y, Acc, Result) :-
        father(X, Z),
        ancestor(Z, Y, father(Acc), Result).
    ancestor(X, Y, Acc, Result) :-
        mother(X, Z),
        ancestor(Z, Y, mother(Acc), Result).
    

    edit :正如 Scott Hunter 在他的编辑中所展示的,这里不需要显式的累加器,因为我们可以在每次迭代时轻松地让术语的内部部分不受约束。因此他的解决方案更好!

    【讨论】:

    • “适应”:这是说“修复”的礼貌方式。
    【解决方案2】:

    @Mog 的累加器技术的术语操作替代方案:

    parent(X, Y, mother(X)) :- mother(X, Y).
    parent(X, Y, father(X)) :- father(X, Y).
    
    ancestor(X, Y, R) :-
        parent(X, Y, R).
    ancestor(X, Y, R) :-
        parent(X, Z, P),
        ancestor(Z, Y, A),
        eldest(A, P, R).
    
    eldest(A, P, R) :-
        A =.. [Af, Aa],
        (   atom(Aa)
        ->  T = P
        ;   eldest(Aa, P, T)
        ),
        R =.. [Af, T].
    

    为了测试,我给 tim 做了个父亲:father(ugo, tim).

    ?- ancestor(tim, ephraim, X).
    X = father(mother(tim)) .
    
    ?- ancestor(ugo, ephraim, X).
    X = father(mother(father(ugo))) .
    

    【讨论】:

      【解决方案3】:

      只需添加一个术语来说明在每个步骤中使用哪种父级(编辑以按正确顺序获得结果):

      ancestor(X,Y,father(X)) :- father(X,Y).
      ancestor(X,Y,mother(X)) :- mother(X,Y).
      ancestor(X,Y,father(Z2)) :- father(Z,Y), ancestor(X,Z,Z2).
      ancestor(X,Y,mother(Z2)) :- mother(Z,Y), ancestor(X,Z,Z2).
      

      【讨论】:

      • 不幸的是不太正确:祖先(蒂姆,以法莲,X)。返回母亲(父亲(安娜))。我试图修复它,但我不明白。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多