How to define an array to contain Union{Missing, T}?

Is there a better way to write this function using parametric types? I’m afraid my version isn’t type stable.

function f(a::AbstractArray)
    b::Vector{Union{eltype(a),Missing}} = [a[1]]
    push!(b, missing)
    return b
end
julia> f([1,2,3])
2-element Vector{Union{Missing, Int64}}:
 1
  missing

just

b = Vector{Union{eltype(a),Missing}}
reutrn b()

?

function f (a::AbstractVector{T}) where {T}
    b = Union{Missing, T}[]
    push!(b, missing)
    return b
end

julia> f([1,2])
1-element Vector{Union{Missing, Int64}}:
 missing

if you want to keep the contents of a:

function f(a::AbstractVector{T}) where {T}
    b = Union{Missing, T}[]
    append!(b, a)
    return b
end


julia> f([1,2])
2-element Vector{Union{Missing, Int64}}:
 1
 2

Thanks, I was missing the where {T}.

allowmissing(x::AbstractArray) in Missings.jl is also useful for this.

1 Like