我正在尝试删除列表中单个元素的出现
I'm trying to remove a single occurrence of an element in a list
我正在使用 prolog 并试图从列表中删除 1 个元素。如果我要查找的元素是列表中的第一个元素,我的追加代码工作正常,但如果它是列表中的第二个元素,它只是说 false。我哪里错了
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 ) .
我正在使用 prolog 并试图从列表中删除 1 个元素。如果我要查找的元素是列表中的第一个元素,我的追加代码工作正常,但如果它是列表中的第二个元素,它只是说 false。我哪里错了
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 ) .