gpt4 book ai didi

julia - 遍历元组数据类型中的类型

转载 作者:行者123 更新时间:2023-12-05 02:51:05 24 4
gpt4 key购买 nike

有没有办法迭代包含在 Tuple{...} DataType 中的类型?例如,如果我有 Tuple{String, Int} 类型,我希望能够使用类似 values(Tuple{String, Int}) 的东西来返回 StringInt 的迭代器,如下所示:

julia> collect(values(Tuple{String, Int}))
2-element Array{DataType,1}:
String
Int64

但当然这实际上不起作用:

julia> values(Tuple{String, Int})
Tuple{String,Int64}

julia> collect(values(Tuple{String, Int}))
ERROR: MethodError: no method matching length(::Type{Tuple{String,Int64}})
Closest candidates are:
length(::Core.SimpleVector) at essentials.jl:596
length(::Base.MethodList) at reflection.jl:852
length(::Core.MethodTable) at reflection.jl:938
...
Stacktrace:
[1] _similar_for(::UnitRange{Int64}, ::Type{Any}, ::Type{T} where T, ::Base.HasLength) at ./array.jl:576
[2] _collect(::UnitRange{Int64}, ::Type{T} where T, ::Base.HasEltype, ::Base.HasLength) at ./array.jl:609
[3] collect(::Type{T} where T) at ./array.jl:603
[4] top-level scope at REPL[30]:1

我更喜欢不涉及深入 DataType 内部结构的解决方案。

最佳答案

元组类型只是一个DataType。对它进行的所有操作都必须涉及 DataTypes——您正在寻找 DataType -> [DataType] 类型的函数。一种可能的答案是 Tuple{String, Int}.parameters。至少在1.3中,Core.Compiler还包含

datatype_fieldtypes(x::DataType) = ccall(:jl_get_fieldtypes, Any, (Any,), x)

不过,这只是内部的和未记录的。两者都会生成 Core.SimpleVector

但后来我想起元组部分既可以作为索引也可以作为字段。所以事实证明 fieldtypes 可能是您的最爱:

julia> fieldtypes(Tuple{Int, String})
(Int64, String)

但是,其他方法的优点是您可以将它们用于任何 参数化类型。这通常在生成的函数中派上用场。

关于julia - 遍历元组数据类型中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63362962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com