|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
built-in set typeThe 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 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 Char setThis 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 rangeIf 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 |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |