Issue with Array of user-defined type

Hello,

I would like to create a parametric struct Basis that holds a vector of a user-defined type ParamFcn. I define the functions getindex and setindex! for the struct Basis but the command @warn_type that the the type can not be inferred

Here is an example:

import Base: @propagate_inbounds

abstract type ParamFcn end

struct constant <:ParamFcn
end

struct linear <:ParamFcn
end

struct rbf <:ParamFcn
        μ::Float64
        σ::Float64
end

struct Basis{m}
    f::Array{ParamFcn,1}
    function Basis(f::Array{ParamFcn,1})
        return new{size(f,1)}(f)
    end
end


Base.size(B::Basis{m}) where {m} = m
@propagate_inbounds Base.getindex(B::Basis{m}, i::Int) where {m} = getindex(B.f,i)
@propagate_inbounds Base.setindex!(B::Basis{m}, v::ParamFcn, i::Int) where {m} = setindex!(B.f,v,i)

B = Basis([constant(); linear(); rbf(1.0, 1.0)])
@code_warntype B[2]

Variables
#self#::Core.Compiler.Const(getindex, false)
B::Basis{3}
i::Int64

Body::ParamFcn
1 ─ nothing
│ %2 = Base.getproperty(B, :f)::Array{ParamFcn,1}
│ %3 = Main.getindex(%2, i)::ParamFcn
└── return %3

The output ::ParamFcn is in red

It’s just telling you that the eltype of your array is an abstract type, equivalent to this:

Real[1, 2.0, 3//1]
@code_warntype ans[2] # Body::Real
2 Likes

Is it going to influence the performance of the code?

Yes it might. Certainly computing with a large array of eltye Real will be slower than the same with concrete Float64.

1 Like

How can I circumvent this issue. ParamFcn is an abstract type to store parameterized scalar functions.