nested loop with same index name - swift

In the below nested loop:
for i in 0..<2 {
print(i)
for i in 0..<2 {
print(i)
}
}
the output should be:
001
However it produces:
001101
I can't find anything referring to the scope of the index (i) in apple documentations. I would appreciate any reference or explanation from an official source.

When you define a loop for X in ..., you're defining scope that exists during each iteration and a constant that exists in that scope. I can't find explicit documentation of scope except for in the case of do {} but the documentation does assume scope is created and destroyed in loops when speaking of things like the guard declaration. In practice, this is what the scope for i in a single loop looks like.
// Scope that i doesn't exist in.
for i in 1..<2 {
// Scope that i exists in.
}
// Scope that i doesn't exist in.
When defining a nested scope (which your inner for loop is), you have the ability to redefine variables and constants. This is what happens when you define i in the loop declaration. Inside the inner loop, the compiler looks outward through the scope for definitions.
In the case of i, it looks in the inner loop and finds it. In the case of print, the identifier used, it looks in the inner loop, the outer loop, any containing fiction, then class, then module, then imported modules until it finds Swift.print.

Loop variables are scoped to the body of the loop. Swift allows shadowing of local variables, so the nested loop gets a brand-new variable called "i", and loses access to variable "i" from its outer scope.

Related

local object in lua class constructor?

I'm new to Lua "classes" (metatables) and I have a doubt.
In the following constructor code that I wrote, I declared the variable obj as local. But in most examples on the web, this variable is just assigned to without a local declaration. So in my understanding, it becomes a global variable (not efficient from what I understood). But is there a reason for that?
A = {}
A.__index = A
function A:new(obj_init)
local obj = obj_init or {val = 0}
setmetatable(obj, A)
return obj
end
I also noticed that members of the class can be accessed directly, even from another Lua module:
x = A:new{val = 2}
print(x.val)
But is there a way to make val a private member? Maybe also using local?
First, let's look at what these examples you found might have looked like.
Parameters: Implicit locals
function A:new(obj)
obj = obj or {val = 0}
...
end
in this snippet, obj is a local variable. This is because all function parameters in Lua are local variables. We may rewrite the function as follows to highlight this:
function A:new(...)
local obj = ...
obj = obj or {val = 0}
end
I assume this is what you saw e.g. in the PIL. You probably renamed the parameter to obj_init, losing the implicit local declaration of obj.
Global assignment
If you happened to consume particularly bad resources, you might have seen the following:
function A:new(obj_init)
obj = obj_init or {val = 0}
...
end
in this snippet, obj is indeed a global variable. This is very bad for multiple reasons:
Efficiency: You are right - excepting pathological cases, global variables are always slower than local variables as global variables are entries in the (hash part of the) _G table whereas locals are stored in fast registers of the Lua VM.
Code quality: Global pollution: This constructor now has a side effect: It modifies the global variable obj and expects it to not be modified during its execution. This might lead to this function overwriting a global variable obj and, even worse, you may not yield from a coroutine in the constructor now, because you're dependent on a global state which may not be altered.
Private members
The typical way to implement private table fields in Lua is by convention: You may prefix the field names with an underscore to indicate that these fields may not be modified from outside. Of course programmers are free to circumvent this.
Otherwise, the concept of "private" variables doesn't mesh too well with the scripting language nature of Lua; you can shoehorn full-fledged OOP onto Lua using metatables, but it will be neither idiomatic nor efficient.
Upvalues
The most idiomatic way to implement private members in Lua is to have them be upvalues of closures ("accessors"):
A = {}
A.__index = A
function A:new(obj_init)
local obj = {} -- empty object: only member is private
local val = obj.val
-- note: this does not need `self`, thus no `:` is used;
-- for setters you might want to discard `self` for consistency
function obj.getVal()
return val
end
setmetatable(obj, A)
return obj
end
x = A:new{val = 2}
print(x.getVal())
-- val can not be set from outside (excepting the debug library);
-- it is "private" and only accessible through the getter method
The downside is that all functions accessing your private members will have to be instantiated with each object creation.
Note that even upvalues aren't fully "private" as they may be accessed through the debug library.
debug library workarounds
The debug library allows you to inspect the stack. This allows you to tell which method triggered your __index metamethod. You could thus return different values to different callers. This may be nice for a proof-of-concept to showcase Lua's metaprogramming capabilities, but should not be done in practice as it is very inefficient and hacky.

Does global variable used in a function need to be defined before the def block?

I must admit that I didn't expect the following code could work (code sample from a collegue of mine):
def foo():
li.append(3)
li = [1, 2]
foo()
print(li) # gives [1, 2, 3]
My questions are:
why is 'global li' not needed in the 'def foo()'?
why is 'li = [1, 2]' not needed to be put before the 'def foo()'?
ps. Python 3.6.1 is used for the listed code sample.
Global keyword is a keyword that allows a user to modify a variable outside of the current scope.
Rules of global keyword:
If a variable is assigned a value anywhere within the function’s
body, it’s assumed to be a local unless explicitly declared as
global.
Variables that are only referenced inside a function are
implicitly global.
We Use global keyword to use a global variable inside a
function.
There is no need to use global keyword outside a function.
Your code , you are not changing or assigning a 'li' value
2.Here list is defined before foo() is called, so it working fine.suppose if you call foo() before li is defined, it will throw a error like NameError: name 'li' is not defined
Since the list is defined before foo() is called, hence there is no error.
global keyword is only required when we want to do assignment or change the global variable. Accessing the methods or printing the variable does not require the global keyword

ES6 modules - why can I use a const before it is declared?

I've tried searching for an explanation on this exact scenario but couldn't find anything. I have a module that looks like the following (simplified):
export default function(name) {
return map[name];
}
const map = {
'a': 'b',
'b': 'c'
};
Clearly the const definition above is hoisted but it should be undefined when being used in the function. I'm trying to find an exact explanation for why this function works when imported and used. Shouldn't a reference error be thrown? The only thing I can think of is that the entire module is loaded prior to when this function is called, but how exactly does that happen or where is this specific behavior explained? Any information would be really appreciated.
JS uses lexical scoping, meaning that a scope is defined as part of the nested structure of the code. Anything referencing the name of a variable anywhere in that scope can attempt to access the value. What the actual value is depends on when the value is initialized, which is a runtime property of the code.
When people talk about hoisting in JS generally it is not super clear which of these things they are describing. In JS, because scopes are lexically-based, the existence of a given variable is hoisted, in that it always exists within that scope.
The actual initialization of a variable in a scope depends on the way the variable is declared.
function foo(){} declarations have their initialization hoisted, so the variable foo will always be available in the body of the function, even if the declaration comes later. e.g.
foo();
function foo(){}
is perfectly valid valid.
var foo = 4; hoists initialization, but the value is initialized to undefined until the declaration has executed, e.g.
foo; // undefined
var foo = 4;
foo; // 4
let/const performs initialization only when executed, and attempts to access uninitialized variables will throw an exception.
foo; // would throw because it is not initialized yet
let foo = 4;
foo; // 4
So taking those together, the behavior of variables is only determined at runtime. For your code example, it depends on when the function is called. Since let foo = 4; only initialized foo when it runs, if the function were called first, it would fail, and if the function were called after, it would work.
function log(){
console.log(foo);
}
log(); // would throw because foo has not been initialized
let foo = 4;
log(); // would log 4
This behavior of delayed initialization for let and const is commonly referred to as the "temporal dead zone".
At the end of the day, as long as the variable has been initialized and has the value you care about by the time you access it, your code is fine. Whether you have access to the variable in the first place only depends on the nesting of your code.
The call can only be made (outside of this module) after the whole module you provided is executed (which means that map is already initialized by the time the function is called)
This observation is based on the fact that when you import a module, all of the code inside it will be executed.
To call the function, one would have to import the module you provided.
See Does ES6 module importing execute the code inside the imported file? for when code executes on import.

How does closure store references to constants or values

The description comes from the swift office document
Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables.
I don't fully understand the store references part. Does it means It creates some sort of "Pointer" to a variable? If the value changed the "de-referenced pointer" also changed to the new value. I think Swift has no pointer concept. I borrowed it to express my understandings.
Would be very nice that someone can provide a simple code lines to explain how the closure stores reference to the constants/variables.
Does it means It creates some sort of "Pointer" to a variable? If the
value changed the "de-referenced pointer" also changed to the new
value.
Yes.
I think Swift has no pointer concept.
It most certainly does, in the (implicit) form of reference types (classes), and the (explicit) form of UnsafePointer
Here's an example of a variable being captured in a closure. This all happens to be single threaded, but you could have this closure be dispatched by grand central dispatch. x is captured so that it exists for the entire life of the closure, even if the closure exists after x's declaring scope (f()) exits.
func f() {
var x = 0 //captured variable
_ = {
x = 5 //captures x from parent scope, and modifies it
}()
print(x) //prints 5, as x was modified by the closure
}
f()
I wrote another answer that explains the relationships between functions, closures, and other terms. It's worth reading, IMO.

With Scala closures, when do captured variables start to live on the JVM heap?

Related question:
Scala closures compared to Java innerclasses -> final VS var
I wonder when do Scala makes the variables captured into a closure live on the heap instead of the stack. I'm reading the Scala book of Martin Odersky but for now i didn't find this information. Can someone explain what's behind the hood?
An anonymous function (and actually, any function) in scala is actually an object (an instance of Function*). When it is instantiated, the capture of vals is done by copying the vals into internal fields of the function object. In the function body (that is, in the function object's apply method) the access to the captured vals is done by accessing these fields.
The capture of vars is similar, except that the compiler has to add a level of indirection: the var value is accessed through some hidden mutable holder (simply an object with a mutable field pointing to the current value of the var) and this is this holder that is copied into the function object. When writing into the var (either by local code or by the function object), it is the holder's field which is written. This mechanism ensures that the local code and function's code manipulate the same data, and both see each other's modifications.
So the answer is that a captured vals and a captured var both always live on the heap (whether directly as a field of the function object, or as a field of some wrapper object)
I don't know the insides of the compiler, but here is how it can be done. For each local variable, the compiler maintains a flag initialized to false. Whenever the variable is used, the compiler checks whether it is being used inside a class or closure that doesn't contain the variable's declaration; if so the flag is set to true. At the end of the variable's scope, if the flag is still false, the variable can live on the stack. Otherwise it must live on the heap.