使用 for 循环在 julia 1.0.0 中确定范围对初学者是否有意义? [英] Does scoping in julia 1.0.0 with for-loops make sense to beginners?

查看:14
本文介绍了使用 for 循环在 julia 1.0.0 中确定范围对初学者是否有意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 julia 1.0.0 中,我得到以下 for 循环作用域行为:

In julia 1.0.0, I get the following for-loop scoping behavior:

julia> counts = 0
0
julia> for i in 1:10
       counts += 1
   end
ERROR: UndefVarError: counts not defined

我发现解决方案是在 for 循环内使 counts 变量 global.

I found the solution was to make the counts variable global inside the for loop.

julia> for i in 1:10
           global counts += 1
       end
julia> counts
10

但是,作为 Julia 的新手,这种行为几乎让我放弃了这门语言,因为它似乎与其他语言大不相同.

However, as a newcomer to julia this behavior almost made me quit the language because it seems so different from other languages.

现在我看到了上面的解决方案,我想知道这对 julia 初学者来说是否直观.这对我来说并不直观,虽然我在相当长的一段时间后终于能够解决它.

Now that I see the solution above, I wonder if this is intuitive to beginning julia users. It was not intuitive to me, though I was finally able to solve it after quite a bit of time.

这是令人困惑的部分.我认为在初始化时创建一个全局变量可以解决问题.它没有:

Here is the confusing part. I thought making a variable global when it was initialized would solve the problem. It does not:

julia> global c = 0
julia> for i in 1:10
           c += 1
       end
ERROR: UndefVarError: c not defined

上面 c 的全局范围会向下流入 for 循环似乎很自然,但是 for 循环中 c 的第一次初始化显然会创建一个不同的 for 循环本地 c.

It would seem natural that the global scope of c above would flow down into the for-loop, but the first initialization of c in the for-loop apparently creates a different for-loop local c.

这对经验丰富的 julia 开发人员有意义吗?

Does this make sense to experienced julia developers?

推荐答案

我认为,对于交互式使用,这种行为不是最佳的,它可能会改变为 REPL、IJulia 等中的预期行为很快.你可以在这里找到讨论:https://github.com/JuliaLang/julia/issues/28789

I think there is agreement that, for interactive usage, this behavior is not optimal and it is likely going to change to the expected behavior in the REPL, IJulia etcetera soon. You can find the discussion here: https://github.com/JuliaLang/julia/issues/28789

但是请注意,一旦将其包装到本地范围(例如函数或 let 块)中,一切都会按预期工作.

Note, however, that everything works as expected once you wrap it into a local scope, such as a function or a let block for example.

在此处查看我的答案:Julia 中的变量范围更多信息/参考.

See my answer here: Scope of variables in Julia for some more information/references.

这篇关于使用 for 循环在 julia 1.0.0 中确定范围对初学者是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆