Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite types in Julia: Dictionaries as a named field?

I'd like to make a composite type that includes a dictionary as one of its named fields. But the obvious syntax doesn't work. I'm sure there's something fundamental that I don't understand. Here's an example:

type myType
    x::Dict()
end

Julia says: type: myType: in type definition, expected Type{T<:Top}, got Dict{Any,Any} which means, I'm guessing, that a dictionary is not a of Any as any named field must be. But I'm not sure how to tell it what I mean.

I need an named field that is a dictionary. An inner constructor will initialize the dictionary.

like image 462
glwhart Avatar asked May 27 '15 15:05

glwhart


2 Answers

There's a subtle difference in the syntax between types and instances. Dict() instantiates a dictionary, whereas Dict by itself is the type. When defining a composite type, the field definitions need to be of the form symbol::Type.

That error message is a little confusing. What it's effectively saying is this:

in type definition, expected something with the type Type{T<:Top}, got an instance of type Dict{Any,Any}.

In other words, it expected something like Dict, which is a Type{Dict}, but instead got Dict(), which is a Dict{Any,Any}.

The syntax you want is x::Dict.

like image 118
mbauman Avatar answered Oct 30 '22 13:10

mbauman


Dict() creates a dictionary, in particular a Dict{Any,Any} (i.e. keys and values can have any type, <:Any). You want the field to be of type Dict, i.e.

type myType
    x::Dict
end

If you know the key and value types, you could even write, e.g.

type myType
    x::Dict{Int,Float64}
end
like image 22
IainDunning Avatar answered Oct 30 '22 13:10

IainDunning