Sets

Learn about sets in Elixir.

We'll cover the following

Introduction

Sets are implemented using the module MapSet. Here are the different functionalities that we can perform with a set. Let’s take a look at short commands:

iex> set1 = 1..5 |> Enum.into(MapSet.new) 
#MapSet<[1, 2, 3, 4, 5]>
iex> set2 = 3..8 |> Enum.into(MapSet.new) 
#MapSet<[3, 4, 5, 6, 7, 8]>

Functionalities

In the above commands, we’re making two sets using the new method of MapSet module. These sets are stored in set1 and set2, respectively. Below are further simple functionalities of sets:

iex> MapSet.member? set1, 3
true
iex> MapSet.union set1, set2 
#MapSet<[1, 2, 3, 4, 5, 6, 7, 8]> 
iex> MapSet.difference set1, set2 
#MapSet<[1, 2]>
iex> MapSet.difference set2, set1 
#MapSet<[6, 7, 8]>
iex> MapSet.intersection set2, set1 
#MapSet<[3, 4, 5]>

Run and practice these simple codes in the given terminal.

Get hands-on with 1200+ tech skills courses.