Removing Duplicate Elements from List of Lists in Prolog

吃可爱长大的小学妹 提交于 2019-12-24 18:53:06

问题


I am trying to work out how to remove duplicate elements in a list of lists in Prolog.

E.g:
input: [[1,2,3],[5,6],[3,4],[1,7]]

expected output: [[1,2,3],[5,6],[4],[7]]

I know I can use the predicate sort/2 to remove duplicates in a single list, but how do I get it to work across multiple lists?


回答1:


Here is my attempt. Hope you've made some attempts to solve it and learn from this...Anyway if you still didn't come up with anything take a look at the following code:

 remove_dupl(InL, OutL):- remove_dupl(InL, [], OutL1),remove_empty(OutL1,OutL).

remove_dupl([],_,[]).
remove_dupl([H|T],L,[[H1]|T2]):-
              H=[H1], \+member(H1,L), 
              remove_dupl(T,[H1|L],T2).
remove_dupl([H|T],L,[[H1|T2]|T3]):- 
              H=[H1|T1], \+member(H1,L), 
              remove_dupl([T1|T],[H1|L],[T2|T3]).
remove_dupl([H|T],L,T2):- 
              H=[H1|T1], member(H1,L), 
              remove_dupl([T1|T],L,T2).
remove_dupl([H|T],L,[[]|T2]):- 
              H=[H1], member(H1,L), 
              remove_dupl(T,L,T2).

remove_empty([],[]).
remove_empty([[]|T],T1):-remove_empty(T,T1).
remove_empty([[H|T]|T1],[[H|T]|T2]):-remove_empty(T1,T2).

Maybe not the most efficient solution. Example:

?- remove_dupl([[1,2,3],[5,6],[3,4],[1,7]],L).
L = [[1, 2, 3], [5, 6], [4], [7]] ;
false.


来源:https://stackoverflow.com/questions/46018429/removing-duplicate-elements-from-list-of-lists-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!