Julia中的数组类型提升

Julia中的数组类型提升,julia,type-promotion,Julia,Type Promotion,在Julia中,我可以使用promote使各种类型的对象兼容。例如: >promote(1, 1.0) (1.0,1.0) >typeof(promote(1, 1.0)) (Float64, Float64) 但是,如果我在阵列上使用promote,它不会提供我想要的: >promote([1], [1.0]) ([1],[1.0]) >typeof(promote([1], [1.0])) (Array{Int64,1},Array{Float64,1}) fun

在Julia中,我可以使用
promote
使各种类型的对象兼容。例如:

>promote(1, 1.0)
(1.0,1.0)
>typeof(promote(1, 1.0))
(Float64, Float64)
但是,如果我在阵列上使用
promote
,它不会提供我想要的:

>promote([1], [1.0])
([1],[1.0])
>typeof(promote([1], [1.0]))
(Array{Int64,1},Array{Float64,1})
function promote_array(arrays...)
  eltype = Base.promote_eltype(arrays...)
  tuple([convert(Array{eltype}, array) for array in arrays]...)
end
我想要的是将
Int64
数组转换为
Float64
数组,因此得到如下结果:

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

这里
promote\u array
是我编的一个假设函数。我正在寻找一个真正的功能,做同样的。Julia中是否有一个函数可以执行上面所述的
promote\u array
功能?

我找到了函数
Base.promote\u eltype
,我可以使用它来获得我想要的:

>promote([1], [1.0])
([1],[1.0])
>typeof(promote([1], [1.0]))
(Array{Int64,1},Array{Float64,1})
function promote_array(arrays...)
  eltype = Base.promote_eltype(arrays...)
  tuple([convert(Array{eltype}, array) for array in arrays]...)
end
这个
promote\u array
函数然后提供了我想要的输出:

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

以上解决了我的问题,尽管存在
Base.promotion\u eltype
表明可能存在一个我还不知道的已构建的解决方案。

以下是我要做的:

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
我不确定您的用例到底是什么,但我认为以下模式对于具有尽可能严格的类型的代码来说是非常常见的:

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

函数foo{SAh没有看到这一点。这与我的基本相同,只是使用参数函数来提取eltype。这一操作对几乎所有线性代数函数都执行,因此您可以查看
linalg
目录。在这里,我们升级到一种类型,其中元素类型在代数的算术运算下是闭合的bra计算,例如,LU需要定量,QR需要2-范数。当计算出正确的元素类型时,您可以使用
convert(AbstractArray{Float64},[10;01])
LinAlg.copy_of type([10;01],Float64)
计算新数组,其中最后一个确保没有别名,但仅在0.4中定义。