arrays - 为任何整数数组定义函数

标签 arrays function types julia

我想定义一个函数,它将任何以整数(并且只有整数)作为其元素的 2 维数组作为输入。虽然我知道我不必在 Julia 中指定函数参数的类型,但我想这样做是为了加快速度。

使用类型层次结构,我可以使用以下代码为将整数作为输入的函数执行此操作:


julia> function sum_two(x::Integer)
           return x+2
       end
sum_two (generic function with 1 method)

julia> sum_two(Int8(4))
6

julia> sum_two(Int16(4))


但是,当我尝试对 Array{Integer,2} 类型进行此操作时我收到以下错误:
julia> function sum_array(x::Array{Integer,2})
           return sum(x)
       end
sum_array (generic function with 1 method)

julia> sum_array(ones(Int8,10,10))
ERROR: MethodError: no method matching sum_array(::Array{Int8,2})
Closest candidates are:
  sum_array(::Array{Integer,2}) at REPL[4]:2
Stacktrace:
 [1] top-level scope at none:0

我不知道我能做些什么来解决这个问题。一种选择是通过以下方式为 Integer 的每个最低级别子类型定义方法:
function sum_array(x::Array{Int8,2})
           return sum(x)
       end

function sum_array(x::Array{UInt8,2})
           return sum(x)
       end
.
.
.


但是看起来不太实用。

最佳答案

首先:为函数指定输入参数的类型不会加速代码。这是一种误解。您应该在定义结构体时指定具体的字段类型,但对于函数签名,它对性能没有任何影响。你用它来控制调度。

现在,对于您的问题:Julia 的类型参数是不变的,这意味着即使 S<:T是真的,A{S}<:A{T}不是真的。您可以在此处阅读更多相关信息:https://docs.julialang.org/en/v1/manual/types/index.html#Parametric-Composite-Types-1

因此,ones(Int8,10,10) ,这是一个 Matrix{Int8}不是 Matrix{Integer} 的子类型.

为了让你的代码工作,你可以这样做:

function sum_array(x::Array{T, 2}) where {T<:Integer}
    return sum(x)
end

或使用这个不错的快捷方式
function sum_array(x::Array{<:Integer, 2})
    return sum(x)
end

关于arrays - 为任何整数数组定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57279788/

相关文章:

java - 从外部元素到内部元素遍历数组

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c++ - 当您只需要这些参数之一时,使用通过引用传递的不同参数调用函数的最佳方法

java - 为什么首选在条件语句中避免使用 Real domain (double/float)?

typescript - 为什么我可以在 Typescript 中创建不可能的交集类型?

objective-c - Swift: "Mapper is not a type",在 swift 和 Objective C 中为数组使用自定义映射类

python - 转换为 numpy 数组会导致 RAM 崩溃

c++ - 打乱矩阵

javascript - 在 JavaScript 函数中获取正确的值时出现问题

function - floor()/int() 函数实现