November 2018
Intermediate to advanced
460 pages
14h 1m
English
In Julia, loops and comprehensions create a new scope, and hence we can make a similar test with a comprehension:
julia> z=5;julia> [(x=z+i;x) for i in 1:2]2-element Array{Int64,1}: 6 7
However, if we try to assign a value to z , it will not work (the comprehension creates a new local scope):
julia> z = 5;julia> [(z=z+i;z) for i in 1:2] ERROR: UndefVarError: z not defined
We can, though, set z to be global , and now it is reachable within the comprehension:
julia> z = 5;julia> [(global z=z+i;z) for i in 1:2]2-element Array{Int64,1}: 6 8
The let statement can also create a new environment that can hold values that are stored even when the scope of the let block is left:
julia> let state = 0 global counter() = (state += 1
Read now
Unlock full access