R.N
R.N

Reputation: 109

Replace every instance of a list by another ONE by ONE in Prolog

So I have a program that is supposed to replace every instance of an element in a list with another one but ONE BY ONE.

E.g.

change_element(5,[1,5,9,12,5,6],3,X). should give 
X = [1,3,9,12,5,6] and 
X = [1,5,9,12,3,6]

So it's replacing first 5 with 3, then in the second output, the first 5 remains 5 and the second changes to 3.

I was able to implement the code to change the first element but the code terminates after that. Doesn't goes to the second element.

change_element(A,[A|As],B,[B|As]).
change_element(A,[E|As],B,[E|Bs]):-
   dif(A, E),
   change_element(A,As,B,Bs).

Any idea, what should I do differently to get the desired result?

Upvotes: 3

Views: 158

Answers (1)

CapelliC
CapelliC

Reputation: 60034

just go on after a match, preserving the old element:

change_element(A,[A|As],B,[B|As]).
change_element(A,[A|As],B,[A|Bs]):-
   change_element(A,As,B,Bs).
change_element(A,[E|As],B,[E|Bs]):-
   dif(A, E),
   change_element(A,As,B,Bs).

Upvotes: 3

Related Questions