프롤로그 목록 차이점
-
13-12-2019 - |
문제
프롤로그에서 프로그램을 만들려고 노력하고 있습니다.
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).
. 해결책
내장 목록에서 요소를 제거하는 :
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은 @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