How do I create a list (Array of values) from a Set?


#1

How do I get

collect(ap)
5-element Array{Partition{Int64},1}:
 Set(Set{Int64}[Set([3]), Set([2]), Set([1])])
 Set(Set{Int64}[Set([3]), Set([2, 1])])       
 Set(Set{Int64}[Set([3, 1]), Set([2])])       
 Set(Set{Int64}[Set([2, 3, 1])])              
 Set(Set{Int64}[Set([2, 3]), Set([1])])   

into an array like this:

[
[[3],[2],[1]],
[[3],[2,1]],
[[3,1],[2]],
[[2,3,1]],
[[2,3],[1]]
]

In Python I can do:

In [1]: from ps1_partition import get_partitions

In [2]: ap  = get_partitions([1,2,3])

In [3]: l = []

In [4]: for i in ap:
   ...:     print(i)
   ...:     l.append(i)
   ...:     
[[1, 2, 3]]
[[2, 3], [1]]
[[1, 3], [2]]
[[3], [1, 2]]
[[3], [2], [1]]

In [5]: l
Out[5]: [[[1, 2, 3]], [[2, 3], [1]], [[1, 3], [2]], [[3], [1, 2]], [[3], [2], [1]]]

#2
julia> toarray(s::Union{Set, Vector}) = [toarray.(s)...]
toarray (generic function with 1 method)

julia> toarray(v::Number) = v
toarray (generic function with 2 methods)

julia> ab = [Set(Set{Int64}[Set([3]), Set([2]), Set([1])]),
                Set(Set{Int64}[Set([3]), Set([2, 1])]),
                Set(Set{Int64}[Set([3, 1]), Set([2])]),
                Set(Set{Int64}[Set([2, 3, 1])]),
                Set(Set{Int64}[Set([2, 3]), Set([1])])]
5-element Array{Set{Set{Int64}},1}:
 Set([Set([3]), Set([2]), Set([1])])
 Set([Set([3]), Set([2, 1])])
 Set([Set([3, 1]), Set([2])])
 Set([Set([2, 3, 1])])
 Set([Set([2, 3]), Set([1])])

julia> toarray(ab)
5-element Array{Array{Array{Int64,1},1},1}:
 [[3], [2], [1]]
 [[3], [2, 1]]
 [[3, 1], [2]]
 [[2, 3, 1]]
 [[2, 3], [1]]

#3

This also works:

(x->collect.(x)).(ab)

#4

Thanks.

(x->collect.(x)).(ab)

works even where ab has the type

Array{Partition{Int64},1}

where the

toarray

solution does not when the type involves {Partition}.


#5

Ah, good.

I also checked the run-time, and it’s quite a bit faster, perhaps because splatting can be expensive.