prolog列出差异
-
13-12-2019 - |
题
我正在尝试在prolog中制作程序,这将是这样的:
diffSet([a,b,c,d], [a,b,e,f], X).
X = [c,d,e,f]
.
我写了这个:
diffSet([], _, []).
diffSet([H|T1],Set,Z):- member(Set, H), !, diffSet(T1,Set,Z).
diffSet([H|T], Set, [H|Set2]):- diffSet(T,Set,Set2).
.
但以此,我只能从第一个列表中获取元素。如何从第二个中提取元素?
@edit: 会员检查h是否在设置
member([H|_], H).
member([_|T], H):- member(T, H).
. 解决方案
有一个 build 从列表中删除元素:
diffSet([], X, X).
diffSet([H|T1],Set,Z):-
member(H, Set), % NOTE: arguments swapped!
!, delete(T1, H, T2), % avoid duplicates in first list
delete(Set, H, Set2), % remove duplicates in second list
diffSet(T2, Set2, Z).
diffSet([H|T], Set, [H|Set2]) :-
diffSet(T,Set,Set2).
. 其他提示
或仅使用内置。如果你想完成工作:
notcommon(L1, L2, Result) :-
intersection(L1, L2, Intersec),
append(L1, L2, AllItems),
subtract(AllItems, Intersec, Result).
?- notcommon([a,b,c,d], [a,b,e,f], X).
X = [c, d, e, f].
. 故意避免内置的内部的@chac提到,这是一个难以做的工作。
notcommon([], _, []).
notcommon([H1|T1], L2, [H1|Diffs]) :-
not(member(H1, L2)),
notcommon(T1, L2, Diffs).
notcommon([_|T1], L2, Diffs) :-
notcommon(T1, L2, Diffs).
alldiffs(L1, L2, AllDiffs) :-
notcommon(L1, L2, SetOne),
notcommon(L2, L1, SetTwo),
append(SetOne, SetTwo, AllDiffs).
? alldiffs([a,b,c,d], [a,b,e,f], X).
X = [c, d, e, f] .
. 不隶属于 StackOverflow