[英]How to use an union of array and parametric NTuple as function argument type in Julia?
我正在尝试编写一个函数,该函数的参数可以是元组或数组。 例如,这适用于:
julia> temp(x::Union{Vector{Int64},NTuple{4,Int64}}) = sum(x)
temp (generic function with 1 method)
julia> temp((3,1,5,4))
13
julia> temp([3,1,5,4])
13
另一方面,当我尝试使用未指定长度的元组时,该数组将失败:
julia> temp(x::Union{Vector{Int64},NTuple{N,Int64}}) where N = sum(x)
temp (generic function with 1 method)
julia> temp([3,1,5,4])
ERROR: MethodError: no method matching temp(::Array{Int64,1})
Closest candidates are:
temp(::Union{Array{Int64,1}, Tuple{Vararg{Int64,N}}}) where N at REPL[1]:1
julia> temp((3,1,5,4))
13
这不是做事的方式吗? 我意识到我可以使用多个分派来解决此问题:
julia> temp(x::Vector{Int64}) = sum(x)
temp (generic function with 1 method)
julia> temp(x::NTuple{N,Int64}) where N = sum(x)
temp (generic function with 2 methods)
julia> temp((3,1,5,4))
13
julia> temp([3,1,5,4])
13
但我想了解Union
在朱莉娅的工作方式,并想知道是否有办法使用它来实现这一目标。
行为在Julia 0.6.3和Julia 0.7-alpha之间有所不同。 Julia 0.7-alpha中的内容更加一致,因为在这种情况下where
子句的位置无关紧要。
您可以通过在函数定义内移动where
子句来解决问题的两种方法:
julia> temp1(x::Union{Vector{Int64},NTuple{N,Int64}} where N) = sum(x)
temp1 (generic function with 1 method)
julia> temp1([3,1,5,4])
13
julia> temp1((3,1,5,4))
13
julia> temp2(x::Union{Vector{Int64},NTuple{N,Int64} where N}) = sum(x)
temp2 (generic function with 1 method)
julia> temp2([3,1,5,4])
13
julia> temp2((3,1,5,4))
13
也可以避免使用Vararg
这样指定where N
的Vararg
:
julia> temp3(x::Union{Vector{Int64}, Tuple{Vararg{Int64}}}) = sum(x)
temp3 (generic function with 1 method)
julia> temp3((3,1,5,4))
13
julia> temp3([3,1,5,4])
13
您的功能将正常工作:
julia> temp(x::Union{Vector{Int64},NTuple{N,Int64}}) where N = sum(x)
temp (generic function with 1 method)
julia> temp([3,1,5,4])
13
julia> temp((3,1,5,4))
13
temp1
, temp2
和temp3
也将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.