Extracting parameter types in Julia

荒凉一梦 提交于 2020-01-13 09:16:27

问题


Suppose I write a function in Julia that takes a Dict{K,V} as an argument, then creates arrays of type Array{K,1} and Array{V,1}. How can I extract the types K and V from the Dict object so that I can use them to create the arrays?


回答1:


Sven and John's answers are both quite right. If you don't want to introduce method type parameters the way John's code does, you can use the eltype function:

julia> d = ["foo"=>1, "bar"=>2]
["foo"=>1,"bar"=>2]

julia> eltype(d)
(ASCIIString,Int64)

julia> eltype(d)[1]
ASCIIString (constructor with 1 method)

julia> eltype(d)[2]
Int64

julia> eltype(keys(d))
ASCIIString (constructor with 1 method)

julia> eltype(values(d))
Int64

As you can see, there are a few ways to skin this cat, but I think that eltype(keys(d)) and eltype(values(d)) are by far the clearest and since the keys and values functions just return immutable view objects, the compiler is clever enough that this doesn't actually create any objects.




回答2:


If you're writing a function that will do this for you, you can make the types a parameter of the function, which may save you some run-time lookups:

julia> function foo{K, V}(d::Dict{K, V}, n::Integer = 0)
          keyarray = Array(K, n)
          valarray = Array(V, n)
          # MAGIC HAPPENS
          return keyarray, valarray
       end
foo (generic function with 2 methods)

julia> x, y = foo(["a" => 2, "b" => 3])
([],[])

julia> typeof(x)
Array{ASCIIString,1}

julia> typeof(y)
Array{Int64,1}



回答3:


You can use keys and values in combination with typeof:

# an example Dict{K, V}
d = Dict{Int64, ASCIIString}()

# K
typeof(keys(d))
Array{Int64,1}

# V
typeof(values(d))
Array{ASCIIString,1}



回答4:


If you are just interested in the types, you can use eltype(d), or define even more specific functions

keytype{K}(d::Dict{K}) = K
valuetype{K,V}(d::Dict{K,V}) = V

and find the type immediately through

keytype(d)
valuetype(d)

As far as I understand, this should be pretty efficient because the compiler can deduce most of this at compile time.



来源:https://stackoverflow.com/questions/20991220/extracting-parameter-types-in-julia

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!