Prolog:用第一个替换列表中的第 n 个项目

Prolog: replace the nth item in the list with the first

我想要一个 Prolog 谓词,它可以将列表中的第 n 项替换为第一项。

示例:

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

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

我不知道该怎么做。感谢您的帮助!

尝试使用谓词 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].

综合起来:

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

示例:

?- 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.

另一种方法,速度稍快(用简单的算术替换 succ/2 有助于提高性能):

replace_nth_with_first(Nth1, Lst, LstReplaced, First) :-
    must_be(positive_integer, Nth1),
    Lst = [First|_Tail],
    replace_nth_with_first_(Nth1, Lst, LstReplaced, First).

% Keeping the arguments simple, to ensure that Nth1 = 1 matches
replace_nth_with_first_(1, Lst, LstReplaced, First) :-
    !,
    Lst = [_Head|Tail],
    LstReplaced = [First|Tail].
replace_nth_with_first_(Nth1, [H|Lst], [H|LstReplaced], First) :-
    Nth is Nth1 - 1,
    replace_nth_with_first_(Nth, Lst, LstReplaced, First).

结果swi-prolog:

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

性能比较:

?- numlist(1, 2000000, L), time(replace_nth_with_first(1000000, L, R, First)).
% 1,000,004 inferences, 0.087 CPU in 0.087 seconds (100% CPU, 11428922 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)

注意参数顺序,按照https://swi-prolog.discourse.group/t/split-list/4836/8

您可能会使用 append/3。漂亮、简洁且声明性强:

replace( [X|Xs] , 1 , [X|Xs], X ) .  % replacing the first item in the list is a no-op
replace( Ls     , I , L1    , X ) :- % for anything else...
  I > 1 ,                            % - the index must be greater than 1
  J is I-1 ,                         % - the length of the prefix is I-1
  length( [X|Xs], J ) ,              % - construct an empty/unbound prefix list of the desired length
  append( [X|Xs] , [_|Ys] , Ls ) ,   % - break the source list up into the desired bits
  append( [X|Xs] , [X|Ys] , L1 )     % - and then put everything back together in the desired manner
  .                                  % Easy!