获得无参数类型

时间:2017-02-14 15:23:02

标签: types julia

我需要获得类型的无参数版本。例如,假设我有x = [0.1,0.2,0.3]。然后是typeof(x)==Array{Float64,1}。我如何创建一个函数(或存在一个函数?)parameterless_type(x) == Array?我需要以通用形式获取它,以便在没有类型参数的情况下访问构造函数。

2 个答案:

答案 0 :(得分:4)

与0.5和0.6兼容的正确方法是使用Compat

julia> using Compat

julia> Compat.TypeUtils.typename(Array{Int, 2})
Array

julia> Compat.TypeUtils.typename(Union{Int, Float64})
ERROR: typename does not apply to unions whose components have different typenames
Stacktrace:
 [1] typename(::Union) at ./essentials.jl:119

julia> Compat.TypeUtils.typename(Union{Vector, Matrix})
Array

答案 1 :(得分:2)

这似乎适用于0.5

julia> typeof(a)
Array{Float64,1}

julia> (typeof(a).name.primary)([1 2 3])
1×3 Array{Int64,2}:
1  2  3

修改1:

感谢tholy的评论和ColorTypes.jl包,0.6的解决方案是:

julia> (typeof(a).name.wrapper)([1 2 3])
1×3 Array{Int64,2}:
 1  2  3

编辑2:

王凤阳说服我,使用typename是必要的。特别是,Array{Int}.name在0.6上失败,因为Array{Int}现在属于UnionAll类型。工作在0.5和0.6的定义是

using Compat.TypeUtils: typename

if :wrapper in fieldnames(TypeName)
    parameterless_type(T::Type) = typename(T).wrapper
else
    parameterless_type(T::Type) = typename(T).primary
end

parameterless_type(x) = parameterless_type(typeof(x))

有了这个,它就是

parameterless_type([0.1,0.2,0.3]) == Array
parameterless_type(Array{Int}) == Array