Hello I'm trying to create a set using this line:
var s: set[int16] = {2, 7, 8, 9, 10}
and i get error saying:
Error: type mismatch: got <set[range 0..65535(int)]> but expected 'set[uint16]'
I tried to read the explanation in the tutorial but i can't get to understand what this line means: >For signed integers the set's base type is defined to be in the range 0 .. MaxSetElements-1 where MaxSetElements is currently always 2^16.var s: set[uint16] = {2u16, 7, 8, 9, 10}
But the memory consumption is not what you want, instead use a hash set from sets.nim:
import sets
var s1 = toHashSet([9, 5, 1])
var s = {2.int16, 7, 8, 9, 10}
If you write just the literal digit its an int and not an int16.
int is an alias for int64, on 64 Bit hardware.
For signed integers the set's base type is defined to be in the range 0 .. MaxSetElements-1 where MaxSetElements is currently always 2^16.
The quoted text presumably means that the set's base type will be shifted into a suitable range so that the lowest possible value (e.g. -32768) corresponds to the 0th bit in the set. This is also relevant if you're using a set of a custom range type:
type MyRange = -100..100
var s = {(-2).MyRange, 7, 8, 9, 10}
Note that, since a set has 1 bit per possible item, the above will use far less memory than a set[int16]
But if you really need the full range of int16 values then using HashSet as Araq suggested may well be the best solution.
So it seems i need to write the first number's type in the set explicitly to define the sets type.
Yeah, that's right, it's the same for seqs/arrays too.
For example [1, 2, 3] is an array of int, while [1'u, 2, 3] is an array of uint. The compiler needs a helping hand to figure out what type you wanted the array to be.
So it seems i need to write the first number's type in the set explicitly to define the sets type.
Yes, but even, so you cannot put numbers above 65535 into a set. That's a hard implementation limit.
Nim's basic set type is simply a bit-field. It's intended for small sets of flags, that in most other languages require defining and or-ing together integer constants (like O_RDONLY and O_WRONLY in the POSIX open(2) API.)
(Note that this means that a set value that can store the number 65535 will be 8KB in size!)
If you want a general purpose set, that can store large integers or any other objects, you should instead use the sets module, as @Araq recommended above. Those are the typical hash-table based sets you were probably expecting.
Yes, but even, so you cannot put numbers above 65535 into a set. That's a hard implementation limit.
you can, though then you can't put small values into it anymore
https://play.nim-lang.org/#ix=2ziE
sorry for the nitpicking, I just wanted to express my love for ranged integers ;)