在julia 1.0.0中使用for循环进行作用域对初学者有意义吗? [英] Does scoping in julia 1.0.0 with for-loops make sense to beginners?

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

问题描述

在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.

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

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