我正在努力在 Julia 的循环中重新分配变量。我有一个以下的例子:
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
如果我在循环内重新分配,它会失败。我发现变量作用域存在问题,因为涉及嵌套作用域。这参考 http://docs.julialang.org/en/release-0.4/manual/variables-and-scoping/说循环引入了“软”范围。我从手册中找不到什么范围open
表达式属于,但看起来它把事情搞砸了,好像我替换了open
with if true
,事情进展顺利。
我的理解正确吗open
引入了“硬”作用域,这就是重新分配追溯性地使变量未定义的原因?
你应该想到
open("file") do f
...
end
as
open(function (f)
...
end, "file")
那是,do
引入了与function
or ->
would.
所以能够写信给feature
从功能上来说,你需要做
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
请注意,这仅是顶级(模块)范围内的情况;一旦进入函数内部,就不存在硬作用域了。
(The for
在这种情况下,循环是一个红鲱鱼;无论循环的软范围如何,都可以访问feature
将受到以下引入的匿名函数的硬作用域的限制do
.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)