Philip Swannell
Philip Swannell

Reputation: 935

Creating custom types in Julia

In Julia, how do I create custom types MyOrderedDictA and MyOrderedDictB such that:

  1. Each has all the functionality of an OrderdDict, and can be passed to any function that accepts AbstractDicts
  2. They are distinct from each other, so that I can take advantage of multiple dispatch.

I suspect\hope this is straightforward, but haven’t been able to figure it out.

Upvotes: 5

Views: 1375

Answers (2)

carstenbauer
carstenbauer

Reputation: 10117

Basically, what you have to do is to define your type MyOrderedDictA, wrapping a regular OrderedDict, and forward all functions that one can apply to an OrderedDict to this wrapped dict.

Unfortunately, the AbstractDict interface is (to my knowledge) currently not documented (cf. AbstractArray). You could look at their definition and check which functions are defined for them. Alternatively, there is the more practical approach to just use your MyOrderedDictA and whenever you get an error message, because a function is not defined, you forward this function "on-the-fly".

In any case, using the macro @forward from Lazy.jl you can do something along the lines of the following.

using Lazy

struct MyOrderedDictA{T,S} <: AbstractDict{T,S}
    dict::OrderedDict{T,S}
end

MyOrderedDictA{T,S}(args...; kwargs...) where {T,S} = new{T,S}(OrderedDict{T,S}(args...; kwargs...))

function MyOrderedDictA(args...; kwargs...)
    d = OrderedDict(args...; kwargs...)
    MyOrderedDictA{keytype(d),valtype(d)}(d)
end

@forward MyOrderedDictA.dict (Base.length, Base.iterate, Base.getindex, Base.setindex!)

d = MyOrderedDictA(2=>1, 1=>2)

Upvotes: 2

Nils Gudat
Nils Gudat

Reputation: 13800

Others will be better placed to answer this, but a quick take:

  1. For this you will need to look at the OrderedDict implementation, and specifically which methods are defined for OrderedDicts. If you want to be able to pass it to methods accepting AbstractDicts you need to subtype it like struct MyDictA{T, S} <: AbstractDict{T, S}

  2. If you define two structs they will automatically be discting from each other!? (I might be misunderstanding the question here)

Upvotes: 1

Related Questions