Pok*_*eLu 4 struct symbols multiple-dispatch julia
正如标题中提到的,我想使用multiple-dispatch来分配同一个struct的不同行为,通过Symbol来区分。该结构体可以构造如下:
\nstruct AbstractAlgorithm\n algorithmName::String\n algorithmSymbol::Symbol\n\n function AbstractAlgorithm(algorithmName::String)\n if algorithmName \xe2\x88\x89 ("Value Iteration", "Policy Iteration")\n error("Given algorithm $algorithmName not defined yet.")\n elseif algorithmName=="Value Iteration"\n new(algorithmName, Symbol("vIter"))\n elseif algorithmName=="Policy Iteration"\n new(algorithmName, Symbol("pIter"))\n end\n end \nend\nRun Code Online (Sandbox Code Playgroud)\n我想在函数中使用不同的符号来区分相同的结构,例如:
\nfunction A(a::AbstractAlgorithm with Symbol vIter) = do A1\nfunction A(a::AbstractAlgorithm with Symbol pIter) = do A2\nRun Code Online (Sandbox Code Playgroud)\n我应该如何使用多重调度来设计函数 A?
\n这似乎是一种非常不寻常且不惯用的方法,因为 Julia 本身支持多重调度。此外,当您将其用于具体AbstractNN类型时,它是抽象类型的命名约定。
为什么不使用调度:
abstract type AbstractAlgorithm end
struct ValueIteration <: AbstractAlgorithm end
struct PolicyIteration <: AbstractAlgorithm end
Run Code Online (Sandbox Code Playgroud)
然后根据算法对象的类型实现您想要的行为:
A(::ValueIteration) = A1()
A(::PolicyIteration) = A2()
Run Code Online (Sandbox Code Playgroud)
我添加了对@Giovanni 提议的一个小评论作为答案,因为它太长了(+对代码进行了一些细微的更改)。
如果你想使用参数类型(而不是像 @DNF 提出的类型层次结构),你可以这样写:
struct Algorithm{T}
algorithmName::String
function Algorithm(algorithmName::AbstractString)
algorithmName == "Value Iteration" && return new{:vIter}(algorithmName)
algorithmName == "Policy Iteration" && return new{:pIter}(algorithmName)
error("Given algorithm $algorithmName not defined yet.")
end
end
function A(a::Algorithm{:pIter})
# ...
end
function A(a::Algorithm{:vIter})
# ...
end
Run Code Online (Sandbox Code Playgroud)
要点是Symbol可以用作类型参数,因此您不必将其包装在Val.
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |