2017-02-14 197 views
5

我需要獲取某個類型的無參數版本。例如,可以說我有x = [0.1,0.2,0.3]。然後typeof(x)==Array{Float64,1}。我如何製作一個功能(或者是否存在?)parameterless_type(x) == Array?我需要以通用的形式得到它,以訪問沒有其中的類型參數的構造函數。獲取無參數類型

+1

'typeof(x).name'給了我'Array'。它可能會訣竅,但不會被官方認可的朱莉婭。 –

+2

ColorTypes.jl做到這一點和許多相關的技巧,可能是一個有用的模型? – tholy

回答

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:

由於勒託利的評論和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 
+1

這在0.6上失敗。最好使用庫函數而不是字段訪問。 –

+0

@FenggyangWang這個用例沒有庫函數。因此,我認爲使用上述方法沒有問題。當然,我會將這些代碼包裝在我自己的函數中('ColorTypes.jl'稱爲'basetype'),以便在更新中斷時很容易修復。 – tim

+0

對於至少'.name'字段訪問,應該使用庫函數'typename'。如果你在'VecOrMat {Int}'上試試這個,就可以看到'.name'。 –

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 
+0

這將返回一個'TypeName'。有沒有一種方法(除了'eval')在0.6上調用適當的構造函數? – tim

+2

@Tim適當的類型可以使用'.wrapper'從'TypeName'中恢復;儘管這種直接現場訪問在未來很容易破裂。 –