1

我正在尝试在 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 是否在 Set 中

member([H|_], H).
member([_|T], H):- member(T, H).
4

3 回答 3

3

有一个从列表中删除元素的内置函数:

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).
于 2012-03-13T15:43:05.690 回答
1

Or using only built-ins. if you wanted to just get the job done:

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].
于 2012-03-13T20:50:52.277 回答
0

故意避免 @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] .
于 2012-03-13T20:36:18.243 回答