Thanks, I managed to figure it out by re-re-re-reading the docs. I was
suspecting that the answer will be about parametric types.
function df_to_m{T<:Jinnie.Jinnie_Model}(df::DataFrames.DataFrame, m::T) #
works!
sâmbătă, 27 februarie 2016, 09:31:23 UTC+1, Adrian Salceanu a scris:
>
> Hi,
>
> I stumbled upon an issue in my code and I can't quite figure out the
> behavior. Any hints would be much appreciated, thanks in advance.
>
> So, I have a function:
>
> function df_to_m(df::DataFrames.DataFrame, m::Jinnie_Model)
>
> It iterates over each row of the df DataFrame and instantiates the
> corresponding m model type, returning an array of m model instances.
>
> For example, say if I have this DataFrame (*df*)
>
> 1x3 DataFrames.DataFrame
> | Row | name | url | updated_at
> |
>
> |-----|---------|---------------------------------------|------------------------------|
> | 1 | "Bokeh" | "git://github.com/bokeh/Bokeh.jl.git" | "2016-02-10
> 19:21:57.209996" |
>
> I would call
>
> df_to_m(df, Jinnie.Package())
>
> and expect to get
>
> 1-element Array{Any,1}:
> Jinnie.Package("packages","name","Bokeh","git://
> github.com/bokeh/Bokeh.jl.git")
>
> where Jinnie_Model is an abstract type defined in the Jinnie module as
>
> abstract Jinnie_Model
>
> and Jinnie.Package extends Jinnie_Model
>
> type Package <: Jinnie_Model
> _table_name::AbstractString
> _id::AbstractString
> name::AbstractString
> url::AbstractString
>
> Package(; name = "", url = "") = new("packages", "name", name, url)
> end
>
> However, the problem is that df_to_m does not want to accept subtypes of
> Jinnie_Model:
>
> ERROR: MethodError: `df_to_m` has no method matching
> df_to_m(::DataFrames.DataFrame, ::Jinnie.Package)
> Closest candidates are:
> df_to_m(::DataFrames.DataFrame, ::Jinnie.Jinnie_Model)
>
> If I drop the type constraint in the function's definition, it works
> great, as expected:
>
> function df_to_m(df::DataFrames.DataFrame, m) # this version works
>
> ==================================
>
> My questions are:
>
> 1. how can I get the function to accept subtypes of Jinnie_Model while
> keeping the type constraint?
>
> 2. I don't like passing instances like Jinnie.Package() and I would
> rather pass the type itself Jinnie.Package into the polymorphic function.
> It's a crappy code smell so I must be doing something wrong.
>
> I experimented with defining the function as
>
> function df_to_m(df::DataFrames.DataFrame, m::Type{Jinnie.Jinnie_Model})
>
> but got the same error, polymorphism be damned.
>
> ERROR: MethodError: `df_to_m` has no method matching
> df_to_m(::DataFrames.DataFrame, ::Type{Jinnie.Package})
> Closest candidates are:
> df_to_m(::DataFrames.DataFrame, ::Type{Jinnie.Jinnie_Model})
>
> How could the function be defined to work with the types itself (rather
> than instances) and be polymorphic as intended?
>
> Thanks for your time.
>
> Cheers
>