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]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)