匹配在序言中列出L1和L2

时间:2015-03-10 07:28:05

标签: list prolog match

如果one_occurence(L1, L2)的每个元素在L1中出现一次,我会尝试编写谓词L2

delete([H|T], H, TN) :- delete(T, H, TN).

delete([H|T], E, [H|TN]) :- \+ H = E, delete(T, E, TN).

delete([], _, []).

/*one_occurence(L,LN) is true if a list LN is identical to a list L
  without all repeated elements.*/

one_occurence([],[]).

one_occurence([H|T], [H|TU]) :- delete(T, E, TN), one_occurence(TN, TU).

但是,当我问one_occurence([a,b,a,a,b,c,d,c],N)时,我得到N=[a,a,c,c]这是错误的。我应该N=[a,b,c,d]。我究竟做错了什么?

2 个答案:

答案 0 :(得分:1)

我做错了什么?

只是一个拼写错误,您将变量H拼错为E

one_occurence([],[]).
one_occurence([H|T],[H|TU]) :- delete(T,H,TN), one_occurence(TN,TU).

SWI-Prolog编译器会警告你这些问题......

答案 1 :(得分:0)

Swi prolog有:list_to_set(+ List,?Set)。

或从头开始:

mymember(X,[X|_]).
mymember(X,[_|T]) :- mymember(X,T).

not(A) :- \+ call(A). 



set([],[]).
set([H|T],[H|Out]) :-
 not(mymember(H,T)),
 set(T,Out).
set([H|T],Out) :-
 mymember(H,T),
 set(T,Out).

once_occurrence(L1,L2):-set(L1,L2).