我想生成一个函数<c:if test="#{beanMb.beanList.size() gt 0 }">
....code
</c:if>
,它在其闭包中保留变量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
的类型,我怀疑这些类型由于缺少{{1}的类型推断1}}。
有没有办法改善它?
答案 0 :(得分:3)
虽然在函数eval
中调用了g
,但它会在全局上下文中计算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_warntype f()
:
Variables:
b::Int64
#s2::Int64
i::Int64