Replacing an element in a list (with 0-based indexing)
replace_nth0(List, Index, OldElem, NewElem, NewList) :- % predicate works forward: Index,List -> OldElem, Transfer nth0(Index,List,OldElem,Transfer), % predicate works backwards: Index,NewElem,Transfer -> NewList nth0(Index,NewList,NewElem,Transfer).
?- replace_nth0([a,b,c,d], 0, Oe, replaced(Oe), NewList). Oe = a, NewList = [replaced(a), b, c, d]. ?- replace_nth0([a,b,c,d], 1, Oe, replaced(Oe), NewList). Oe = b, NewList = [a, replaced(b), c, d]. ?- replace_nth0([a,b,c,d], 2, Oe, replaced(Oe), NewList). Oe = c, NewList = [a, b, replaced(c), d]. ?- replace_nth0([a,b,c,d], 3, Oe, replaced(Oe), NewList). Oe = d, NewList = [a, b, c, replaced(d)].