有没有一种方法可以在经过一定次数的迭代后在prolog中停止递归?

有没有一种方法可以在经过一定次数的迭代后在prolog中停止递归?,prolog,Prolog,这是我写的代码 passesBatonTo(bob, doug). passesBatonTo(doug, steve). passesBatonTo(steve, sam). passesBatonTo(sam, bob). getRelayTeam(X):- passesBatonTo(X, Y), write(Y), nl, getRelayTeam(Y). 我想把代码交给整个接力小组,但代码进入无限循环。 getRelayTeam(bob)应该给bob、d

这是我写的代码

passesBatonTo(bob, doug).
passesBatonTo(doug, steve).
passesBatonTo(steve, sam).
passesBatonTo(sam, bob).

getRelayTeam(X):-
    passesBatonTo(X, Y),
    write(Y), nl,
    getRelayTeam(Y).

我想把代码交给整个接力小组,但代码进入无限循环。
getRelayTeam(bob)应该给bob、doug、steve、sam


getRelayTeam(steve)应该给steve、sam、bob、doug一个倒计时值你可以试试这个技巧:

passesBatonTo(bob, doug).
passesBatonTo(doug, steve).
passesBatonTo(steve, sam).
passesBatonTo(sam, bob).

% getRelayTeam(X,RelaysLeft)

getRelayTeam(X,0) :- 
   !, % tell Prolog there is no point in trying the next clause if this head matched
   format("No more relays for you, ~q is the last carrier!\n",[X]).

getRelayTeam(X,RelaysLeft) :-
    RelaysLeft > 0, % make clear we want RelaysLeft > 0 (even though we use ! above)
    passesBatonTo(X, Y),
    format("Passed baton from ~q to ~q\n",[X,Y]),
    succ(RelaysLeftNow,RelaysLeft),
    getRelayTeam(Y,RelaysLeftNow).
因此:

?- getRelayTeam(bob,4).
Passed baton from bob to doug
Passed baton from doug to steve
Passed baton from steve to sam
Passed baton from sam to bob
No more relays for you, bob is the last carrier!
true.