MapSet and the conversions

A set is the collection that answers one question fast: is this value in it? MapSet is the set of Elixir, built on the same hash table a map uses, so a lookup costs one step whatever the size. The second half of this page is the conversion between the four collections, because most real code receives one type and needs another.

MapSet and its operations

MapSet.new/1 builds a set from any enumerable and drops the duplicates. member?/2 answers membership, put/2 adds a value, and the module has the set operations under their mathematical names:

basics.exs

set = MapSet.new([1, 2, 2, 3]) IO.inspect(set) IO.inspect(MapSet.member?(set, 2)) IO.inspect(MapSet.put(set, 4)) IO.inspect(MapSet.union(set, MapSet.new([3, 4]))) IO.inspect(MapSet.difference(set, MapSet.new([3]))) IO.inspect(MapSet.intersection(set, MapSet.new([2, 3])))

elixir basics.exs

MapSet.new([1, 2, 3])
true
MapSet.new([1, 2, 3, 4])
MapSet.new([1, 2, 3, 4])
MapSet.new([1, 2])
MapSet.new([2, 3])

The set keeps no order, and the list inside MapSet.new([...]) in the output is the internal order of the hash table rather than the order of the input. A program that sorts the members asks for the order explicitly with MapSet.to_list/1 and Enum.sort/1.

Enum.into and the target type

Enum.into/2 walks an enumerable and pours it into a collectable: a keyword list, a map or a MapSet. The target decides what a duplicate means, which is the whole point of the call: a set drops it, a map keeps the last pair, a list keeps every item:

into.exs

IO.inspect(Enum.into([1, 2, 2, 3], MapSet.new())) IO.inspect(Enum.into([{"a", 1}, {"b", 2}], %{})) IO.inspect(Enum.into([1, 2], []))

elixir into.exs

MapSet.new([1, 2, 3])
%{"a" => 1, "b" => 2}
[1, 2]

The empty [] as the target is the identity of the conversion, and into: is the option of a comprehension that does the same thing inside the for.

Map.new and the key function

Map.new/1 takes a list of pairs, and Map.new/2 takes any enumerable and a function that returns a pair for each item. The second form builds an index from a list, which is the most common conversion in a program:

mapnew.exs

IO.inspect(Map.new([{"a", 1}, {"b", 2}])) IO.inspect(Map.new([1, 2, 3], &{&1, &1 * &1})) IO.inspect(Map.new([{"a", 1}, {"a", 2}]))

elixir mapnew.exs

%{"a" => 1, "b" => 2}
%{1 => 1, 2 => 4, 3 => 9}
%{"a" => 2}

The last line is the rule of a map: the second pair with a key wins. A program that must keep both values turns each one into a list first, with Enum.group_by/3, or pairs them as {"a", [1, 2]} before the conversion.

Which type to pick

The four collections answer four different questions, and the type is the answer:

The keyword list sits beside the map as the options form of a function, with order and duplicate keys and a linear lookup. A program that starts with a list and needs a lookup converts it once with Map.new/2; a program that filters duplicates converts with MapSet.new/1 or keeps the order with Enum.uniq/1.

Deduplicate in a pipeline

A set in the middle of a pipeline is the shortest way to remove duplicates and sort the answer once:

pipeline.exs

words = ["apple", "fig", "apple", "kiwi", "fig"] IO.inspect(Enum.uniq(words)) IO.inspect(words |> MapSet.new() |> MapSet.to_list() |> Enum.sort()) IO.puts(words |> MapSet.new() |> MapSet.size())

elixir pipeline.exs

["apple", "fig", "kiwi"]
["apple", "fig", "kiwi"]
3

Enum.uniq/1 keeps the first occurrence and the order of the input, which is what a reader usually wants. The set loses the order and gains a fast membership test, so the set is the right middle step when the program then asks "is it in" many times.

The mistake: a list of plain values poured into a map

A map is a collection of pairs, and a plain value has no key to become. The conversion stops with an ArgumentError whose inner line names the function that did the work:

mistake.exs

IO.inspect(Enum.into([1, 2], %{}))

elixir mistake.exs

** (ArgumentError) argument error
    (stdlib 6.2.2.5) :maps.from_list([1, 2])
    (elixir 1.19.7) lib/enum.ex:1517: Enum.into_map/1
    mistake.exs:1: (file)

The fix is a target that can hold the values and a key function that makes the pairs: Enum.into([1, 2], MapSet.new()) for a set, Map.new([1, 2], &{&1, &1 * 2}) for a map. The error line :maps.from_list([1, 2]) is the Erlang function behind both calls, and it says what the target wanted: a list of two-item tuples.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a MapSet keep that a list does not?

    Answer

    At most one copy of each value

    A set holds members, so a value is either in it or not, once.

  2. What does Enum.into/2 use to decide what a duplicate means?

    Answer

    The target collection

    A set drops a duplicate, a map keeps the last pair, and a list keeps every item.

  3. When the same key arrives twice in a list of pairs, what does Map.new/1 keep?

    Answer

    The last value

    A map has one value per key, and the later pair overwrites the earlier one.

  4. Which collection is right for a fast "is it in the collection" test?

    Answer

    a MapSet, looked up in one step

    A set is a hash table, so membership costs one step whatever the size.

  5. What does this program print? IO.inspect(MapSet.new([1, 2, 2, 3]))

    Answer

    MapSet.new([1, 2, 3])

    The set drops the repeated 2 and the output shows the set form.

  6. What does this program print? IO.inspect(Enum.into([1, 2], MapSet.new()))

    Answer

    MapSet.new([1, 2])

    A set collects plain values, so the list becomes a set of two members.

  7. What does this program print? IO.inspect(Map.new([1, 2], &{&1, &1 * 10}))

    Answer

    %{1 => 10, 2 => 20}

    The key function returns the pair of the value and its tenfold.

  8. What does this program print? IO.inspect(Map.new([{"a", 1}, {"a", 2}]))

    Answer

    %{"a" => 2}

    The second pair with the same key replaces the first.

  9. What does this program do? IO.inspect(Enum.into([1, 2], %{}))

    Answer

    An ArgumentError, because a map target needs pairs

    The inner maps.from_list call needs two-item tuples, and plain numbers are not pairs.

  10. Which call keeps the first occurrence and the order of the input?

    Answer

    Enum.uniq(list)

    Enum.uniq walks the list in order and drops a value after its first occurrence.

Article author: Arthur Isaev