Search code examples
prolog

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

I wrote this code in prolog, it works well when I test it with:

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

but when I use a variable instead of an empty list, e.g.,

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

it won't work, it just prints so many numbers starting with underscore (_32512 _32518 _32524 _32530... etc.) and won't stop until I abort execution.

I need to test it with a variable in order to use the output in other predicates. So, what can be causing this or how can I solve it?


Solution

  • Add a TempResult parameter to your predicate then add another predicate that takes one less parameter and calls it, like this:

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