Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir Remove Duplicates From List

Tags:

elixir

Would someone be willing to provide some alternate solution to the removal of duplicate values from a List (X) using Functional Programming and Elixir Constructs?

X = [1,26,3,40,5,6,6,7] # the 6 being the duplicate 

The stock solution in my mind for solving this problem, would be to iterate the list (X), and add to a new list (Y) where the key doesn't already exist.

Thank you

like image 285
Dane Balia Avatar asked May 11 '15 11:05

Dane Balia


People also ask

How do I remove duplicates in list Elixir?

Thanks to the Enum module, in Elixir we can trivially remove duplicates from a list. In the following example, we take a list of integers and pass it to the Enum. uniq/1 function which removes duplicates from the list without altering the original order of the remaining elements.

How do you access elements from a list in Elixir?

You can either do [head | tail]. = list (If you need the first element, head, as well) or tail = tl(list) (if you don't need the head) to get the tail of a list, then just map over that.

How do you find the length of a list in Elixir?

The length() function returns the length of the list that is passed as a parameter.

Is Elixir a list?

Lists are a basic data type in Elixir for holding a collection of values. Lists are immutable, meaning they cannot be modified. Any operation that changes a list returns a new list. Lists implement the Enumerable protocol, which allows the use of Enum and Stream module functions.


1 Answers

Enum.uniq does what you want, for example:

iex(6)> Enum.uniq([1,26,3,40,5,6,6,7]) [1, 26, 3, 40, 5, 6, 7] 

In terms of how you'd implement it you could write a recursive function like so:

defmodule Test do   def uniq(list) do     uniq(list, MapSet.new)   end    defp uniq([x | rest], found) do     if MapSet.member?(found, x) do       uniq(rest, found)     else       [x | uniq(rest, MapSet.put(found, x))]     end   end    defp uniq([], _) do     []   end end  iex(3)> Test.uniq([1, 1, 2, 3, 4, 4, 1]) [1, 2, 3, 4] 
like image 105
Paweł Obrok Avatar answered Sep 22 '22 13:09

Paweł Obrok