在Erlang中从列表中删除重复元素

kmynzznz  于 2022-12-08  发布在  Erlang
关注(0)|答案(6)|浏览(213)

我如何在Erlang中删除列表中的重复项?
假设我有一个列表:

[1,1,2,3,4,5,5,6]

如何获取:

[1,2,3,4,5,6]
llmtgqce

llmtgqce1#

You could use sets , for example:

my_nonDuplicate_list1() ->
    List = [1,1,2,3,4,5,5,6],
    Set = sets:from_list(List),
    sets:to_list(Set).

This returns [1,2,3,4,5] , no more duplicates, but most likely not sorted.
Another possibility without the usage of sets would be:

my_nonDuplicate_list2() ->
    List = [1,1,2,3,4,5,5,6],
    lists:usort(List).

In this case it returns [1,2,3,4,5] , no more duplicates and sorted.

wz3gfoph

wz3gfoph2#

对于那些希望保持列表顺序的人:

remove_dups([])    -> [];
remove_dups([H|T]) -> [H | [X || X <- remove_dups(T), X /= H]].
5fjcxozz

5fjcxozz3#

一个可能的解决方案将Preserve the order of the elements帮助你学习如何操作列表,将涉及两个函数:

delete_all(Item, [Item | Rest_of_list]) ->
    delete_all(Item, Rest_of_list);
delete_all(Item, [Another_item| Rest_of_list]) ->
    [Another_item | delete_all(Item, Rest_of_list)];
delete_all(_, []) -> [].

remove_duplicates(List)-> removing(List,[]). 
removing([],This) -> lists:reverse(This);
removing([A|Tail],Acc) -> 
    removing(delete_all(A,Tail),[A|Acc]).

为了测试,

Eshell V5.9  (abort with ^G)
1> mymod:remove_duplicates([1,2,3,1,2,4,1,2,1]).
[1,2,3,4]
2>
qeeaahzv

qeeaahzv4#

一开始我会做这样的事情来保持秩序,尽管这是不推荐的。记住AddedStuff ++ Accumulator是可以的,但Accumulator ++ AddedStuff真的很糟糕。

rm_dup(List) ->
    lists:foldl(
        fun(Elem, Acc) ->
            case lists:member(Elem, Acc) of
                true ->
                    Acc;
                false ->
                    Acc ++ [Elem]
            end
        end, [], List
    ).

如果要保持顺序,此解决方案的效率要高得多:

rm_dup(List) ->
    lists:reverse(lists:foldl(
        fun(Elem, Acc) ->
            case lists:member(Elem, Acc) of
                true ->
                    Acc;
                false ->
                    [Elem] ++ Acc
            end
        end, [], List
    )).
ulydmbyx

ulydmbyx5#

我认为最好的选择是使用lists:usort()
但是,如果您不想使用BIF,而希望对列表进行排序,我建议使用快速排序,在此实现中,您将得到没有重复值的排序列表。

unique_sort([]) -> [];
unique_sort([Pivot|T]) ->
unique_sort ([X || X <- T, X < Pivot ) ]++
[Pivot] ++
unique_sort ([X || X <- T, X > Pivot ]).
2nbm6dog

2nbm6dog6#

Module sets has two functions that can be composed and do the job in an efficient way: sets:from_list/1 returns a set with all the elements of a list (with no duplicated elements from definition) and sets:to_list/1 returns a list with the elements of a set. Here is an example of use:

4> sets:to_list(sets:from_list([1,1,2,3,4,5,5,6])).
[3,6,2,5,1,4]

We could define the function as

nub(L) -> sets:to_list(sets:from_list(L)).

相关问题