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.