Alternative to express “Commutativity” in Prolog?

牧云@^-^@ 提交于 2019-12-05 05:02:18

The problem with family(X,Y) :- family(Y,X). part of the rule is that it keeps unifying unconditionally with itself at each level, and keeps recursing down; there is no exit condition out of this recursion.

You should make the argument swap at the level above:

family(X,Y) :-
    is_family(X,Y);
    is_family(Y,X).

is_family(X,Y) :-
    married(X,Y);
    relative(X,Y);
    father_son(X,Y).

Alternatively, you could make underlying rules below symmetric where it makes sense:

is_married(X,Y) :-
    married(X,Y);
    married(Y,X).

is_relative(X,Y) :-
    relative(X,Y);
    relative(Y,X).

You could now rewrite your family rule as follows:

family(X,Y) :-
    is_married(X,Y);
    is_relative(X,Y);
    father_son(X,Y);
    father_son(Y,X).
Eric

How about:

relatives(X,Y) :-
  married(X,Y);
  relative(X,Y);
  father_son(X,Y).

family(X,Y) :-
  relatives(X,Y);
  relatives(Y,X).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!