调用Julia中的父函子
因为版本1.3允许。因此,我想知道是否可以从子对象显式调用父函子 例如,在下面的示例中,是否有任何方法可以通过调用Julia中的父函子,julia,dispatch,Julia,Dispatch,因为版本1.3允许。因此,我想知道是否可以从子对象显式调用父函子 例如,在下面的示例中,是否有任何方法可以通过bar::bar对象调用(x::Foo)( abstract type Foo end (x::Foo)() = "Invoked Foo functor." struct Bar <: Foo end (x::Bar)() = "Invoked Bar functor." bar = Bar() @info "Calling bar functor directly." ba
bar::bar
对象调用(x::Foo)(
abstract type Foo end
(x::Foo)() = "Invoked Foo functor."
struct Bar <: Foo end
(x::Bar)() = "Invoked Bar functor."
bar = Bar()
@info "Calling bar functor directly."
bar() |> println
@info "Invoking parent functor."
# ??? - how to invoke parent functor (x::Foo)() (e.g. desired output "Invoked Foo functor")
invoke(bar,Tuple{Bar}, bar) |> println
抽象类型Foo-end
(x::Foo)(=“调用了Foo函子。”
结构条println
@信息“调用父函数。”
# ??? - 如何调用父函子(x::Foo)()(例如,所需的输出“调用的Foo函子”)
调用(bar,元组{bar},bar)|>println
使用默认结构怎么样
abstract type Foo end
(x::Foo)() = "Invoked Foo functor."
struct Bar <: Foo end
(x::Bar)() = "Invoked Bar functor."
struct DefaultFoo <: Foo end
#here we dont define an specialized method, DefaultFoo calls Foo
#an interface to define default methods:
default(x::Type{Foo}) = DefaultFoo
function parent(x::T) where {T}
y = default(supertype(T))
return y()
end
这需要为每个超类型定义defaultFoo
类型和default(x::type{T})
。可以使用以下宏自动执行此操作:
macro create_default_functor(type)
a = gensym(type)
esc(quote
struct $a <: $type end
default(x::Type{$type}) = $a
end)
end
宏创建默认函数(类型)
a=gensym(类型)
电子稳定控制系统
struct$a为什么您不想只定义函数x(y::Foo)…end
?不,我可以完全用函数替换它(因为函数提供的任何功能都可以由简单函数代替)。我只是想知道是否有语法上的甜点可以做到这一点,或者我是否必须坚持你建议的解决方法。在Julia中,函数比定义一个函子和处理Dispatch更为惯用。这不是立即的(甚至不是立即的)可能是因为invoke
是一个内置的。现在,您可能能够做的是在适当的位置调用Julia的内部。这只需要一些munging就可以完成-作为对非官方API的攻击,Julia很容易发生更改。
macro create_default_functor(type)
a = gensym(type)
esc(quote
struct $a <: $type end
default(x::Type{$type}) = $a
end)
end
abstract type Foo end
(x::Foo)() = "Invoked Foo functor."
@create_default_functor Foo
struct Bar <: Foo end
(x::Bar)() = "Invoked Bar functor."
function parent(x::T) where {T}
y = default(supertype(T))
return y()
end
#calling bar
bar = Bar()
bar()
#calling foo
foo = parent(bar)
foo()