Does scoping in julia 1.0.0 with for-loops make sense to beginners? [closed]

£可爱£侵袭症+ 提交于 2019-12-23 07:11:13

问题


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

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

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

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

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.

Does this make sense to experienced julia developers?


回答1:


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

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.

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



来源:https://stackoverflow.com/questions/52187073/does-scoping-in-julia-1-0-0-with-for-loops-make-sense-to-beginners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!