Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Nim2
* Scala


[ edit | logout ]
[ sandbox | passwd ]

built-in set type

The built-in set data structure's base type must be an ordinal type (small integer type, char). Nim's built-in set type is implemented as a bit vector. Sets are often used in the stdlib too to represent flags.

A string is not an ordinal type. The HashSet supports any type as its base type.

var collection: set[int8]   # int8 has the range -128 to 127
assert collection == {}

collection.incl(77)       # include (insert) an element
echo 77 in collection     # true

collection.incl(127)      # OK
#collection.incl(128)     # ERROR: value out of range

collection.incl(-66)      # OK
#collection.incl(-200)    # ERROR: out of range

𝥶The base type is int8. It determines what values can be stored in the set: -128 to 127. It also determines the size of the bit vector: 2^8 bits = 256 bits = 32 bytes.

The size of a set[int16] is 8 KB. The Nim compiler doesn't allow you to create a set[int32] since it would be too big in the memory. The maximal number of elements can be 2^16.

Char set

This type is perfect for storing ASCII characters.

let
  s1 = {'a', 'b', 'c', 'd'}             # {'a', 'b', 'c', 'd'} is a set literal
  s2 = {          'c', 'd', 'e', 'f'}

echo s1       # {'a', 'b', 'c', 'd'}

echo s1 + s2  # union: {'a', 'b', 'c', 'd', 'e', 'f'}
echo s1 * s2  # intersection: {'c', 'd'}
echo s1 - s2  # difference: {'a', 'b'}

It also works:

let
  lowercase = {'a'..'z'}
  alphabet =  {'a'..'z', 'A'..'Z'}

Specify the range

If you know the range of possible values that you want to store in a set, you can specify that range. This way the size of the set will be minimal, and if you want to insert a value out of range, you'll get a compile error.

var numbers: set[range[1..100]]  # possible values: 1 to 100 (incl.)

echo numbers  # empty: {}

numbers.incl(2)
numbers.incl(3)
numbers.incl(5)

echo numbers  # {2, 3, 5}

#numbers.incl(120)  # compile ERROR: out of range

You can also put a custom type name on the range:

type
  SmallRange = range[-5 .. 20]

var values: set[SmallRange]  # empty: {}

values.incl(-3)
values.incl(-1)
values.incl(15)

echo values          # {-3, -1, 15}
echo sizeof(values)  # 4; i.e. 4 bytes
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 05, 10:32