【问题标题】:How can I generalize a custom type call function to an abstract type?如何将自定义类型调用函数泛化为抽象类型?
【发布时间】:2017-06-16 20:31:23
【问题描述】:

我有以下模拟设置,有一个抽象类型,具体类型作为子类型,还有一个函数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 的任何(具体)子类型?

【问题讨论】:

  • 棘手,我现在唯一得到的是:foreach(T-&gt;(t::T)(x) = f(t,x), subtypes(Letter))
  • 您的示例现在在 Julia 1.0 中运行,仅供参考。
  • @nix 你确定吗?我在 1.0 上看到了相同的错误消息。
  • @HarrisonGrodin 很抱歉我误解了您的要求。它现在仍然无法正常工作(v1.0.2)。
  • 似乎与问题#14919 相关,该问题仍处于打开状态。

标签: types julia abstract


【解决方案1】:

基于 Dan 的回答,元编程似乎是要走的路

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

但是,这种将结构/子类型用作枚举的做法是 discouraged

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 2016-02-14
    • 2023-03-11
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多