How to unfold a set of tuples?

I have a set of tuples something like A = [(1,2),(,7,10),(3,2),(9,8),(5,1)] and wanted to unwrap them into a set. So, for “A” output would be like B = {1,2,3,5,7,8,9,10}

Is there any way to do this (without using for loop, ideally)?

What about

reduce(union, Set.(A))

Set(Iterators.flatten(A)) gets you there.

2 Likes

Any clues why unique(Iterators.flatten(A)) is so much slower than Set?

Well, it allocates an array in addition to (internally) creating a Set.

1 Like
collect(Set(Iterators.flatten(A)))

is much faster than:

unique(Iterators.flatten(A))

what is then the point of unique?

It preserves the order of the elements. collect(Set(...)) does not.

1 Like

Thanks Steve. The order is not the first thing that comes to mind from the unique name, but you and the manual never lie.

Is it?

julia> @btime collect(Set(Iterators.flatten($A)))
  204.793 ns (5 allocations: 528 bytes)

julia> @btime unique(Iterators.flatten($A))
  227.554 ns (6 allocations: 544 bytes)

It is:

A = [(rand(Int8), rand(Int8)) for _ in 1:10_000]

Set(Iterators.flatten(A))           #  11 μs ( 7 allocs: 1.4 KiB)
collect(Set(Iterators.flatten(A)))  #  13 μs ( 8 allocs: 1.7 KiB)
unique(Iterators.flatten(A))        # 121 μs (18 allocs: 4.5 KiB)