首次出现后Prolog插入元素

时间:2013-09-30 18:38:23

标签: list prolog

如何在列表E第一次出现X后立即添加元素Xs

示例:

?- insert_right_behind(5,10,[2,4,10,12],Xs).
Xs = [2,4,10,5,12].                     % expected answer

此刻,我有理解的问题 由于我不熟悉该语言,因此需要进行递归。

提前致谢!

3 个答案:

答案 0 :(得分:2)

previous answer最成功的查询中留下了无用的选择点。

我们可以使用if_/3 and (=)/3来避免这些选择点:

item_following_in_inserted(I,J,[X|Xs],Ys0) :-
   if_(J = X,
       Ys0 = [J,I|Xs],
       (Ys0 = [X|Ys], item_following_in_inserted(I,J,Xs,Ys))).

让我们运行一些查询!

?- item_following_in_inserted(5,10,[2,4,12],Xs).
false.                                               % OK, unchanged

?- item_following_in_inserted(5,10,[2,4,10,12],Xs).
Xs = [2,4,10,5,12].                                  % succeeds deterministically

?- item_following_in_inserted(5,10,[2,4,10,12,10],Xs).
Xs = [2,4,10,5,12,10].                               % succeeds deterministically

?- item_following_in_inserted(I,E,Xs,Ys).
  Xs = [      E|_Z], Ys = [      E,I|_Z]             % OK, unchanged
; Xs = [   _A,E|_Z], Ys = [   _A,E,I|_Z], dif(E,_A)
; Xs = [_A,_B,E|_Z], Ys = [_A,_B,E,I|_Z], dif(E,_A), dif(E,_B)
...

答案 1 :(得分:1)

使用三个谓词子句:

% Inserting after in an empty list is an empty list:
insert_after( _X, _Y, [], [] ).

% If the "after" item is at the head of the list, then the "insert" item can go after it:
insert_after( X, Y, [Y|T], [Y,X|T] ).

% If the head of the list isn't the "after" item, then the result will be
% this with a new tail list that has the "insert" item inserted:
insert_after( X, Y, [H|T], [H|L] ) :-
    Y \= H,
    insert_after( X, Y, T, L ).

如果给定列表中不存在“after”项,则insert_after/4将生成原始列表。通过删除上面的第一个insert_after子句,它就会失败。

答案 2 :(得分:1)

让我们保持简单,并使用append/3 maplist/2,如下所示:

item_following_in_inserted(I,J,Xs,Ys) :-
   append(Prefix,[J  |Suffix],Xs),
   maplist(dif(J),Prefix),
   append(Prefix,[J,I|Suffix],Ys).

完成!这是查询时间......首先,让我们运行OP给出的查询:

?- item_following_in_inserted(5,10,[2,4,10,12],Xs).
  Xs = [2,4,10,5,12]               % succeeds, but leaves behind choicepoint
; false.

如果该项目不是给定列表的成员怎么办?

?- item_following_in_inserted(5,10,[2,4,   12],Xs).
false.                             % fails, as expected: 10 is absent

让我们检查一下仅在第一次发生之后插入 - 而不是其他地方!

?- item_following_in_inserted(5,10,[2,4,10,12,10],Xs).
  Xs = [2,4,10,5,12,10]            % single solution
; false.                           % terminates universally

item_following_in_inserted/4的最常见查询呢?

?- item_following_in_inserted(I,E,Xs,Ys).
  Xs = [         E|_Z], Ys = [         E,I|_Z]
; Xs = [      _A,E|_Z], Ys = [      _A,E,I|_Z], dif(E,_A)
; Xs = [   _A,_B,E|_Z], Ys = [   _A,_B,E,I|_Z], dif(E,_A), dif(E,_B)
; Xs = [_A,_B,_C,E|_Z], Ys = [_A,_B,_C,E,I|_Z], dif(E,_A), dif(E,_B), dif(E,_C)
...