Retrieve member types of a Union

Is there a standard way to get the member types of a Union?

In v0.5 I used, but was never happy with:

typealias Primitive_UInt Union{UInt8,UInt16,UInt32,UInt64,UInt128}
Primitive_UInt.types

In v0.6 I’ve experimented, without fully understanding what I’m doing, to come up with:

members(x::DataType) = (x,)
members(x::Union) = (x.a, members(x.b)...)

const Primitive_UInt = Union{UInt8,UInt16,UInt32,UInt64,UInt128}
members(Primitive_UInt)

Is there a better or standard way?

Is this what you are looking for?

julia> Base.uniontypes(Primitive_UInt)
5-element Array{Any,1}:
 UInt8
 UInt16
 UInt32
 UInt64
 UInt128

The definition of uniontypes() (in base/reflection.jl) is not too different from your members():

_uniontypes(x::Union, ts) = (_uniontypes(x.a,ts); _uniontypes(x.b,ts); ts)
_uniontypes(x::ANY, ts) = (push!(ts, x); ts)
uniontypes(x::ANY) = _uniontypes(x, Any[])
2 Likes

Thanks! This is exactly what I’m looking for.

Presumably not important enough to export, but I hope it’s reliably “official”.

Yeah, Base.uniontypes is fine, though if you’re concerned about performance/memory, then your original approach seems better IMO.

Neither is inferrable and the approach in this post is O(N^2) instead of O(N).