问题
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