ail*_*luj 8 function multiple-dispatch julia
您将如何实现这样的功能:
function foo(a,b...,c)
println(a,b,c)
end
Run Code Online (Sandbox Code Playgroud)
foo(2,3,3,"last")
Run Code Online (Sandbox Code Playgroud)
=> a = 2 , b = (3,3) , c = "最后一个"
我不能使用类似的东西:
function foo(a,b...)
c = b[end]
println(a,b,c)
end
Run Code Online (Sandbox Code Playgroud)
因为我想在 c 上调度,即我想要有方法:
foo(a,b...,c::Foo)
Run Code Online (Sandbox Code Playgroud)
和
foo(a,b...,c::Bar)
Run Code Online (Sandbox Code Playgroud)
我也不能有这样的东西:
foo_wrapper(a,b...) = foo(a,b[1:end-1],b[end])
Run Code Online (Sandbox Code Playgroud)
因为我也想在 foo 上调度。
这有可能吗?
您可以反转顺序,然后分派辅助函数:
function foo(a,d...)
c = last(d)
b = d[begin:end-1]
return _foo(a,c,b...)
end
function _foo(a,c::Int,b...)
return c+1
end
function _foo(a,c::Float64,b...)
return 2*c
end
Run Code Online (Sandbox Code Playgroud)
在 REPL 中:
julia> foo(1,2,3,4,5,6)
7
julia> foo(1,2,3,4,5,6.0)
12.0
julia> foo(1,2,8.0)
16.0
julia> foo(1,90) #b is of length zero in this case
91
Run Code Online (Sandbox Code Playgroud)