我有以下模拟设置,其中包含抽象类型、具体类型作为子类型和函数f
它需要两个参数,第一个是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()
我想定义一个自定义调用函数Letter
简单调用的子类型f
.
(t::A)(x) = f(t, x)
(t::B)(x) = f(t, x)
虽然这有效,但似乎相当多余,特别是考虑到可能有更多的子类型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
如何概括调用函数以匹配任何(具体)子类型Letter
?
根据 Dan 的答案,元编程似乎是正确的选择
for T in Symbol.(subtypes(Letter))
@eval (t::$T)(x) = f(t, x)
end
为每种类型生成函数。
Or:
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
然而,使用结构/子类型作为枚举是灰心 https://docs.julialang.org/en/latest/manual/style-guide/#Avoid-confusion-about-whether-something-is-an-instance-or-a-type-1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)