简体   繁体   English

如何在Julia中使用数组和参数NTuple的联合作为函数参数类型?

[英]How to use an union of array and parametric NTuple as function argument type in Julia?

I am trying to write a function that takes an argument that can be a tuple or an array. 我正在尝试编写一个函数,该函数的参数可以是元组或数组。 This works for example: 例如,这适用于:

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

On the other hand, when I try to use a tuple of an unspecified length, it fails for the array: 另一方面,当我尝试使用未指定长度的元组时,该数组将失败:

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

Is this not the way of doing things? 这不是做事的方式吗? I realise that I can solve this using multiple dispatch: 我意识到我可以使用多个分派来解决此问题:

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

but I am trying to understand how Union works in julia, and wondering if there is a way to achieve this using it. 但我想了解Union在朱莉娅的工作方式,并想知道是否有办法使用它来实现这一目标。

The behavior differs between Julia 0.6.3 and Julia 0.7-alpha. 行为在Julia 0.6.3和Julia 0.7-alpha之间有所不同。 What we have in Julia 0.7-alpha is more consistent as location of where clause does not matter in this case. Julia 0.7-alpha中的内容更加一致,因为在这种情况下where子句的位置无关紧要。

Case of Julia 0.6.3 朱莉娅案0.6.3

You have two ways to fix the problem by moving where clause inside function definition: 您可以通过在函数定义内移动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

also you can avoid the need to specify where N by using Vararg like this: 也可以避免使用Vararg这样指定where NVararg

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

Case of Julia 0.7-alpha 朱莉娅0.7-阿尔法案

Your function will just work: 您的功能将正常工作:

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

also temp1 , temp2 and temp3 will work. temp1temp2temp3也将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM