我正在尝试删除列表中的单个元素



我正在使用prolog,我试图从列表中删除1个元素。我的追加代码工作得很好,如果我正在寻找的元素是列表中的第一个元素,但如果它是列表中的第二个元素,它只是说假。我哪里错了

deleteFirst([A|X],B,Y,R):-
A=B,
appendL(Y,A,[],Y1),
deleteFirst(X,B,Y1,R).
deleteFirst([A|X],A,Y,R):-
appendL(Y,X,[],R).

试试这样:

% ---------------------------------------------
% remove the first X from List, yielding Result
% ---------------------------------------------
delete_first( X , List , Result ) :-
append( Prefix, [X|Suffix], List ) ,
! ,
append( Prefix, Suffix, Result ) .

需要切割以消除选择点:否则,在回溯时,它将把删除的项目放回并尝试找到另一个匹配的x。

如果你要滚动你自己的(我想这是你的老师想要的),像这样,只是一个列表的遍历就可以了:

delete_first( _ , []     , []     ) .  % Remove this to fail if no matching X is found
delete_first( X , [X|Rs] ,    Rs  ) :- % Once we find an X, we're done.
!.                                   % - and eliminate the choice point
delete_first( X , [Y|Ys] , [Y|Rs] ) :- % Otherwise, put Y on the result list and recurse down
delete_first( X , Ys, Rs ) .