I need do this:
replace(L,P,E,R)
, where L is the current list, P is the position where the element will be insert, E is the element to insert and R is the return, the new list.
Example:
L = [1,2,3,4,5],
replace(L,2,'@',R).
R = [1,2,'@',4,5]
I tried this, but nothing happens, the list continuous to be the same:
replaceInThePosition([_|T],1,E,[['1',E]|T]).
replaceInThePosition([H|T],P,E,[H|R]) :-
P > 0, NP is P-1, replaceInThePosition(T,NP,E,R), !.
You could do this using
append/3
:You're not far.
You can try with
I mean:
1)
0
instead1
in the first clause (or1
in the first clause butP > 1
in the second one; but in this case fromreplaceInThePosition([1, 2, 3, 4, 5], 2, '@', R)
you unifyR = [1, @, 3, 4, 5]
, notR = [1, 2, @, 4, 5]
)2)
[E|T]
for the last ergument in the first clause, not[['1',E]|T]
3) no cut (no
!
) at the end of the second clause (there is no need: the first clause i whenP
is zero; the secon one whenP > 0
; so they are mutually exclusiveanother possibility: