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

标签 arrays 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 中的工作原理,并想知道是否有办法使用它来实现此目的。

最佳答案

Julia 0.6.3 和 Julia 0.7-alpha 之间的行为有所不同。我们在 Julia 0.7-alpha 中拥有的内容更加一致,因为在这种情况下 where 子句的位置并不重要。

Julia 0.6.3 案例

您有两种方法可以通过将 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,如下所示:

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 0.7-alpha 案例

你的函数将会正常工作:

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

temp1temp2temp3 也可以工作。

关于arrays - 如何在 Julia 中使用数组和参数 NTuple 的联合作为函数参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50655337/

相关文章:

arrays - 哈希数组之间的交集,但返回完整的哈希

string - Julia 中不区分大小写的字符串比较

julia - 如何从 Julia 中的文件名中提取扩展名?

julia - 如何在 Julia 中构建直方图

c++ - 将宽字符串或宽字符数组转换为简单字符数组的最简单方法?

javascript - 如何使用 JavaScript 读取 Json 中的数组

python - 将长列表全部写入一行

c - 将文本文件中的数字列表读入二维数组

julia - 在没有互联网连接的情况下使用 julia 语言(镜像?)

julia - 如何在 Julia 中实现迭代器?