Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

local scopes in Julia

I understand that the for loops are now local in Julia. But there is something I do not understand. Please consider the following two examples.

Example 1

a = 0
for i = 1:3
   a += 1
end

Example 2

a = [0]
for i = 1:3
   a[1] += 1
end

Example 1 throws an error message, which I understand. But Example 2 works as it is expected. How should I understand this? Arrays are not variables? Can somebody explain this to me?

like image 683
SJ Jun Avatar asked Jun 28 '20 06:06

SJ Jun


People also ask

What is local scope?

Local scope is a characteristic of variables that makes them local (i.e., the variable name is only bound to its value within a scope which is not the global scope).

What is scope of local variable in Ruby?

Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, local, global, instance and class. In addition, Ruby has one constant type. Each variable type is declared by using a special character at the start of the variable name as outlined in the following table.

What is local scope in PHP?

A local scope is a restricted boundary of a variable within which code block it is declared. That block can be a function, class or any conditional span. The variable within this limited local scope is known as the local variable of that specific code block. The following code block shows a PHP function.

How do you declare a global variable in Julia?

For any assignment to a global, Julia will first try to convert it to the appropriate type using convert : julia> global y::Int julia> y = 1.0 1.0 julia> y 1 julia> y = 3.14 ERROR: InexactError: Int64(3.14) Stacktrace: [...]


1 Answers

This question is essentially a duplicate of Julia scoping: why does this function modify a global variable?, where it is discussed in detail that the difference is that a = ... is an assignment operation (changes binding of a variable a) and a[1] = ... is a setindex! operation (changes value contained in a collection). Also see Creating copies in Julia with = operator.

I am not marking it as a duplicate only because in your case the first example fails in REPL under Julia 1.4.2 but will work under Julia 1.5 once it is released, see https://github.com/JuliaLang/julia/blob/v1.5.0-rc1/NEWS.md:

The interactive REPL now uses "soft scope" for top-level expressions: an assignment inside a scope block such as a for loop automatically assigns to a global variable if one has been defined already. This matches the behavior of Julia versions 0.6 and prior, as well as IJulia. Note that this only affects expressions interactively typed or pasted directly into the default REPL (#28789, #33864).

like image 102
Bogumił Kamiński Avatar answered Oct 12 '22 06:10

Bogumił Kamiński