[英]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
)几个不同的函数,每个函数Kernel
的子类——即
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当我使用上面的内容时,它的工作原理是当我调用
ExpKernel(a,b)
时我得到了正确的值,但是当我尝试将这些 kernel 对象传递给不同的构造函数时,比如
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但是当我尝试调用
Model(ExpKernel)
时出现错误
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.但是请注意,这不是 Julia 中的典型设计模式 - 通常您会使用https://docs.julialang.org/en/v1/manual/methods/#Function-like-objects-1模式来实现此类功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.