prologturbo-prolog

Prolog replace element in a list with another list


*Hi, i am trying to replace an element from a list with another list and im stuck when turbo prolog gives me syntax error at the case where if C=A-> put in result list(L1) the list that replace the element.

domains
    list=integer*
    element=i(integer);l(list)
    lista=element*
predicates
    repl(list,integer,list,lista)
clauses
    repl([],A,B,[]):-!.
    repl([C|L],A,B,**[l(|L1])**:- C=A,repl(L,A,B,L1),!.
    repl([C|L],A,B,[i(C)|L1]):- repl(L,A,B,L1),!.

Thanks for help, problem solved (using dasblinkenlight code)


Solution

  • Try this:

    concat([],L,L).
    concat([H|T],L,[H|Res]) :- concat(T,L,Res).
    
    repl([],_,_,[]).
    repl([Val|T],Val,Repl,Res) :- repl(T,Val,Repl,Temp), concat(Repl,Temp,Res).
    repl([H|T],Val,Repl,[H|Res]) :- repl(T,Val,Repl,Res).
    

    I do not know if it is going to work in Turbo Prolog, but it works fine in SWI, and it does not use any built-in predicates.

    concat/3 pair of rules concatenates lists in positions 1 and 2 into a resultant list in position 3.

    As a side note, the cut operator ! is rarely necessary. In case of this problem, you can definitely do without it.