在 prolog 中匹配列表 L1 和 L2
match lists L1 with L2 in prolog
我尝试编写谓词 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]
。我究竟做错了什么?
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).
what am I doing wrong?
只是一个拼写错误,您将变量 H
拼错为 E
:
one_occurence([],[]).
one_occurence([H|T],[H|TU]) :- delete(T,H,TN), one_occurence(TN,TU).
SWI-Prolog 编译器会警告您此类问题...
我尝试编写谓词 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]
。我究竟做错了什么?
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).
what am I doing wrong?
只是一个拼写错误,您将变量 H
拼错为 E
:
one_occurence([],[]).
one_occurence([H|T],[H|TU]) :- delete(T,H,TN), one_occurence(TN,TU).
SWI-Prolog 编译器会警告您此类问题...