我如何在Prolog中的append / 3之后退出递归

时间:2018-11-18 23:57:44

标签: recursion prolog append

    door_between(bed_room, hidden_chamber).
    door_between(hidden_chamber, basement).       

    rev(L,R) :- my_reverse(L,[],R).
    my_reverse([H|T],A,R) :- my_reverse(T,[H|A],R).
    my_reverse([],A,A).

    path_from(Src,Dest,Path) :-
         path_from(Src,Dest,[],Path),
         rev(Path,Z),
         append(Src,Z,Z).

     path_from(S,S,P,P).
     path_from(S,D,P,NV) :-
         (door_between(S,A) ; door_between(A,S)),
         \+ member(A,P),
         path_from(A, D, [A|P], NV).

这是我的代码,用于在无向房间图中找到路径。似乎在递归过程中获得了正确的结果,但是在某个点调用* Redo,我不明白为什么,这是跟踪。

path_from(bed_room,basement,X).
 * Call: (8) path_from(bed_room, basement, _12282) ? creep
 * Call: (9) path_from(bed_room, basement, [], _12282) ? creep
   Call: (10) door_between(bed_room, _12624) ? creep
   Exit: (10) door_between(bed_room, hidden_chamber) ? creep
   Call: (10) lists:member(hidden_chamber, []) ? creep
   Fail: (10) lists:member(hidden_chamber, []) ? creep
 * Redo: (9) path_from(bed_room, basement, [], _12282) ? creep
 * Call: (10) path_from(hidden_chamber, basement, [hidden_chamber], _12282) ? creep
   Call: (11) door_between(hidden_chamber, _12630) ? creep
   Exit: (11) door_between(hidden_chamber, basement) ? creep
   Call: (11) lists:member(basement, [hidden_chamber]) ? creep
   Fail: (11) lists:member(basement, [hidden_chamber]) ? creep
 * Redo: (10) path_from(hidden_chamber, basement, [hidden_chamber], _12282) ? creep
 * Call: (11) path_from(basement, basement, [basement, hidden_chamber], _12282) ? creep
 * Exit: (11) path_from(basement, basement, [basement, hidden_chamber], [basement, hidden_chamber]) ? creep
 * Exit: (10) path_from(hidden_chamber, basement, [hidden_chamber], [basement, hidden_chamber]) ? creep
 * Exit: (9) path_from(bed_room, basement, [], [basement, hidden_chamber]) ? creep
   Call: (9) rev([basement, hidden_chamber], _12636) ? creep
   Call: (10) my_reverse([basement, hidden_chamber], [], _12638) ? creep
   Call: (11) my_reverse([hidden_chamber], [basement], _12644) ? creep
   Call: (12) my_reverse([], [hidden_chamber, basement], _12650) ? creep
   Exit: (12) my_reverse([], [hidden_chamber, basement], [hidden_chamber, basement]) ? creep
   Exit: (11) my_reverse([hidden_chamber], [basement], [hidden_chamber, basement]) ? creep
   Exit: (10) my_reverse([basement, hidden_chamber], [], [hidden_chamber, basement]) ? creep
   Exit: (9) rev([basement, hidden_chamber], [hidden_chamber, basement]) ? creep

通话:(9)个列表:append(bed_room,[hidden_​​chamber,地下室],[hidden_​​chamber,地下室])吗?爬行

    * Redo: (11) path_from(basement, basement, [basement, hidden_chamber], _12282) ? creep
      Call: (12) door_between(basement, _12636) ?

(破坏代码块的粗体行是我关注的行,由path_from / 3中的append(Src,Z,Z)触发。)在调用处:(9)< / strong>追加,结果列表就是我想要的此特定测试用例的答案,我假设追加将返回[bed_room,hidden_​​chamber,地下室],但接下来的事情是* Redo,我真的很困惑关于为什么,我只是对递归的概念感到困惑?我想我只需要轻轻推一下,就可以把头缠住。

0 个答案:

没有答案