Array type promotion in Julia

In Julia I can use promote

different types of objects for compatibility. For example:

>promote(1, 1.0)
(1.0,1.0)
>typeof(promote(1, 1.0))
(Float64, Float64)

      

However, if I use promote

for arrays, it doesn't give me what I want:

>promote([1], [1.0])
([1],[1.0])
>typeof(promote([1], [1.0]))
(Array{Int64,1},Array{Float64,1})

      

I want the array to Int64

convert to array Float64

, so I end up with something like:

>promote_array([1], [1.0])
([1.0],[1.0])
>typeof(promote_array([1], [1.0]))
(Array{Float64,1},Array{Float64,1})

      

Here promote_array

is a hypothetical function I have composed. I am looking for a real function that does the same. Is there a function in Julia that does what the promote_array

above does?

+3


source to share


2 answers


Here's what I would do:

function promote_array{S,T}(x::Vector{S},y::Vector{T})
    U = promote_type(S,T)
    convert(Vector{U},x), convert(Vector{U},y)
end

      



I'm not sure what your use case is exactly, but the following pattern is what I see as usually required for code that has the tightest typing that can be general:

function foo{S<:Real, T<:Real}(x::Vector{S},y::Vector{T})
    length(x) != length(y) && error("Length mismatch")
    result = zeros(promote_type(S,T), length(x))
    for i in 1:length(x)
        # Do some fancy foo-work here
        result[i] = x[i] + y[i]
    end
    return result
end

      

+4


source


I found a function Base.promote_eltype

that I can use to get what I want:

function promote_array(arrays...)
  eltype = Base.promote_eltype(arrays...)
  tuple([convert(Array{eltype}, array) for array in arrays]...)
end

      

This function promote_array

gives me the result I am looking for:



>promote_array([1], [1.0])
([1.0],[1.0])
>typeof(promote_array([1], [1.0]))
(Array{Float64,1},Array{Float64,1})

      

The above problem solves my problem, although existence Base.promote_eltype

suggests there may be a solution already built that I am not aware of yet.

+3


source







All Articles