julia-lang检查任意嵌套数组的元素类型

Phu*_*uoc 4 julia

我如何检查嵌套数组的元素类型,因为我不知道嵌套的级别?:

julia> a = [[[[1]]]]
1-element Array{Array{Array{Array{Int64,1},1},1},1}:
 Array{Array{Int64,1},1}[Array{Int64,1}[[1]]]

julia> etype(a)
 Int64?
Run Code Online (Sandbox Code Playgroud)

tim*_*tim 7

由于类型计算通常是这种情况,因此递归方法非常有效:

nested_eltype(x) = nested_eltype(typeof(x))
nested_eltype{T<:AbstractArray}(::Type{T}) = nested_eltype(eltype(T))
nested_eltype{T}(::Type{T}) = T
Run Code Online (Sandbox Code Playgroud)

这没有运行时开销:

julia> @code_llvm nested_eltype([[[[[[[[[[1]]]]]]]]]])

define %jl_value_t* @julia_nested_eltype_71712(%jl_value_t*) #0 {
top:
  ret %jl_value_t* inttoptr (i64 140658266768816 to %jl_value_t*)
}
Run Code Online (Sandbox Code Playgroud)


Col*_*ers 3

可能有一种巧妙的方法可以用一行来完成此操作,但与此同时,您可以使用递归调用在循环eltype内执行此操作while

function nested_eltype(x::AbstractArray)
    y = eltype(x)
    while y <: AbstractArray
        y = eltype(y)
    end
    return(y)
end
Run Code Online (Sandbox Code Playgroud)

请注意,这适用于任何维度的嵌套数组,即它不必Vector像您问题中的示例一样......