Is it possible to get a set of types that form a union?

Let's say I have Union :

  SomeUnion = Union{Int, String} 

Is there a way to extract the set of types that make up this union? For instance....

  union_types(SomeUnion) # => [Int, String] 
+5
source share
2 answers

just write a simple example here:

 a = Union(Int,String) function union_types(x) return x.types end julia> union_types(a) (Int64,String) 

you can save the result to an array if you want:

 function union_types(x) return collect(DataType, x.types) end julia> union_types(a) 2-element Array{DataType,1}: Int64 String 

UPDATE: use collect as @Luc Danton suggested in the comment below.

+5
source

For Julia 0.6, NEWS.md indicates that " Union types have two fields, a and b instead of one types field." In addition, "Parametric types with" unspecified "parameters, such as Array , are now represented as UnionAll , not DataType s."

Thus, to get types as a tuple, we can do

 union_types(x::Union) = (xa, union_types(xb)...) union_types(x::Type) = (x,) 

If you need an array, just collect tuple

 julia> collect(union_types(Union{Int, Float64, String, Array})) 4-element Array{Type,1}: Int64 Float64 String Array 
+1
source

All Articles