質問
私はこのような何かをするプロローグでプログラムを作ろうとしています:
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).
.
しかし、そのようにして、私は最初のリストからの要素しか取得できません。2番目のものから要素を抽出するにはどうすればいいですか?
@edit: Hが設定されているかどうかメンバーがチェック
member([H|_], H).
member([_|T], H):- member(T, H).
. 解決
組み込みリストから要素を削除する:
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].
. 故意にこれを組み込んだINSを回避する@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