[英]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.