Prólogo listas de diferença
-
13-12-2019 - |
Pergunta
Eu estou tentando fazer programa em prolog que vai fazer algo parecido com isso:
diffSet([a,b,c,d], [a,b,e,f], X).
X = [c,d,e,f]
Eu escrevi isso:
diffSet([], _, []).
diffSet([H|T1],Set,Z):- member(Set, H), !, diffSet(T1,Set,Z).
diffSet([H|T], Set, [H|Set2]):- diffSet(T,Set,Set2).
Mas dessa forma eu só pode obter os elementos da primeira lista.Como posso extrair os elementos a partir do segundo?
@edit:membro é verificar se H é em Conjunto
member([H|_], H).
member([_|T], H):- member(T, H).
Solução
Há um builtin que remover os elementos da lista:
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).
Outras dicas
Ou usando apenas built-ins.se você queria apenas fazer o trabalho:
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].
Evitando deliberadamente o built-ins para isso que @chac menciona, esta é uma maneira deselegante que faz o trabalho.
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] .
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow