在 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})
我要的是
Int64
要转换为 Float64
的数组数组,所以我得到类似的东西:>promote_array([1], [1.0])
([1.0],[1.0])
>typeof(promote_array([1], [1.0]))
(Array{Float64,1},Array{Float64,1})
这里
promote_array
是我编的一个假设函数。我正在寻找一个真正的功能,做同样的事情。 Julia 中是否有一个函数可以做 promote_array
以上吗?
最佳答案
我找到了函数 Base.promote_eltype
,我可以用它来获得我想要的:
function promote_array(arrays...)
eltype = Base.promote_eltype(arrays...)
tuple([convert(Array{eltype}, array) for array in arrays]...)
end
此
promote_array
函数然后给我我正在寻找的输出:>promote_array([1], [1.0])
([1.0],[1.0])
>typeof(promote_array([1], [1.0]))
(Array{Float64,1},Array{Float64,1})
以上解决了我的问题,虽然存在
Base.promote_eltype
表明可能有一个我还不知道的已经构建的解决方案。
关于julia - Julia 中的数组类型提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235469/