UndefVarError in Julia when evaluating a condition in for-loop

Viewed 87

As a beginner in learning Julia, I am using the code below to get the smallest number in an array;

smallest = 100000
array = [2, 34, 5, 67, 8]

for i in array
    if i < smallest
        smallest = i
    end
end
println(smallest)

I can successfully run the similar code in Python but when I run it in Julia, it throws an error:

ERROR: LoadError: UndefVarError: smallest not defined

Am I missing for-loop syntax in Julia?

1 Answers

The for syntax is correct, but since you've introduced a new scope within the loop, in order to assign to smallest you need to indicate that you are trying to set the global variable smallest:

for i in array
    if i < smallest
        global smallest = i
    end
end

This behavior (needing to indicate global) is going away in Julia 1.5 as people (like here!) have found it tricky when just getting started.

The README of the SoftGlobalScope package has a very gentle introduction to the scoping here. More detailed documentation of scoping in the official manual.

Here's also a similar question and answer on SO, which quoted the manual (linked above) describing why the scoping rules were originally set up this way (ie the pre-1.5 way):

Avoiding changing the value of global variables is considered by many to be a programming best-practice. One reason for this is that remotely changing the state of global variables in other modules should be done with care as it makes the local behavior of the program hard to reason about. This is why the scope blocks that introduce local scope require the global keyword to declare the intent to modify a global variable.

Related