Elixir Remove Duplicates From List

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]

Also using MapSet

"3 3 2 1 1" |> String.split |> MapSet.new |> Enum.to_list

==> ["1", "2", "3"]


Yet another possible solution is to use Set when creating collection:

[1, 1, 2, 3, 4, 2, 1] |> Enum.into(HashSet.new) #HashSet<[2, 3, 4, 1]>

Tags:

Elixir