当我们有这么多结构时,如何定义多个调度?

bit*_*ise 1 julia

如果我们有一些结构,那么使用多个调度就不是问题。但是,当我们有这么多结构时,如何使用多个调度?例如,我们有N个这样的结构:

struct An
   a::Float64
end
Run Code Online (Sandbox Code Playgroud)

和类似的功能:

f!(a::Ai) = exp(Ai.a)
Run Code Online (Sandbox Code Playgroud)

当N大时,将是头痛的。考虑到此功能简单易用!功能可能是如此之大!

ARa*_*rez 7

如果所有结构的函数定义都相同,则可以将它们定义为某种抽象类型的具体类型,而只保留一个在抽象类型上分派的函数:

julia> abstract type Allmystructs end

julia> struct A1 <: Allmystructs
           a::Float64
       end

julia> struct A2 <: Allmystructs
           a::Float64
       end
julia> f(A :: Allmystructs) = exp(A.a)
f (generic function with 1 method)

julia> test1 = A1(5)
A1(5.0)

julia> test2 = A2(8)
A2(8.0)

julia> f(test1)
148.4131591025766

julia> f(test2)
2980.9579870417283
Run Code Online (Sandbox Code Playgroud)

当然,如果每种类型的struct的函数定义不同,则可能不是您要查找的内容。在这种情况下,元编程可以成为您的朋友。

编辑:错别字。