Pregunta

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

¿Fue útil?

Solución

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.

  • The first repl deals with the empty list coming in; it is identical to yours, except it replaces singleton variables with underscores (a highly recommended practice)
  • The second rule deals with the situation where the value Val being replaced is at the head of the list; it replaces the values in the tail, and concatenates the replacement list Repl with the result of the replacement Res.
  • The last rule deals with the situation when the head value does not match the Val. It recurses down one level, and prepends the head of the initial list to the head of the result of the replacement.

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top