我正在尝试在 Julia 中设计一些代码,这些代码将采用用户提供的函数列表,并基本上对它们应用一些代数运算。
看来如果这个函数列表是闭包,则不会推断它们的返回值,导致根据@code_warntype 导致类型不稳定的代码。
我尝试为闭包提供返回类型,但似乎无法找到正确的语法。
下面是一个例子:
functions = Function[x -> x]
function f(u)
ret = zeros(eltype(u), length(u))
for func in functions
ret .+= func(u)
end
ret
end
Run Code Online (Sandbox Code Playgroud)
运行这个:
u0 = [1.0, 2.0, 3.0]
@code_warntype f(u0)
Run Code Online (Sandbox Code Playgroud)
并获得
Body::Array{Float64,1}
1 ? %1 = (Base.arraylen)(u)::Int64
? %2 = $(Expr(:foreigncall, :(:jl_alloc_array_1d), Array{Float64,1}, svec(Any, Int64), :(:ccall), 2, Array{Float64,1}, :(%1), :(%1)))::Array{Float64,1}
? %3 = invoke Base.fill!(%2::Array{Float64,1}, 0.0::Float64)::Array{Float64,1}
? %4 = Main.functions::Any
? %5 = (Base.iterate)(%4)::Any
? %6 = (%5 === nothing)::Bool
? %7 = (Base.not_int)(%6)::Bool …Run Code Online (Sandbox Code Playgroud)