Retrieving parameter types in Julia

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

+6
source share
4 answers
The answers of Sven and John are both perfectly correct. If you don’t want to enter method type parameters, as 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 several ways to hide this cat, but I think that eltype(keys(d)) and eltype(values(d)) by far the clearest, and since the keys and values functions simply return immutable objects of the form , the compiler is smart enough not to actually create any objects.

+6
source

If you write a function that does this for you, you can make types a parameter of the function, which can save you time searching at runtime:

 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} 
+7
source

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} 
+3
source

If you are only interested in 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 quite effective, because the compiler can output most of this at compile time.

+2
source

All Articles