简体   繁体   中英

creating an abstract type as a wrapper for different functions

I'm trying to create an abstract type that is a superclass (called Kernel ) several different of functions, each a subclass of Kernel --ie

abstract type Kernel end

struct ExponentialKernel <: Kernel
    ExponentialKernel(rate::Number, x::Number) = exp(-1*rate*x)
end


struct GaussianKernel <: Kernel
    GaussianKernel(sigma::Number, x::Number) = (1.0/(sigma*sqrt(2*pi))) * exp((-1*x^2)/(2*sigma^2)
end

...

and so on.

When I use what I have above, it works in the sense that when I call ExpKernel(a,b) I get the right value, but when I try to pass these kernel objects to a different constructor, like

mutable struct Model
    kernel::T where {T <: Kernel}    

    Model(kernel) = new(kernel) 
end

but when I try to call Model(ExpKernel) I get the error

ERROR: MethodError: Cannot `convert` an object of type Type{ExpKernel} to an object of type Kernel

Is there something I'm missing about types here?

Is this what you are looking for?

julia> mutable struct Model
           kernel::DataType

           Model(k::Type{<:Kernel}) =
               isconcretetype(k) ? new(k) : throw(ArgumentError("concrete type required"))
       end

julia> Model(GaussianKernel)
Model(GaussianKernel)

julia> Model(1)
ERROR: MethodError: no method matching Model(::Int64)
Closest candidates are:
  Model(::Type{var"#s1"} where var"#s1"<:Kernel) at REPL[4]:4
Stacktrace:
 [1] top-level scope at REPL[6]:1

julia> Model(Kernel)
ERROR: ArgumentError: concrete type required
Stacktrace:
 [1] Model(::Type{Kernel}) at .\REPL[4]:4
 [2] top-level scope at REPL[7]:1

Note however that this is not a typical design pattern in Julia - normally you would use https://docs.julialang.org/en/v1/manual/methods/#Function-like-objects-1 pattern for such functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM