如何将自定义类型调用函数泛化为抽象类型? [英] How can I generalize a custom type call function to an abstract type?
问题描述
我有以下模拟设置,具有抽象类型,具体类型作为子类型以及带有两个参数的函数f
,第一个是Letter
.
I have the following mock setup, with an abstract type, concrete types as subtypes, and a function f
which takes two arguments, the first being 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()
我想为Letter
子类型定义一个自定义调用函数,该函数简单地调用f
.
I would like to define a custom call function for Letter
subtypes which simply calls f
.
(t::A)(x) = f(t, x)
(t::B)(x) = f(t, x)
虽然可行,但似乎很多余,尤其是考虑到Letter
的子类型可能更多.我的尝试如下,但似乎都无效.
While this works, it seems quite redundant, especially considering that there could be many more subtypes of Letter
. My attempts are as follows, but neither seem to work.
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
的任何(具体)子类型?
How can I generalize a call function to match any (concrete) subtype of Letter
?
推荐答案
以Dan的回答为基础,元编程似乎是必经之路
Building on Dan's answer, metaprogramming seems to be the way to go
for T in Symbol.(subtypes(Letter))
@eval (t::$T)(x) = f(t, x)
end
为每种类型生成函数.
或者:
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
However, this use of structs/subtypes as enums is discouraged
这篇关于如何将自定义类型调用函数泛化为抽象类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!