Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom types in Julia

Tags:

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.

like image 846
Philip Swannell Avatar asked Oct 16 '22 09:10

Philip Swannell


2 Answers

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)
like image 98
carstenbauer Avatar answered Oct 21 '22 03:10

carstenbauer


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)

like image 43
Nils Gudat Avatar answered Oct 21 '22 03:10

Nils Gudat