0
votes

I'm trying to learn a prologue, I'm having trouble defining the predicate:

In Prolog define a predicate substitute (L1, X, L2) which every second element of the list L1 (starting from the second element) replaces with element X.

Examples:

L1 = [a, b, c], X = 1, L2 = [a, 1, c]

L1 = [a, b, c, d], X = a, L2 = [a, a, c, a]

I tried this way:

replace([],_,[]):-!. replace([X|Xs],T,[Z1,Z2|Zs]):-Z1=X, Z2=T, replace(Xs,T,Zs).

but it adds items to the second list, not replaces them. Thank you in advance for your help

You have to take 2 items from the first list too. The second item may be ignored (use the anonymous variable _). Also you may need to add another base case for when the number of items in L1 is odd. - gusbro
You can also use the same variable where appropriate. So instead of unifying Z1 with X just use the same variable X in both places. Likewise with T and Z2. - gusbro
And you may get rid of the cut ! as it is not needed in your procedure - gusbro