小编Ald*_*yeg的帖子

为任何整数数组定义函数

我想定义一个函数,该函数将任何以整数(且只有整数)为元素的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))

Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用该类型时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
Run Code Online (Sandbox Code Playgroud)

我没有办法解决这个问题。一种选择是通过以下方式为Integer的每个最低级别的子类型定义方法:

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

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

Run Code Online (Sandbox Code Playgroud)

但这看起来并不实用。

arrays types function julia

3
推荐指数
1
解决办法
58
查看次数

标签 统计

arrays ×1

function ×1

julia ×1

types ×1