如何在Julia中重新计算向量的Eltype

Let's say I have a vector v = Any[1,2,3,4]

And I would like to recompute its eltype in such a way that typeof(v) = Vector{Int}

Is it possible to accomplish this without having to manually concatenate each of the elements in v?

评论
  • oqui
    oqui 回复

    You can't "retype" the existing v, just create a copy of it with the more concrete type1.

    转换次数

    假设您已经(静态地)知道结果类型,则有多种选择。最易读的(和IMO,惯用的)是

    Vector{Int}(v)
    

    我认为这相当于

    convert(Vector{Int}, v)
    

    或者:

    convert.(Int, v)
    

    转换成什么

    If you don't know what the "common type" would be, there are multiple options how to get one that matches. In general, typejoin can be used to find a least upper bound:

    mapreduce(typeof, typejoin, v)
    

    The result will most likely be abstract, e.g. Real for an array of Ints and Float64s. So, for numeric types, you might be better off with promote_type:

    mapreduce(typeof, promote_type, v2)
    

    This at least gives you Float64 for mixed Ints and Float64s.

    但是,实际上并不建议所有这些方法,因为它可能很脆弱,令人惊讶,并且类型不稳定。

    1For certain combinations of types, reinterpret will work and return a view with a different type, but this is only possible for bits types, which Any is not. For converting Any[1,2,3] to Int[1,2,3] copying is fundamentally necessary because the two arrays have different layouts in memory: the former is an array of pointers to individually allocated integers objects, whereas the latter stores the Int values inline in contiguous memory.