Declaring an empty set

Hello all,

I need to declare and empty set and then I have to append some of the other sets to it as follows:

main = []
K = Set()
        K[1] = union(A,C)
        K[2] = union(B,A,C)
        K[3] = union(A,B)
        K[4] = B
        push!(main,K)

Where A, B and C are also sets. it is giving me the following error MethodError MethodError: no method matching setindex!(::Set{Int64}, ::Vector{Int64}, ::Int64)

Any idea whats is going on? Thank you :slight_smile:

Should be either push!(K, union(…)) oder append!(K, union(…))union!(K, union(...)) depending on whether you want K to be a set of sets or set of values.
Setindex (K[i] =…) is not defined for sets since a set does not have this kind of numbered slots: it‘s an unordered collection.

So i should write it like this. push!(K, union(A,C),union(B,A,C),union(A,B)) ?

No you have to push one at a time. Push only takes one additional argument (at least I think so). However you could also push just union(A,B,C) because it shoud already contain all the elements. Or even K = union(A,B,C).
Its a bit hard to say without knowing what you want to achieve exactly.

Anyway I‘d really recommend playing around with that interactively. Either using the Julia repl directly or using rowwise execution in VSCode. That will show you the output at every single step and you will pick up the patterns really quickly! I no time you’ll understand what those errors mean and what exactly triggers them.

Thanks, but push!(K,union(A,B)) still doesnt work, it give me this error MethodError MethodError: Cannot `convert` an object of type Vector{Int64} to an object of type Int64.
I actually just want to know how can i declare an empty set and then push other sets in it? Can you give me any toy example?

Sorry there was an error in my previous post. If you declare a set A = Set{Int}() it can only take integer elements. Therefore, you cannot push! something other than an Int. For that you can use union! which is the mutation version of union and changes the fist argument. In contrast to push! this will not try to put the Set into the outer set, but instead add every single element.

julia> A = Set{Int}();
julia> union!(A, Set([1,2,3]));
juila> A
Set{Int64} with 3 elements:
  2
  3
  1

Maybe there is a misconception what a set is. Consider

A = Set([1,2]) 
B = Set([3,4])
C = Set([4,5])
D = union(A,B,C)

Note that 4 appears only once in D. Hence you don’t need more than one union to get your desired result.
At least as far as I understood what you want to achieve by your description.
If I look at your code it seems that you try to construct a vector of sets. This would look like

main = []
push!(main, union(A,C))
push!(main, union(A,B,C)) # note that sets do not care about ordering
push!(main, union(A,B))
push!(main, B)
2 Likes

Or maybe they are looking for a 1 element Vector{Set{Set{Int}}}, in which case they should just replace the indexed assignments by push!