In Julia, how do I create custom types MyOrderedDictA
and MyOrderedDictB
such that:
OrderdDict
, and can be passed to any function that accepts AbstractDict
sI suspect\hope this is straightforward, but haven’t been able to figure it out.
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)
Others will be better placed to answer this, but a quick take:
For this you will need to look at the OrderedDict
implementation, and specifically which methods are defined for OrderedDict
s. If you want to be able to pass it to methods accepting AbstractDict
s you need to subtype it like struct MyDictA{T, S} <: AbstractDict{T, S}
If you define two structs they will automatically be discting from each other!? (I might be misunderstanding the question here)
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