How to stop the recursion in prolog, once the desired value is returned?

若如初见. 提交于 2021-01-28 19:51:02

问题


The .pl file that I am consulting looks like this

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

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

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.


回答1:


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

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


来源:https://stackoverflow.com/questions/63317159/how-to-stop-the-recursion-in-prolog-once-the-desired-value-is-returned

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