Tano
Tano

Reputation: 1377

Elixir MapSet vs Enum.member?

I need to keep only unique values and I am confused which data structure should I use. Later on I will only read the whole data structure.

I am not sure which approach is better to use in such scenario. Which is more efficient, and which is better practice?

Upvotes: 3

Views: 1002

Answers (3)

Konrad Słotwiński
Konrad Słotwiński

Reputation: 699

If you already have datastructure with duplicates use Enum.uniq/1.

Example:

[1, 1, 2, 2, 2, 3, 4] |> Enum.uniq

Result:

[1, 2, 3, 4]

Upvotes: 0

Adam Millerchip
Adam Millerchip

Reputation: 23091

I think you're confusing datastructures and protocols. MapSet is a datastructure (and a module) that implements the Enumerable protocol. You can call Enum.member/2 on a MapSet, but it's not necessary:

mapset =
  MapSet.new()
  |> MapSet.put(1)
  |> MapSet.put(2)
  |> MapSet.put(2)
  |> MapSet.put(3)
  |> MapSet.put(3)
  |> MapSet.put(3)

Enum.join(mapset, ",")

Output:

"1,2,3"

Upvotes: 1

Paweł Obrok
Paweł Obrok

Reputation: 23164

If you keep your data in a MapSet, then Enum.member? will in fact call MapSet.member? underneath, so you will have all advantages of MapSet. You can see the relevant protocol implementation here.

Upvotes: 5

Related Questions