I'd like to have a Prolog predicate that can replace an element in a list at a specified index.
Example:
% replace(+List,+Index,+Value,-NewList).
?- L=[a,b,c,d], replace(L,1,z,L2).
L2 = [a,z,c,d]
I don't know how to do this. Thanks for your help! Loïc.
If we use
same_length/2
,append/3
, andlength/2
, we don't need to write recursive code:Sample query given by the OP:
This works "in the other direction", too!
Even better, we do not even need to specify the concrete index:
What about doing it in a straight-forward way like this?
Here's the use-case the OP specified:
Above code is pure, so we can ask more general queries—and expect logically sound answers: