# Prolog: Replace the nth item in the list with the first

I’d like to have a Prolog predicate that can replace the nth item in the list with the first.

Example:

``````% replace(+List,+Counter,-New List, %-First Item).
?- replace([1,2,3,4,5],3,L,Z).

L = [1, 2, 1, 4, 5]
Z = 1
``````

This code replaces the nth item in the list with the last. I`m looking sth like this:

``````%+List,+Counter,-New List, %-Last Item
replace([X|Xs],I,[X|Xs1],Xz):-
I\=1,
I1 is I-1,
replace(Xs,I1,Xs1,Xz).
replace([_|Xs],1,[Xz|Xs1],Xz):-
replace(Xs,0,Xs1,Xz).
replace([Xz],_,[Xz],Xz).
``````

I don’t know how to do this. Thanks for your help!

I changed the first value in the list to `a` and the third value in the list to `c` to demonstrate that the value is coming from the list and is not one of the parameters used.

``````?- L = [a,2,3,4,5],nth1(1,L,V).
L = [a, 2, 3, 4, 5],
V = a.

֭?- L1 = [a,2,c,4,5],nth1(1,L1,V1),nth1(3,L1,V2),select(V2,L1,V1,L2).
L1 = [a, 2, c, 4, 5],
V1 = a,
V2 = c,
L2 = [a, 2, a, 4, 5] ;
false.
``````

EDIT

This is cross-posted on StackOverflow.