The Set also contains a collection of elements of the same data type similar to arrays, and stores unique elements.

The Set stores elements or ordinal type only. The set contains a dynamic size length.

Important points about the Nim Set

  • Set contains a collection of elements of the same data type under a single variable name
  • Dynamic size
  • Duplicate elements are not allowed
  • It allocates memory on the heap
  • Set elements are not ordered

Let’s see different examples of Set type.

How to Declare and assign a set type in Nim Language?

Set type created using set[datatype] where datatype is one of the ordinal types following

  • int8- int16
  • uint8/byte-uint16
  • char
  • enum

Here is an example

var numbers: set[int8]
echo numbers # {}

If you declare a set[int] and throw an error set is too large.

Another way, create with empty braces {} Let’s create an empty set.

var numbers = {}
echo numbers # {}

Another Set literal syntax that contains elements separated by a comma, wrapped inside {} Here, the type of set is inferred from a given value ie.int8

var numbers = {1,2,3,12}
echo numbers # {1,2,3,12}
var vowels = {'a','e','i','o','us}
echo vowels # {'a','e','i','o','us}

Check if an element exists in a set

Multiple ways we can check an element exists in a set.

  • The in operator checks if an element exists in a set, and returns true. else return false.

  • notin checks if an element does not exist in a set and returns true, else return false. Here is an example

var vowels = {'a','e','i','o','u'}
echo vowels
echo 'a' in vowels # true
echo 'b' in vowels # false

echo 'a' notin vowels # false
echo 'b' notin vowels # true
  • contains checks elements contained in a set
var vowels = {'a','e','i','o','u'}
echo vowels
echo contains(vowels,'a') # true
echo contains(vowels,'b') # false

Iterate Nim Set using for loop

for in loop is used to iterate each element in a set.

var vowels = {'a','e','i','o','u'}
echo vowels
for vowel in vowels :
  echo vowel

Output:

a
e
i
o
u

Nim Set supports mathematical operations

The set supports the following mathematical operations.

  • union: the union of two sets. set1 + set2
  • intersection: the intersection of two sets.set1 * set2
  • Difference: the difference between two sets. set1 - set2
  • Equal : set1 == set2

Another incl and excl procedure on sets

var vowels = {'a','e','i','o','u'}
echo vowels
incl(vowels,'A')
echo vowels
excl(vowels,'A')
echo vowels

Output:

{'a', 'e', 'i', 'o', 'u'}
{'A', 'a', 'e', 'i', 'o', 'u'}
{'a', 'e', 'i', 'o', 'u'}

Length of a set in nim

card(set) returns the cardinality of a set ie number of elements.

Here is a set length example

var vowels = {'a','e','i','o','u'}
echo vowels
echo card(vowels) #5