9
votes

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?

4

4 Answers

9
votes

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.

7
votes

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
votes

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}
2
votes

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.