表达“交换性"的替代方法在序言中? [英] Alternative to express "Commutativity" in Prolog?

查看:59
本文介绍了表达“交换性"的替代方法在序言中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 Prolog 的初学者,我发现 Prolog 中的交换表达式很不直观.

as a beginner to Prolog, I found the commutative expression in Prolog are quite not intuitive.

例如如果我想表示 X 和 Y 在一个家庭中,例如:

for example if I want to express X and Y are in one family, like:

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

我还应该在定义中添加以下内容,以使其可交换":

I should also add the following to the definition, in order to make it "commutative":

      married(Y,X);
      relative(Y,X);
      father_son(Y,X).

但是我们使用Prolog,因为我们想写优雅的代码......所以,我希望在原来的基础上只添加一行(而不是上面的三行):

But we use Prolog, because we want to write elegant code... so, I'd hope to add only one line(instead of the above three) to the original :

      family(Y,X).

这是重点.它会导致终止!为什么序言没有那么合乎逻辑"?是否有替代这种不会导致终止的简洁的单行表达式?

Here is the POINT. it leads to untermination! why is prolog no so "logical"? and is there an alternative to this neat one line expression that doesn't lead to untermination?

周末愉快!瓦特

推荐答案

family(X,Y) 的问题 :- family(Y,X). 部分规则是它保持在每一层无条件地与自身统一,并不断向下递归;这个递归没有退出条件.

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).

您现在可以按如下方式重写您的 family 规则:

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).

这篇关于表达“交换性"的替代方法在序言中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆