How to broadcast set operation on array of sets in Julia?

Viewed 226

I'm trying to perform set operations between a given set y and all items in some array of sets X as follows:

X=Array{Set}([Set([1,2,1]), Set([4,6,8 ]), Set([4,5])]) 
y=Set{Int16}([2,8,4])
z=broadcast(intersect, y, X)

println(z)

Which gives me empty sets, instead of sets with the singletons in y, for my example.

1 Answers

You have to protect y from being iterated over. Normally you would get an error but unfortunately y has three elements as well as vector X. Let us create a bigger vector then so see the problem:

julia> X=Array{Set}([Set([1,2,1]), Set([4,6,8 ]), Set([4,5]), Set([7])])
4-element Array{Set,1}:
 Set([2, 1])
 Set([4, 8, 6])
 Set([4, 5])
 Set([7])

julia> y=Set{Int16}([2,8,4])
Set{Int16} with 3 elements:
  4
  2
  8

julia> z=broadcast(intersect, y, X)
ERROR: DimensionMismatch("arrays could not be broadcast to a common size; got a dimension with lengths 3 and 4")

How to solve it - wrap y in a 0-dimensional container with Ref(y) like this:

julia> z=broadcast(intersect, Ref(y), X)
4-element Array{Set{Int16},1}:
 Set([2])
 Set([4, 8])
 Set([4])
 Set()

or equivalently just write:

julia> z=intersect.(Ref(y), X)
4-element Array{Set{Int16},1}:
 Set([2])
 Set([4, 8])
 Set([4])
 Set()
Related