How to make unsorted MapSet?

Dmitry Cat Source

Is it possible to create MapSet unsorted?

how it works:

iex(1)> MapSet.new([2,3,2,1])
#MapSet<[1, 2, 3]>

how expected:

iex(1)> MapSet.new([2,3,2,1])
#MapSet<[2, 3, 1]>
elixir

Answers

answered 6 months ago Dogbert #1

MapSets aren't sorted at all. You might see that the values appear sorted for small maps, but that's an implementation detail of how Erlang handles small maps and MapSet uses a map internally.

If you want to get a list of unique elements back, you can instead use Enum.reduce + a MapSet like this:

defmodule A do
  def sorted_uniq(list) do
    Enum.reduce(list, {[], MapSet.new}, fn x, {list, map_set} ->
      if MapSet.member?(map_set, x) do
        {list, map_set}
      else
        {[x | list], MapSet.put(map_set, x)}
      end
    end)
    |> elem(0)
    |> Enum.reverse
  end
end

IO.inspect A.sorted_uniq([2, 3, 2, 1])

Output:

[2, 3, 1]

comments powered by Disqus