Search code examples
listprolog

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

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


Solution

  • Try using the predicate nth1(Index, List, Item, Rest):

    ?- nth1(3, [1,2,3,4,5], Item, Rest).
    Item = 3,
    Rest = [1, 2, 4, 5].
    
    ?- nth1(3, List, 1, [1,2,4,5]).
    List = [1, 2, 1, 4, 5].
    

    Putting it all together:

    replace(List, Index, NewList, First) :-
        List = [First|_],
        nth1(Index, List, _Removed, Rest),
        nth1(Index, NewList, First, Rest).
    

    Examples:

    ?- replace([1,2,3,4,5], 3, L, Z).
    L = [1, 2, 1, 4, 5],
    Z = 1.
    
    ?- replace([one,two,three,four,five], 4, NewList, First).
    NewList = [one, two, three, one, five],
    First = one.