"outer" keyword, Julia for-loop variable scope

Viewed 290

I want to use a for-loop to implement an iterative method. At the end of the loop I also want to check if max_iter is reached:

function iterative_method()

    iter_max = 10

    for iter in 1:iter_max 
        # some computations
        # ...
        # if converged 
        #    break
        # end
    end

    @assert iter!=iter_max "max iteration = $iter_max reached!"

end

Unfortunately the @assert cannot work as iter is out of scope:

julia> iterative_method()
ERROR: UndefVarError: iter not defined

Question: how to make iter visible outside the for loop block?

1 Answers

The solution is to use outer as described in the official doc: Loops-and-Comprehensions

function iterative_method()

    iter_max = 10

    local iter                           # <- declare "iter" variable
    for outer iter in 1:iter_max         # <- use "outer" keyword
        # some computations
        # ...
        # if converged 
        #    break
        # end
    end

    @assert iter!=iter_max "max iteration = $iter_max reached!"

end

which now works as expected:

julia> iterative_method()
ERROR: AssertionError: max iteration = 10 reached!

However, Julia core devs have expressed regret about adding this feature and will likely remove it in Julia 2.0, so it's probably clearer and simpler to express this with the following slightly more verbose version:

function iterative_method()

    iter_max = 10

    local iter
    for i in 1:iter_max
        iter = i
        # some computations
        # ...
        # if converged 
        #    break
        # end
    end

    @assert iter!=iter_max "max iteration = $iter_max reached!"

end
Related