Function.length and variable (...rest) argument length [AS3] - actionscript-3

Is there any way to determine if a (anonymous) function has defined the ...(rest) parameter in ActionScript 3? I know there's the function.length property, but it only counts the explicitly defined arguments.

If you mean checking to see if the function has defined parameters when it was called, then the only way to really do this (to my knowledge) is to prototype the function class and then inside your newly prototyped function class, capture the args array parameter and check to see if it's null. I'm not going to figure out and write all that code for you (lack of time) but here is a nice article that should thoroughly describe this process and have you well on your way.
http://tobyho.com/Modifying_Core_Types_in_ActionScript_3_Using_the_Prototype_Object

There is a way to determine if a function has defined a ...rest parameter, but you can only determine this within the function's body. Outside the function's body, the function has 0 parameters as shown by the first trace output. In reality, this ...rest parameter is an array that only has scope inside the body of the function. However, once you're inside the function body you can test for it, as shown by the second and third trace outputs.
public function Test()
{
trace(doSomething.length);
doSomething(7, 8, 9, 10);
}
public function doSomething(...numbers):void
{
if (numbers.length > 0) trace("Found the parameters!");
for (var i:int = 0; i < numbers.length; i++) trace(numbers[i]);
}
Output: 0
Output: Found the parameters!
Output: 7 8 9 10

Related

function handle to nested function not working for some values of parameter

This function is supposed to return a function handle to the nested function inside, but if the variable x is set to a negative value in the outer function, it doesn't work.
The inner nested function is just a constant function returning the value of the variable x that is set in the outer function.
function t=test(x)
x=-1;
function y=f()
y=x;
endfunction
t=#f;
endfunction
If I try to evaluate the returned function, e.g. test()(3), I get an error about x being undefined. The same happens if x is defined as a vector with at least one negative entry or if x is argument of the function and a negative default value is used for evaluation. But if I instead define it as some nonnegative value
function t=test(x)
x=1;
function y=f()
y=x;
endfunction
t=#f;
endfunction,
then the returned function works just fine. Also if I remove the internal definition of x and give the value for x as an argument to the outer function (negative or not), like
function t=test(x)
function y=f()
y=x;
endfunction
t=#f;
endfunction
and then evaluate e.g. test(-1)(3), the error doesn't occur either. Is this a bug or am misunderstanding how function handles or nested functions work?
The Octave documentation recommends using subfunctions instead of nested functions, but they cannot access the local variables of their parent function and I need the returned function to depend on the input of the function returning it. Any ideas how to go about this?
This is a bug that was tracked here:
https://savannah.gnu.org/bugs/?func=detailitem&item_id=60137
Looks like it was fixed and will be gone in the next release.
Also, to explain the different behavior of negative and positive numbers: I experimented a bit, and no variable that is assigned a computed value is being captured:
function t=tst()
x = [5,3;0,0]; # captured
y = [5,3;0,0+1]; # not captured
z = x + 1; # not captured
function y=f()
endfunction
t=#f;
endfunction
>> functions(tst)
ans =
scalar structure containing the fields:
function = f
type = nested
file =
workspace =
{
[1,1] =
scalar structure containing the fields:
t = #f
x =
5 3
0 0
}
The different behavior of negative and positive numbers are probably caused by the minus sign - before the numbers being treated as a unary operator (uminus).
As of octave version 5.2.0 the nested function handles were not supported at all. I'm going to guess that is the novelty of the version 6.
In octave functions are not variables, the engine compiles\translates them at the moment of reading the file. My guess would be that behavior you are observing is influenced by your current workspace at the time of function loading.
The common way for doing what you are trying to do was to generate the anonymous (lambda) functions:
function t = test1(x=-1)
t = #()x;
end
function t = test2(x=-1)
function s = calc(y,z)
s = y + 2*z;
end
t = #(a=1)calc(a,x);
end
Note that default parameters for the generated function should be stated in lambda definition. Otherwise if you'd call it like test2()() it would not know what to put into a when calling calc(a,x).
If you are trying to create a closure (a function with associated state), octave has limited options for that. In such a case you could have a look at octave's object oriented functionality. Classdef might be useful for quick solutions.

Difference between using higher scope variables and using variables explicitly passed in a function

I mainly code in JS, but I guess this would apply to many languages.
What is the effective difference between a global/higher scope variable in a function versus using a variable passed into the function, and vice versa?
let somevariable = 5 ;
function somefuntion() {
let scopedvariable = 10;
return scopedvariable*myvariable
}
somefunction();
// OR
let myvariable = 5 ;
function somefuntion(somevariable ) {
let scopedvariable = 10;
return scopedvariable *somevariable
}
somefunction(myvariable);
If a function uses a variable from scope that might cause a side effect(function modifying the outer variable) and this is considered bad practice because makes function impure.
Global variables considered bad practice and should only be used if variable is constant. If the variable is constant it is okay, because now function can't modify the scope.

Go Tour #18: understanding pic.Show

I did not understand how the function call pic.Show(Pic) works and what it does.
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
pic := make([][]uint8, dy)
for y := range pic {
pic[y] = make([]uint8, dx)
for x := range pic[y] {
pic[y][x] = uint8(5 * (x + y))
}
}
return pic
}
func main() {
//pic.Show(Pic(40,30)) // doesn't work, but why?
pic.Show(Pic) // works, but why? Where are the values for dx and dy set?
}
There is, starting at line 5, a function, named Pic, and it receives two integer variables (dx, dy). So I think, a correct function call might be Pic(40,30) (with 40 and 30 being the values for dx and dy).
But why does line 17 throw an error? (pic.Show(Pic(40,30)))
Why does line line 18 work? (pic.Show(Pic))
And where do the values of dx and dy come from when line 18 is executed?
I tried to look up http://golang.org/x/tour/pic which redirects me to https://godoc.org/golang.org/x/tour/pic. There I can read, that the function Show is defined this way:
func Show(f func(int, int) [][]uint8)
Which I understand as:
Show is a function that needs one parameter. This parameter is a function that needs two parameters, both of type int, and it has to return a value of type [][]uint8 (a slice of slices of unsigned 8-bit integers). Show itself doesn't return anything.
So, here again, I read that the inner function (the parameter of Show) needs two parameters. But why do I get an error, when I try to provide those parameters? Why is it ok to call the function Pic without parameters? And where do the values for those parameters come from, when Pic is executed?
When you say Pic(40, 30) you call the function Pic and it returns a [][]uint8 (as seen in the function definition). This means that in your commented-out code you pass a [][]uint8 to Show.
When you say Show(Pic) you pass Pic as the parameter, which is a function. That is what Show expects. Pic is of type func(dx, dy int) [][]uint8.
Go allows you to pass functions around as parameters and that is what is happening here.
You are quite right about definition of Show - it is a function which accepts another specific format notion as a parameter.
Pic is such a function matching this criteria - so you pass it to Show successfully.
But when you call Pic(30,40) that means not a function but a result of calling the function with such parameters. So in this case you passs to Show not a function Pic but a slice returned by it [][]uint8. Of course Show can’t accept it.
Your function, Pic, takes two parameters, Show takes one. You're calling Show with a single parameter, which is a function; that function takes two parameters. When you pass a function to another function, the assumption is that the function you're calling (Show) will call the function you passed in (Pic) and provide the necessary parameters when it makes that call.

Scilab not returning variables in variable window

I have created a function that returns the magnitude of a vector.the output is 360x3 dimension matrix. the input is 360x2.
Everything works fine outside the function. how do i get it to work ?
clc
P_dot_ij_om_13= rand(360,2); // 360x2 values of omega in vectors i and j
//P_dot_ij_om_13(:,3)=0;
function [A]=mag_x(A)
//b="P_dot_ijOmag_"+ string(k);
//execstr(b+'=[]'); // declare indexed matrix P_dot_ijOmag_k
//disp(b)
for i=1:1:360
//funcprot(0);
A(i,3)=(A(i,2)^2+A(i,1)^2)^0.5; //calculates magnitude of i and j and adds 3rd column
disp(A(i,3),"vector magnitude")
end
funcprot(1);
return [A] // should return P_dot_ijOmag_k in the variable browser [360x3 dim]
endfunction
mag_x(P_dot_ij_om_13);
//i=1;
//P_dot_ij_om_13(i,3)= (P_dot_ij_om_13(i,2)^2+P_dot_ij_om_13(i,1)^2)^0.5;// example
You never assigned mag_x(P_dot_ij_om_13) to any variable, so the output of this function disappears into nowhere. The variable A is local to this function, it does not exist outside of it.
To have the result of calculation available, assign it to some variable:
res = mag_x(P_dot_ij_om_13)
or A = mag_x(P_dot_ij_om_13) if you want to use the same name outside of the function as was used inside of it.
By the way, the Scilab documentation discourages the use of return, as it leads to confusion. The Scilab / Matlab function syntax is different from the languages in which return specifies the output of a function:
function y = sq(x)
y = x^2
endfunction
disp(sq(3)) // displays 9
No need for return here.

use of "d" in function literal in D3?

I am teaching myself D3 without too much knowledge on syntax / grammar of javascript.
Could anyone explain the use of "d" as a parameter in the following function literal?
I see that it points to the data set being worked on, but want to understand the grammar behind this.
d3.selectAll("circle")
.attr("cy",function (d) { return percent_scale(d.late_percent);})
.attr("cx",function (d) { return time_scale(d.time);})
.attr("r",1);
This is called an anonymous function, which is a function that isn't given a named label. Anonymous functions in Javascript are objects like everything else and this is why you can pass them as parameters into other javascript functions.
In the case of d3, it allows you to pass in a function as the second parameter. As you discovered, this function will be called with the current data element as well as the index of the current data element. If the second parameter is not a function, it can use a value instead.
In your example:
d3.selectAll("circle")
.attr("cy",function (d) { return percent_scale(d.late_percent);})
.attr("cx",function (d) { return time_scale(d.time);})
.attr("r",1);
Both cy and cx are being assigned values based on the return value of an anonymous function call, while r is being assigned a static value. We could rewrite this as:
function setY(d) { return percent_scale(d.late_percent);}
function setX(d) { return time_scale(d.time); }
d3.selectAll("circle")
.attr("cy", setY)
.attr("cx", setX)
.attr("r",1);
Here I've replaced the anonymous function calls with more standard function definitions and specified the name of the function to be called in the d3 call. This works exactly the same as before. Also note that there is nothing magical about d in this case.
function setY(foo) { return percent_scale(foo.late_percent);}
function setX(foo) { return time_scale(foo.time); }
d3.selectAll("circle")
.attr("cy", setY)
.attr("cx", setX)
.attr("r",1);
This code will also do the same thing. Note that I've renamed the parameter from d to foo, but this just changes how you access the parameter within the function. It has no effect outside of the function call. Generally in d3 documentation and tutorials, you'll see d used for the current data element and i used for the index of the current data element. The index is passed in as the second element to the function calls like so:
function setY(d, i) { return percent_scale(d.late_percent);}
function setX(d, i) { return time_scale(d.time); }
d3.selectAll("circle")
.attr("cy", setY)
.attr("cx", setX)
.attr("r",1);
Now specifically in the d3 case:
// Select all of the 'circle' elements (that is <circle>) elements
// in the HTML document and put the associated data into an array
d3.selectAll("circle")
// For each circle element, set the Y position to be the result
// of calling percent_scale on the data element late_percent
.attr("cy",function (d) { return percent_scale(d.late_percent);})
// For each circle element, set the X position to be the result
// of calling time_scale on the data element time
.attr("cx",function (d) { return time_scale(d.time);})
// For each circle element, set the radius to be 1
.attr("r",1);
This is a very common construct in d3. The first step is always to make a selection to define which set of elements you want to modify (this is the .selectAll in this case). After that, you can chain together additional calls (in this case the .attr calls) that actually perform the desired modifications to the elements.
This creates a very powerful method of working with data driven documents (like graphs, charts, etc) without having to track the data elements manually or have to create lots of loops. In fact, you can usually tell you are using d3 incorrectly if you have any loops in your code that deals with modifying elements.
If you don't have much experience with javascript, the tutorials at https://www.dashingd3js.com/ might be helpful for getting started with d3.