Julia: Scoping rules

Created on 8 Aug 2018  路  3Comments  路  Source: JuliaLang/julia

Most helpful comment

0.7 correctly gives a warning that global k is needed to access k in the loop.

This is a slight inconvenience in the REPL, but is well worth it for programming in general since the scope rules are now much simpler and prefer making variables loop-local, which is better for multiple reasons. One example we run into a lot is that test suites tend to use global variables. Then somebody adds a loop somewhere with a variable intended to be local, but ends up modifying global state.

I also think the new version makes it bit easier to explain that the global version is slower, since it's clearer that you're updating a global variable.

All 3 comments

Julia v1.0 seems to have problems with scope in the REPL within a for loop

eg: A quick evaluation of PI ( -- the code works fine in 0.6.4)

julia> k = 0;
julia> n = 1000_000;
julia> @time for i in 1:n
         if (rand()^2 + rand()^2) < 1.0 
           k += 1       
         end
       end
ERROR: UndefVarError: k not defined
Stacktrace:
 [1] macro expansion at ./REPL[3]:3 [inlined]
 [2] top-level scope at ./util.jl:156 [inlined]
 [3] top-level scope at ./none:0

Wrap this in a let .. end block and it is OK

julia> let
       k = 0; 
       n = 1000_000;
       @time for i in 1:n
         if (rand()^2 + rand()^2) < 1.0 
           k += 1       
         end
       end
       p = 4*k/n
       end
  0.010449 seconds
3.13978

0.7 correctly gives a warning that global k is needed to access k in the loop.

This is a slight inconvenience in the REPL, but is well worth it for programming in general since the scope rules are now much simpler and prefer making variables loop-local, which is better for multiple reasons. One example we run into a lot is that test suites tend to use global variables. Then somebody adds a loop somewhere with a variable intended to be local, but ends up modifying global state.

I also think the new version makes it bit easier to explain that the global version is slower, since it's clearer that you're updating a global variable.

Closing as the current behavior is intended.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TotalVerb picture TotalVerb  路  3Comments

i-apellaniz picture i-apellaniz  路  3Comments

arshpreetsingh picture arshpreetsingh  路  3Comments

ararslan picture ararslan  路  3Comments

musm picture musm  路  3Comments