A[0] doesn't work.
It would make no sense if you couldn't get the element out. Should I use a for loop for this?
I'm not sure you can access a set like you would access an array, but you can check whether it contains an element or not
'a' in {'a', 'b'}
contains({'b'}, 'a')
'A' notin {'B', 'C'}
I can not really imagine how useful something like A[2] may be for a set...
And [] may work only for a recent compiler version, for me deprecated mget() works. Nim Compiler Version 0.11.3 (2015-08-11) [Linux: amd64]
import sets
var values = initSet[int]()
assert(not values.contains(2))
values.incl(2)
assert values.contains(2)
#values.excl(2)
#assert(not values.contains(2))
var i = 2
echo values.mget(i)
echo values.mget(2)
Notice that you are creating there a HashSet:
Hash sets are different from the built in set type. Sets allow you to store any value that can be hashed and they don't contain duplicate entries.
These consume more memory, but can handle more types of data.
Similar to what @Yolziii mentioned, today in day 16 of the Advent of Code 2020, I needed to extract the only element of a set, as my algorithm relied on extracting one after another element from a set until only one remained.
I ended up using toSeq(theSet)[0], just in case someone else finds that useful.
I did not use set for today's AOC (I probably should have), but in that case I probably would have implemented a simple pop for built-in set, like there is one for HashSet (playground):
var s = {1, 2, 3}
proc pop[T](s: var set[T]): T =
for e in s:
s.excl e
return e
while s.len > 0:
let e = pop s
echo e
I used sets for Day 16 AOC too. I declared a procedure to retrieve the only value of a singleton:
proc value(posSet: set[Position]): Position =
for pos in posSet: return pos
But your solution is fine.