Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate elements from a list in Erlang

Tags:

list

erlang

How can I remove the duplicate from a list in Erlang?

Suppose I have a list like:

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

How can I get:

[1,2,3,4,5,6]
like image 888
Sina Avatar asked Dec 02 '12 19:12

Sina


People also ask

How do I remove duplicates from elements list?

To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of the set() method is that it returns distinct elements.

How do I check if a list is empty in Erlang?

This is the function that is called: set_viewer_values(Value, ViewerSet) -> if ViewerSet /= empty_set -> lists:map(fun(ViewerPid) -> ViewerPid ! {self(), set_value, Value} end, ViewerSet) end.

Is Erlang a list?

The List is a structure used to store a collection of data items. In Erlang, Lists are created by enclosing the values in square brackets.

How do I add to a list in Erlang?

In Elixir and Erlang we use `list ++ [elem]` to append elements.


1 Answers

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.

like image 97
paper_knight Avatar answered Sep 29 '22 13:09

paper_knight