如何在prolog中找到并从列表中删除元素?

如何在prolog中找到并从列表中删除元素?,prolog,meta-predicate,Prolog,Meta Predicate,我有一个列表,我需要找到一个元素并删除它 我的想法是,如果它是头部,就把它移除,如果它是尾部的头部,就把它移除。但是我不知道怎么做 任何建议都将不胜感激 这就是我得到的 choice(8, X):- nl, write('\tRemove a student from roster:'),nl,nl, write('\tEnter student name or ID : '), read(S), remove(S, X, X2), nl, menu(X2). remove(S, []

我有一个列表,我需要找到一个元素并删除它

我的想法是,如果它是头部,就把它移除,如果它是尾部的头部,就把它移除。但是我不知道怎么做

任何建议都将不胜感激

这就是我得到的

choice(8, X):-
  nl, write('\tRemove a student from roster:'),nl,nl,
  write('\tEnter student name or ID : '), read(S), remove(S, X, X2), nl, menu(X2).

remove(S, [], []):- write('\tStudent '), writef("%s", [S]), write(' is not in the roster.'),nl.

remove(S, [[I,N,G]|T], X):-
  S = I -> X = T2, remove(S, T, T2);
  T = [] -> X = [];
  X = [[I,N,G]|T2], remove(S, T, T2).
我希望它删除所有事件

removes(S, [], []):- write('\tStudent '), writef("%s", [S]), write(' is not in the roster.'),nl.

removes(S, [[I,N,G]|T], X):- remove(S, [[I,N,G]|T], X).

remove(S, [], []).

remove(S, [[I,N,G]|T], X):-
  S = I -> X = T2, 
    write('\tStudent '),writef("%s", [S]),write(' removed.'),nl,
    remove(S, T, T2);
  S = N -> X = T2,
    write('\tStudent '),writef("%s", [S]),write(' removed.'),nl,
    remove(S, T, T2);
  X = [[I,N,G]|T2], remove(S, T, T2).

来自潜伏者的链接很有帮助。我需要另一个功能。添加会删除已修复的内容。

单向,使用内置:

remove(X,L,R) :-      % to remove all X from L:
  append(P,[X|S],L),  % - break L into a prefix P, X itself and a suffix S
  append(P,S,T) ,     % - append the prefix and suffix together to form a new list
  remove(X,T,R)       % - and remove X from that list
  .                   %
remove(X,L,L) :-      % otherwise, succeed, leaving L unchanged
  \+ member(X,L)      % - if X is not contained in L
  .                   %
或者你可以用很难的方法来做——不是那么难并推出您自己的:

remove( X , []     , [] ) .      % removing X from the empty list yields the empty list
remove( X , [X|Ls] , R  ) :-     % removing X from a non-empty list consists of
  remove( X , Ls , R )           % - tossing X if it's the head of the list, and
  .                              % - recursing down.
remove( X , [L|Ls] , [L|R] ) :-  % or ...
  X \= L ,                       % - if X is not the head of the list,
  remove( X , Ls , R )           % - simply recursing down.
  .                              % Easy!
这并不比使用
append/3更清晰、更优雅,而且可能更快/更有效。

与具体化的术语不等式一起使用,保持纯洁:


你能在这里展示一些作品吗?您甚至还没有显示您希望查询的外观。您的定义不清楚(您希望它删除所有事件还是仅删除第一个事件?)。我只是添加了到目前为止的内容。我没有添加它的原因是,我只想了解如何执行此操作的一般概念。注意,您的代码需要在if/then/else部分周围加上括号,否则,它会表现得很奇怪-并让您在调试不同输入时遇到麻烦…@d0m1n1c,如果这是您问题的完整解决方案,请将其标记为答案。
?- tfilter(dif(x),[x,1,2,x,3,4,5,x,6,x,x,7],Xs).
Xs = [1,2,3,4,5,6,7].                       % succeeds deterministically