这段代码来自 JuliaBoxTutorials
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
i = 1;
while i <= length(myfriends)
friend = myfriends[i]
println("Hi $friend, it's great to see you!")
i += 1
end
使用 Julia v1.0 运行时出现此错误
UndefVarError: i not defined
Stacktrace:
[1] top-level scope at ./In[12]:5 [inlined]
[2] top-level scope at ./none:0
但是当
i += 1
替换为 global i += 1
有用。我猜这在 v0.6 中仍然有效,一旦新的 Intro to Julia 于本周五发布,本教程将进行调整。我只是想知道,是否有可能在不声明全局变量的情况下进行 while 循环?
最佳答案
由于@Michael Paul 和@crstnbr 已经在评论中回复,范围规则已更改( Scope of variables in Julia )。 for
和 while
循环引入了一个新的作用域,并且无法访问外部(全局)变量。您可以使用 global
获得范围访问权限关键字,但推荐的工作流程是将代码包装在函数中。
新设计的好处之一是,用户被迫避免这种直接影响函数性能的全局构造——当他们访问全局变量时,这些构造不能是类型稳定的。
一个缺点是在 REPL 中进行实验并看到此类错误时会出现困惑。
在我看来,新行为在可预测性方面更清晰。然而,在整个 Julia 社区中,这是一场非常艰难且长期的讨论;)
目前正在讨论是否通过使用 let
将 REPL 更改为与旧版本相同的行为。 -包裹:https://github.com/JuliaLang/julia/issues/28789
这是手动完成的不切实际的事情(比使用 global
关键字复杂得多),请参阅 Stefan Karpinski 的示例:https://github.com/JuliaLang/julia/issues/28789#issuecomment-414666648
无论如何,为了完整起见( 虽然我不建议这样做 )这里是一个使用 global
的版本:
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
i = 1;
N = length(myfriends)
while i <= N # you cannot even call a function here
# with a global, like length(myfriends)
global i, myfriends
friend = myfriends[i]
println("Hi $friend, it's great to see you!")
i += 1
end
但是请注意,这也是完全有效的:
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
greet(friend) = println("Hi $friend, it's great to see you!")
for friend in myfriends
greet(friend)
end
关于scope - 虽然没有全局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52037753/