julia变量的范围:在开放表达式中的循环内重新分配 [英] scope of julia variables: re-assigning within a loop in open expression
问题描述
我正在努力在Julia中的循环中重新分配变量.我有一个以下示例:
I am struggling with re-assigning a variable in a loop in Julia. I have a following example:
infile = "test.txt"
feature = "----"
for ln in 1:3
println(feature)
feature = "+"
end
open(infile) do f
#if true
# println(feature)
# feature = "----"
println(feature)
for ln in 1:5 #eachline(f)
println("feature")
#fails here
println(feature)
# because of this line:
feature = "+"
end
end
如果我在循环中重新分配,它将失败.我看到了变量作用域的问题,因为涉及嵌套作用域. 引用表示,循环引入了软' 范围.我无法从手册中找到范围open
表达式所属的内容,但是看起来它搞砸了,就好像我将open
替换为if true
一样,事情运行也很顺利.
It fails if I do reassignment within the loop. I see that the issue with the variable scope, and because nested scopes are involved. The reference says that the loops introduce 'soft' scope. I cannot find out from the manual what scope open
expression belongs to, but seemingly it screws things up, as if I replace open
with if true
, things run smoothly.
我是否正确理解open
引入了硬"作用域,这就是为什么重新分配追溯地使变量不确定的原因?
Do I understand correctly that open
introduces 'hard' scope and that it is the reason why re-assignment retroactively makes the variable undefined?
推荐答案
您应该想到的
open("file") do f
...
end
为
open(function (f)
...
end, "file")
也就是说,do
引入了与function
或->
相同的硬作用域.
that is, do
introduces the same kind of hard scope as a function
or ->
would.
因此要能够从该函数写入feature
,您需要做
So to be able to write to feature
from the function, you need to do
open(infile) do f
global feature # this means: use the global `feature`
println(feature)
for ln in 1:5
println("feature")
println(feature)
feature = "+"
end
end
请注意,只有在顶级(模块)范围内才是这种情况;一旦进入函数,就没有硬作用域.
Note that this is only the case in top-level (module) scope; once inside a function, there are no hard scopes.
(在这种情况下,for
循环是一条红色鲱鱼;无论循环的软作用域如何,对feature
的访问都将受到do
引入的匿名函数的硬作用域的限制.)
(The for
loop in this case is a red herring; regardless of the soft scope of the loop, the access to feature
will be limited by the hard scope of the anonymous function introduced by do
.)
这篇关于julia变量的范围:在开放表达式中的循环内重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!