Why this following code prints x values as 1 and y values as 10 - node.js

var y;
function modify(x) {
var z = 5;
x += 2;
y += x + z
}
var x = 1,
y = 2,
z = 3
modify(x)
Above snippet result is x=1,y=10,z=3 Please explain this code. Thanks in advance

In the modify function, "x" is in the scope of modify, and is not going to use the x in the global scope. In addition, primitive types, such as numbers, are passed by value instead of reference. Therefore, x is always going to remain 1.
Also in the modify function, you are declaring a new variable of z in the scope of the modify function, so just like x, z is going to remain as 3.
Since y isn't declared in the function, it's going to use the global scope, so that's the only one that's going to change. In this case it's 2 + ((1 + 2) + 5), which is how you get 10.

Related

Global variable wrapped in a function

I'm learning Julia as part of my PhD in economics but I've come across an issue that doesn't make sense to me. I'm trying to write a function that performs some preliminary calculations then conducts a while loop and returns some value. I want to do this without using global variables. For some reason I can't get it to work. See the minimal working example below which returns a undefined variable error for z.
function test_me(n)
x = 2 + 1
y = x - 1
i = y
while i <= n
println(i)
i += 1
z = 3*i
end
return z
end
I can solve the problem easily by making z a global variable.
function test_me2(n)
x = 2 + 1
y = x - 1
i = y
while i <= n
println(i)
i += 1
global z = 3*i
end
return z
end
I'm confused as I was under the impression that by wrapping the while loop in a function implies that z is in the local scope and the global declaration is unnecessary. For example the code below works as expected.
function test_me3(n)
i = 1
while i <= n
println(i)
i += 1
z = 3*i
end
return z
end
I apologise if this issue is trivial. Any help is really appreciated. Thanks.
Just put a local z or alternatively a z = 0 before your while loop such that z is defined in the loop.
For more on this check out the scoping page of the Julia documentation and the local keyword docstring.
See also this question/answer: In Julia, is there a way to pass a variable from a local scope to the enclosing local scope?

A small question about the change() function,how to understand the process about it?

I am learning the basic usage of python,and I'm confusing about how the variable runs in a practice question. Here are the code below:
x = 1
def change(a):
a = x + 1
print(x)
change(x)
x = 1
def change(a)
x = x + 1
print(x)
change(x)
This is how I think the process:
in the first code:change(x) means: x = x + 1 - print (x) - output:2
but in fact the result is 1.So the real process is: x(symbol in the function) = x(global variable) + 1, print(x), this x is the global variable.
is that right?
in the second code,I think still the output should be 2,but it shows me that UnboundLocalError: local variable 'x' referenced before assignment
so in the python,we can't use function to change the global variable?
Inside a function, you can read global variables but you cannot modify them without explicitly declaring them as global like this:
x = 1
def change(a):
global x # <- this is required since you're assigning a new value to x
x = x + 1
print(x)
change(x)
In the first case, with a = x + 1, the global declaration is not required since you're only reading the value of x, not modifying it. Also, the output is 1 in the first case, since you're printing x not a.

What is the correct syntax in metaprogramming assignment in Julia?

I want x to take the value 4; why doesn't this work? What would the correct syntax be?
x=3
y=5
z=[:x; :y]
:(z[1])=4
The equivalent of &x in C++ in Julia, is to use a Ref.
x = Ref(1)
x[] # get value of x, it's 1
x[] = 2 # set value of x to 2
What you want to do is
x = Ref(3)
y = Ref(5)
z = [x, y]
z[1][] = 4
For more information, see the section on Ref in the documentation.

Variable scope python3

I have
def func1(var):
if var == 0:
return
else
var = var - 1
func1(var)
PROPOSAL = 1
def func2():
func1(PROPOSAL)
print(PROPOSAL)
In the recursive calls in func1, will the variable PROPOSAL be decremented, meaning the print statement will print 0?
Edit: I should've asked, why doesn't it do this?
No, the PROPOSAL global variable will not be decremented by your code. This isn't really because of scope, but because of how Python passes arguments.
When you call a function that takes an argument, the value of the argument you pass is bound to a parameter name, just like an assignment to a variable. If the value is mutable, an in-place modification through one name will be visible through the other name, but if the variable is immutable (as ints are in Python), you'll never see a change to one variable effect another.
Here's an example that shows functions and regular assignment working the same way:
x = 1
y = x # binds the y to the same value as x
y += 1 # modify y (which will rebind it, since integers are immutable)
print(x, y) # prints "1 2"
def func(z): # z is a local variable in func
z += 1
print(x, z)
func(x) # also prints "1 2", for exactly the same reasons as the code above
X = [1]
Y = X # again, binds Y to the same list as X
Y.append(2) # this time, we modify the list in place (without rebinding)
print(X, Y) # prints "[1, 2] [1, 2]", since both names still refer to the same list
def FUNC(Z):
Z.append(3):
print(X, Z)
FUNC(X) # prints "[1, 2, 3] [1, 2, 3]"
Of course, rebinding a variable that referred to a mutable value will also cause the change not to be reflected in other references to the original value. For instance, you replaced the append() calls in the second part of the code with Y = Y + [2] and Z = Z + [3], the original X list would not be changed, since those assignment statements rebind Y and Z rather than modifying the original values in place.
The "augmented assignment" operators like +=, -=, and *= are a bit tricky. They will first try to do an in-place modification if the value on the left side supports it (and many mutable types do). If the value doesn't support in-place modification of that kind (for instance, because it's an immutable object, or because the specific operator is not allowed), it will fall back on using the regular + operator to create a new value instead (if that fails too it will raise an exception).
func1(PROPOSAL) will return NONE and it won't affect the global PROPOSAL variable because you don't assign that return value to PROPOSAL.
func2() just calls func1() and then prints the PROPOSAL variable that wasn't changed it that scope just in func1(PROPOSAL)

number as an object, or storing properties of a number

in designing an algebraic equation modelling system, I had this dilemma: we cannot associate properties to a number, if I turn the number to a table with a field "value" for example, I can overload arithmetic operators, but not the logic operator since that only works when both operands have same metatable, while my users will compare "x" with numbers frequently.
For example, here is a minimal equation solver system:
x = 0
y = 0
eq1 = {function() return 2*x + 3*y end, rhs = 1 }
eq2 = {function() return 3*x + 2*y end, rhs = 2 }
p = {{x,y},{eq1, eq2}}
solve(p)
The "solve()" will process table "p" to get all coefficients of the equation system and rhs. However, it is essential, a user can associate properties to "x" and "y", for example, lower bound, upper bound. I tries using table,
x = {val=0, lb=0, ub=3}
y = {val=1,lb=3,ub=5}
....
and write metamethods for "x" and "y" such that arithmetic operating will act on x.val and y.val. However, in a scripting environment, we also need to compare "x" with numbers, i.e., "if x>0 then ...". And I stuck here. An ugly solution is to ask users to use x.val, y.val everywhere in modelling the equation and scripting. Does anyone here has similar need to associate properties to a number, and the number can still be used in arithmetic/logic operations?
Something like this could work:
x = {val = 10}
mt = {}
mt.__lt = function (op1, op2)
if (type(op1) == 'table') then a = op1.val else a = op1 end
if (type(op2) == 'table') then b = op2.val else b = op2 end
return a < b
end
setmetatable(x, mt)
print(x < 5) -- prints false
print(x < 15) -- prints true
print(x < x) -- prints false
print(5 < x) -- prints true
Of course, you would write similar methods for the other operators (__add, __mul, __eq and so on).
If you'd rather not use type()/reflection, you can use an even dirtier trick that takes advantage of the fact that unary minus is well, unary:
mt = {}
mt.__unm = function (num) return -(num.val) end
mt.__lt = function (a, b) return -(-a) < -(-b) end
This is rather simple if you have access to the debug library, do you?
debug.setmetatable(0, meta)
meta will be the metatable of ALL numbers. This will solve your logical overloading problem.
However if you would prefer assigning properties to numbers, there is a way you could do this, I wrote a quick example on how one would do so:
local number_props = {
{val="hi"},
{val="hi2"}
}
debug.setmetatable(0,{__index=function(self,k)return number_props[self][k]end})
print((1).val, (2).val)

Resources