Stream: helpdesk (published)

Topic: Union promotion on array operations


view this post on Zulip Théo Galy-Fajou (Aug 08 2022 at 12:56):

When using collect , map , vcat etc..., on Arrays of mixed type (for example Int and Float64), the automatic eltype promotion is to use promote_type . So vcat(rand(3), rand(1:3, 3)) will return a Vector{Float64}
Is there a generic way to get a Union instead, i.e. that vcat returns an array of eltype Union{Int, Float64} ?

view this post on Zulip Mason Protter (Aug 09 2022 at 20:49):

Hm, I guess you could write things like

function union_vcat(x::AbstractArray{T}, y::AbstractArray{U}) where {T, U}
  Union{T, U}[x; y]
end

and so on.

julia> union_vcat(rand(3), rand(1:3, 3))
6-element Vector{Union{Float64, Int64}}:
 0.5169156455130914
 0.19690004688154739
 0.14011289835785867
 3
 3
 3

Last updated: Oct 02 2023 at 04:34 UTC