Home > other >  Prolog: replace the nth item in the list with the first
Prolog: replace the nth item in the list with the first

Time:04-18

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!

CodePudding user response:

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.

CodePudding user response:

Another method, attempting to be faster than slago's (by iterating though the list once) but not really succeeding:

replace_nth_with_first(Nth1, Lst, LstReplaced, First) :-
    Lst = [First|_Tail],
    replace_nth_with_first_(Nth1, Lst, LstReplaced, First).
    
replace_nth_with_first_(1, Lst, LstReplaced, First) :-
    !,
    Lst = [_Head|Tail],
    LstReplaced = [First|Tail].
replace_nth_with_first_(Nth1, [H|Lst], [H|LstReplaced], First) :-
    succ(Nth, Nth1),
    replace_nth_with_first_(Nth, Lst, LstReplaced, First).

Result in swi-prolog:

?- replace_nth_with_first(3, [a, b, c, d, e], R, F).
R = [a,b,a,d,e],
F = a.

Performance comparison:

?- numlist(1, 2000000, L), time(replace_nth_with_first(1000000, L, R, First)).
% 2,000,000 inferences, 0.171 CPU in 0.169 seconds (101% CPU, 11688351 Lips)

% slago's
?- numlist(1, 2000000, L), time(replace_f(L, 1000000, R, First)).
% 2,000,011 inferences, 0.174 CPU in 0.174 seconds (100% CPU, 11484078 Lips)

Note the argument order, as per https://swi-prolog.discourse.group/t/split-list/4836/8

  • Related