一旦返回所需的值,如何停止序言中的递归? [英] How to stop the recursion in prolog, once the desired value is returned?

查看:51
本文介绍了一旦返回所需的值,如何停止序言中的递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在咨询的 .pl 文件是这样的

The .pl file that I am consulting looks like this

spouse(eddard_stark,catelyn_stark).
spouse(X,Y):-spouse(Y,X).

我在这里基本上想要的程序是如果Eddard 是 Catelyn 的配偶",那么Catelyn 是 Eddard 的配偶".

What I fundamentally wanted program here was that if 'Eddard is spouse of Catelyn' then 'Catelyn is spouse of Eddard'.

但是当我查询 spouse(eddard_stark, X). 这会导致 catelyn_stark 的无限递归返回.一旦达到所需的输出,我不确定如何在 Prolog 中停止递归.

But when I query spouse(eddard_stark, X). this goes into an endless recursive return of catelyn_stark . I am not sure how to stop recursion in Prolog once desired output is reached.

另外,如果您想到此问题的任何替代解决方案,请提及,我非常感谢您的意见.

Also if you think of any alternate solution for this problem please mention it, I highly appreciate your views.

推荐答案

它将无休止地交换参数.您可以使用两个谓词来解决这个问题,一个spouse_data/2例如包含:

It will keep swapping the parameters endlessly. You can solve this problem by using two predicates, one spouse_data/2 for example that contains:

spouse_data(eddard_stark,catelyn_stark).

然后是一个谓词spouse/2,它试图在两个方向上调用谓词:

and then a predicate spouse/2 that tries to call the predicate in two directions:

spouse(X, Y) :-
    spouse_data(X, Y).
spouse(X, Y) :-
    spouse_data(Y, X).

这篇关于一旦返回所需的值,如何停止序言中的递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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