Prolog 谓词仅在我发送 [ ] "an empty list" 时有效

Prolog predicate works only when I send [ ] "an empty list"

getSwaps(CurrentList,InitialList,L,R) :-
    CurrentList = [H,S,W|_],
    Indexo is L-1,
    nth0(Indexo, InitialList, ReplacingW),
    nth0(StopAt , InitialList , W),
    StopAtIndex is StopAt-1,
    ReplacingW > W,
    NewW is ReplacingW,
    ( not(memberx([H,S,NewW], R)) ->
        NewL is L-1,   
        not(StopAtIndex =:= NewL),!,
        appendx([[H,S,NewW]], R, NewResult),
        getSwaps([H,S,W],InitialList, NewL, NewResult);
        
        NewL is L-1,
        not(StopAtIndex =:= NewL),!,
        getSwaps([H,S,W],InitialList, NewL, R)
    ).
    
getSwaps(_,_,_,R) :- 
    printList(R).

我在 prolog 中编写了这段代码,当我用它进行测试时它运行良好:

?- swapTwice([3,8,9],[3,8,9,10,12,14],6,[]).

但是当我使用变量而不是空列表时,例如

?- swapTwice([3,8,9],[3,8,9,10,12,14],6,Result).

它不会工作,它只会打印这么多以下划线开头的数字 (_32512 _32518 _32524 _32530... 等等) 直到我中止执行才会停止.

我需要使用变量对其进行测试,以便在其他谓词中使用输出。 那么,是什么原因造成的,或者我该如何解决?

向谓词添加一个 TempResult 参数,然后添加另一个少一个参数的谓词并调用它,如下所示:

getSwaps(CurrentList,InitialList,L,R) :- 
    getSwaps(CurrentList,InitialList,L,[],R).

getSwaps(CurrentList,InitialList,L,TempR,R) :-
    CurrentList = [H,S,W|_],
    Indexo is L-1,
    nth0(Indexo, InitialList, ReplacingW),
    nth0(StopAt , InitialList , W),
    StopAtIndex is StopAt-1,
    ReplacingW > W,
    NewW is ReplacingW,
    ( 
        not(memberx([H,S,NewW], TempR)) ->
        NewL is L-1,   
        not(StopAtIndex =:= NewL),!,
        appendx([[H,S,NewW]], TempR, NewResult);
        
        NewL is L-1,
        not(StopAtIndex =:= NewL),!,
        NewResult = TempR
    ),
    getSwaps([H,S,W],InitialList, NewL, NewResult, R).
    
getSwaps(_,_,_,R,R).