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?
Type Unions A type union is a special abstract type which includes as objects all instances of any of its argument types, constructed using the special Union keyword: julia> IntOrString = Union{Int,AbstractString} Union{Int64, AbstractString} julia> 1 :: IntOrString 1 julia> "Hello!" :: IntOrString "Hello!"
The choice of which method to execute when a function is applied is called dispatch. Julia allows the dispatch process to choose which of a function's methods to call based on the number of arguments given, and on the types of all of the function's arguments.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With