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

时间:2014-04-25 02:38:21

标签: prolog

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

我正在进行的想法就是将它移除,如果它是头部的话,如果它是尾部的头部则将它移除。我不知道怎么做。

感谢任何建议。

这就是我所拥有的

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

我希望它能删除所有事件。

3 个答案:

答案 0 :(得分:2)

使用 tfilter/3以及明确的术语不等式dif/3保持纯洁:

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

答案 1 :(得分:0)

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).
来自潜伏者的链接很有帮助。我需要另一个功能。添加删除修复它。

答案 2 :(得分:-1)

一种方法,使用内置插件:

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更清晰或更优雅,而且可能更快/更有效。