Julia 如何为闭包中的变量提供类型?
我想生成一个函数Julia 如何为闭包中的变量提供类型?,julia,Julia,我想生成一个函数f,它将变量a保持在其闭包中,如下所示: function g(a::Vector{Int}) gf = quote x = $a function test() b = 0 for i in eachindex(x) b += i end b end end eval(gf)
f
,它将变量a
保持在其闭包中,如下所示:
function g(a::Vector{Int})
gf = quote
x = $a
function test()
b = 0
for i in eachindex(x)
b += i
end
b
end
end
eval(gf)
end
f = g([1,2,3,4])
@code_warntype f()
Variables:
b::ANY
#s41::ANY
i::ANY
Body:
begin # In[21], line 6:
b = 0 # In[21], line 7:
GenSym(0) = (Main.eachindex)(Main.x)::ANY
#s41 = (top(start))(GenSym(0))::ANY
unless (top(!))((top(done))(GenSym(0),#s41)::ANY)::ANY goto 1
2:
GenSym(1) = (top(next))(GenSym(0),#s41)::ANY
i = (top(getfield))(GenSym(1),1)::ANY
#s41 = (top(getfield))(GenSym(1),2)::ANY # In[21], line 9:
b = b + i::ANY
3:
unless (top(!))((top(!))((top(done))(GenSym(0),#s41)::ANY)::ANY)::ANY goto 2
1:
0: # In[21], line 11:
return b
end::ANY
如您所见,f
效率有点低,因为类型推断无法区分i
、b
的类型,我怀疑这是由于缺少a
的类型推断
有什么方法可以改进它吗?尽管在函数
g
中调用了eval
,但它在全局上下文中计算gf
。在全局上下文中,变量的类型推断比较困难。将值定义为const
可以改善这种情况。在您的示例中:
function g(a::Vector{Int})
newvar= gensym("t")
gf = quote
const $newvar = $a
function test()
b = 0
for i in eachindex($newvar)
b += i
end
b
end
end
eval(gf)
end
提供更好的类型化变量。从@code\u warntype f()
:
谢谢,我知道我必须在某个地方声明
const
,但我没有意识到我可以将const
放在引号内
Variables:
b::Int64
#s2::Int64
i::Int64