Confusing about a very simple program - parameter-passing

I have this question :
The program is very simple :
sub(b, a)
<=>
sub(x, y)
x = x + y = 3 + 2 = 5
y = x + y = 5 + 2 = 7
<=>
b = 5
a = 7
therefore d is the right answer
but the given answer is c(a = 7, b =3 )
Why? What am i missing here ?
Any help is greatly appreciated !

Note that "the parameter x is called by value, and the parameter y is called by reference".
So b is passed by value, which means that the x inside sub is just a local variable - it's not pointing to the same location as b.
Therefore, the changes made to x inside sub do not affect the variable b that was passed in.
Contrast with y which is passed by reference, which means that y and a are actually the same variable, so changes to y inside sub are reflected in a outside of it.

The trick here is the difference between pass-by-value and pass-by-reference. As the prompt notes x is passed (or "called") by value. This means that when you pass b to sub as x, x contains only the literal value of b. What this means from a practical standpoint is that any changes made to x in sub will NOT affect b back in the main program.
On the other hand, since y is passed by reference, when you pass a to sub as y, y is really a reference to the variable a (y "points" to a). This means that if you make changes to y in sub those changes affect a back in the main program.
If the above is confusing to you, think of it this way: if a variable is passed by value to a function, you can replace the parameter name (x) with the value of the argument (3). If a variable is passed by reference to a function, you can think of it as replacing the parameter name (y) with the variable name of the argument (a).
With that in mind, let's revisit the question:
a = 2;
b = 3;
sub(b, a);
----------
x = x + y
(in this line x represents the value of b, which is 3, so the value of x (but not b) is now 5)
y = x + y
(in this line y represents the actual variable a, whose value is 3. When we add x to y, however, it actually changes a. Therefore, the value of both y and a after this line is 7)
return;
So as you can see, b cannot be changed in the original function, so its final value can only be 3. a however can be changed, and due to operations in sub now has a value of 7.
I hope this clears up any confusion you were facing with this problem.

Related

OCaml meaning of "in"

Lets assume the following function
val foo : int -> int -> bool -> int
let foo x y b =
let x,y = if x > y then y,x else x,y in
let rec loop x y b =
if x >= then x
else if b then loop (x+1) y (not b)
else loop x (y-1) (not b)
in
loop x y b
I still don't quite understand the concept of the "in".
Does the line mean "let x,y = ... in" that it is executed immediately or only when you "Call" it? And when i dont need to call it why do i need the last line loop x y b?
Thanks in advance :)
in is just part of the OCaml syntax - let PATTERN = EXPR1 in EXPR2 is an expression which binds the result of EXPR1 to PATTERN and then evaluates EXPR2 with the new bindings present. In some languages like F# and Haskell, you don't (always) need in - it's inferred from the indentation. OCaml syntax is indentation insensitive which requires it to have an explicit in.
Does the line mean "let x,y = ... in" that it is executed immediately or only when you "Call" it?
It's evaluated immediately.
And when i dont need to call it why do i need the last line loop x y b?
In this code, the previous line defines a function named loop with 3 arguments, and then later you call the function with the arguments x y b.

Applying a function to multiple rows of a data frame where the row is an argument in the function in R

Apologies for the rather long name, but I wanted to be specific. I am rather new to R and coding so please go easy on me.
I have a function as follows:
myfun = function(x, y, g) {return(1 / (1 + exp(y*g%*%x)))}
where x is any data frame with n rows and d columns, y is a scalar and integer, and g is a vector of length d (i.e. same as x). I want to run this function for each row of x without using loops.
I have tried various function in the apply family similar to the code below:
apply(x = a, 1, myfun(y = 1, g = b)
where a is a 3x3 data frame and b is a vector 3 elements long. The above code gives an error that I am missing an argument from myfun, but I am obviously clueless on what to try.
Thanks for any help in advance!
Edit: My actual data frame is huge, sparse, and not very straight forward (I think), so I will include an example data frame and other variables:
a = data.frame(c1 = seq(1,3,1), c2 = seq(4,6,1), c3 = seq(7,9,1))
b = c(1,2,3)
c = 1
Also, I think I may have not clearly stated an important piece of information. I want to actually do a summation of myfun over all the rows and values of b, so I actually want the following:
answer = myfun(a[1,], c, b[1]) + myfun(a[2,], c, b[2]) + myfun(a[3,], c, b[3])
In other words, a[1,] should be applied to myfun with b[1] as they are grouped together. I also made an edit to the function above because I forgot to include return(). Hopefully, this makes things more clear. Apologies for the confusion!

Call by value, name/reference, need in ML

I am studying for a final, and I have a practice problem here.
The question asks for the result of
val y = ref 1;
fun f x = (!y) + (x + x);
(f (y := (!y)+1; !y)) + (!y);
under the following parameter passing techniques:
Call by value
Call by name
Call by need.
It seems to me that for call by value, the answer is 8.
However, I believe the answer for call by name is also 8, but I would expect it to be different. The reason I think it is 8:
y := (!y)+1 derefs y as 1, adds 1, and then sets y to 2
!y in line 3 serves as the argument to f, and since it is being dereferenced it is
passed as a value rather than as a reference (this may be where I am
going wrong?)
The function call returns 6, but does not set y as y was passed in as a value from the previous step
6 is added to the dereferenced value of y, which is 2.
This returns 8
Is this the correct answer, and if not, can someone please point out where I have gone wrong? Also, can someone explain to me how call by need would work in this situation also?
Many thanks.
I found out how it works:
(y := (!y)+1; !y) is the parameter passed to f.
f then looks like:
fun f x = (!y) + ((y:= (!y)+1; !y) + (y:= (!y)+1; !y));
so this ends up being 1+2+3, and the final step + (!y) adds 3 as this is the current value of y, giving 9.
Thanks for pointing out that I was still doing call-by-value.

Error plotting a function of 2 variables

I am trying to plot the function
f(x, y) = (x – 3).^2 – (y – 2).^2.
x is a vector from 2 to 4, and y is a vector from 1 to 3, both with increments of 0.2. However, I am getting the error:
"Subscript indices must either be real positive integers or logicals".
What do I do to fix this error?
I (think) I see what you are trying to achieve. You are writing your syntax like a mathematical function definition. Matlab is interpreting f as a 2-dimensional data type and trying to assign the value of the expression to data indexed at x,y. The values of x and y are not integers, so Matlab complains.
If you want to plot the output of the function (we'll call it z) as a function of x and y, you need to define the function quite differently . . .
f = #(x,y)(x-3).^2 - (y-2).^2;
x=2:.2:4;
y=1:.2:3;
z = f( repmat(x(:)',numel(y),1) , repmat(y(:),1,numel(x) ) );
surf(x,y,z);
xlabel('X'); ylabel('Y'); zlabel('Z');
This will give you an output like this . . .
The f = #(x,y) part of the first line states you want to define a function called f taking variables x and y. The rest of the line is the definition of that function.
If you want to plot z as a function of both x and y, then you need to supply all possible combinations in your range. This is what the line containing the repmat commands is for.
EDIT
There is a neat Matlab function meshgrid that can replace the repmat version of the script as suggested by #bas (welcome bas, please scroll to bas' answer and +1 it!) ...
f = #(x,y)(x-3).^2 - (y-2).^2;
x=2:.2:4;
y=1:.2:3;
[X,Y] = meshgrid(x,y);
surf(x,y,f(X,Y));
xlabel('x'); ylabel('y'); zlabel('z');
I typically use the MESHGRID function. Like so:
x = 2:0.2:4;
y = 1:0.2:3;
[X,Y] = meshgrid(x,y);
F = (X-3).^2-(Y-2).^2;
surf(x,y,F);
xlabel('x');ylabel('y');zlabel('f')
This is identical to the answer by #learnvst. it just does the repmat-ing for you.
Your problem is that the function you are using uses integers, and you are trying to assign a double to it. Integers cannot have decimal places. To fix this, you can make it to where it increases in increments of 1, instead of 0.2

Dynamic Scoping - Deep Binding vs Shallow Binding

I've been trying to get my head around shallow binding and deep binding, wikipedia doesn't do a good job of explaining it properly. Say I have the following code, what would the output be if the language uses dynamic scoping with
a) deep binding
b) shallow binding?
x: integer := 1
y: integer := 2
procedure add
x := x + y
procedure second(P:procedure)
x:integer := 2
P()
procedure first
y:integer := 3
second(add)
----main starts here---
first()
write_integer(x)
Deep binding binds the environment at the time the procedure is passed as an argument
Shallow binding binds the environment at the time the procedure is actually called
So for dynamic scoping with deep binding when add is passed into a second
the environment is x = 1, y = 3 and the x is the global x so it writes 4 into the global x, which is the one picked up by the write_integer.
Shallow binding just traverses up until it finds the nearest variable that corresponds to the name so the answer would be 1.
a) In deep binding we deal with the environment of add, in which x refers to the global x and y refers to the y local to first (the last executed function which has a declaration of y)
x (global) = x (global) + y (local) : x = 1 + 3 = 4
b) In shallow binding, we deal with the environment of second, in which x refers to the x local to second and y refers to the y local to first (the last executed function which has a declaration of y)
x (local) = x (local) + y (local) : x = 2 + 3 = 5
BUT : write_integer(x) outputs the global x which is equal to 1
Finally
a) 4
b) 1
shallow binding should be 5.
definations:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=15&lngWId=6