Lyn*_*ite 1 symbols dispatch julia
我听说过朱莉娅已经发布了符号的值,而且我也使用了todo Val{:MySymbol}.
但这似乎不起作用:
julia> foo(x) = "other"
foo (generic function with 1 method)
julia> foo(x::Val{:zinger}) = "It was zinger"
foo (generic function with 2 methods)
julia> foo(:zinger)
"other"
Run Code Online (Sandbox Code Playgroud)
为什么不输出"它是zinger"?
调度值并不神奇.它使用与在参数类型上调度完全相同的机制.因此,如果要对其进行分派,则需要传入一个实例参数类型,该类型具有该值作为类型参数.
在你的问题Val是参数类型 - 它只存在于这种事情.
所以你需要写:
julia> foo(Val{:zinger}())
"It was zinger"
Run Code Online (Sandbox Code Playgroud)
如果你想要,你可以编写一个重载foo来自动将其参数包装到一个类型参数中
julia> foo(x::Symbol) = foo(Val{x}())
foo (generic function with 3 methods)
julia> foo(:zinger)
"It was zinger"
Run Code Online (Sandbox Code Playgroud)
但是,这将导致动态调度.
julia> @code_lowered foo(:zinger)
CodeInfo(:(begin
nothing
return (Main.foo)(((Core.apply_type)(Main.Val, x))())
end))
Run Code Online (Sandbox Code Playgroud)
vs完全实现的编译时解决方案:
julia> @code_lowered foo(Val{:zinger}())
CodeInfo(:(begin
nothing
return "It was zinger"
end))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
682 次 |
| 最近记录: |