如何将自定义类型调用函数泛化为抽象类型? [英] 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屋!