Har*_*din 5 types abstract julia
我有以下模拟设置,抽象类型,具体类型作为子类型,以及一个f带两个参数的函数,第一个是a Letter.
abstract type Letter end
struct A <: Letter end
struct B <: Letter end
f(::A, x) = ('a', x)
f(::B, x) = ('b', x)
a = A()
b = B()
Run Code Online (Sandbox Code Playgroud)
我想为Letter只需调用的子类型定义一个自定义调用函数f.
(t::A)(x) = f(t, x)
(t::B)(x) = f(t, x)
Run Code Online (Sandbox Code Playgroud)
虽然这有效,但似乎相当多余,特别是考虑到可能有更多的亚型Letter.我的尝试如下,但似乎都没有效果.
julia> (t::Letter)(x) = f(t, x)
ERROR: cannot add methods to an abstract type
julia> (t::T)(x) where T <: Letter = f(t, x)
ERROR: function type in method definition is not a type
Run Code Online (Sandbox Code Playgroud)
如何推广一个调用函数来匹配任何(具体)子类型Letter?
根据 Dan 的答案,元编程似乎是正确的选择
for T in Symbol.(subtypes(Letter))
@eval (t::$T)(x) = f(t, x)
end
Run Code Online (Sandbox Code Playgroud)
为每种类型生成函数。
或者:
for T in Symbol.(subtypes(Letter))
c = Char(lowercase(first(String(T))))
@eval f(::$T, x) = ($c, x)
@eval (t::$T)(x) = f(t, x)
end
Run Code Online (Sandbox Code Playgroud)
但是,不鼓励使用结构/子类型作为枚举
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |