Nim Programming Cookbook // Sets

Sets

Create a set from a sequence

Problem

You have an existing sequence and you want to create a set from it.

Solution

import sets

let a = @[2, 3, 5, 4, 4, 5, 2]

let b = a.toSet()
echo b
{2, 3, 4, 5}

Check if a value is in the set

Problem

You want to check if some value is in the set.

Solution

import sets

let a = [3, 5, 7, 9].toSet()

echo a.contains(10)
echo 5 in a
echo 30 notin a
false
true
true

Add/remove value from a set

Problem

You want to add or remove some value to/from the existing set.

Solution

import sets

var a = [2, 3, 4, 5].toSet()

a.incl(1)
a.excl(5)

echo a
{1, 2, 3, 4}

Operations on two sets

Problem

You want to add two sets together (union).

Solution

import sets

let
  a = [1, 2, 3, 4, 5].toSet()
  b = [3, 4, 5, 6, 7].toSet()

echo union(a, b)
echo a + b
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}

Problem

You want to get the intersection of two sets.

Solution

echo intersection(a, b)
echo a * b
{3, 4, 5}
{3, 4, 5}

Problem

You want to get the difference of two sets.

Solution

echo difference(a, b)
echo a - b

echo difference(b, a)
echo b - a
{1, 2}
{1, 2}
{6, 7}
{6, 7}

Note: difference is non-commutative.

Problem

You want to get the elements which are in either of two sets, but not in both (symmetric difference).

Solution

echo symmetricDifference(a, b)
echo a -+- b
{1, 2, 6, 7}
{1, 2, 6, 7}