September 21, 2014
A function with multiple return values
A typical AFL function returns one value. For example sin( x ) returns sine value of argument x. Sometimes however it is useful and/or required to return more than one value from the function.
Returning multiple values is possible only via arguments passed by reference, but trouble is that in AFL all arguments are passed by value (as in C language). Passing by value means that only value of variable is passed, not the variable itself, so original variable is not modified as shown in the example below:
function Dummy( x )
{
x = 7; // x is treated as function-local
}
//
val = 10;
Dummy( val );
printf( "%g\\n", val ); // will print 10 because 'val' is unaffected by function cal
The behaviour shown above is desirable because we usually want the function to be opaque and do not interfere with what is defined outside of the function except for returning the result of the function.
But what if we actually wanted to write to variables passed as arguments? Well that is possible if we pass the names of the variables as arguments.
// This example shows how to return multiple values
// the idea is to pass the name of the variable instead of
// value
//
function fun_multiple_results( result1name, result2name )
{
VarSet( result1name, 1 ); // setting variable using passed name
VarSet( result2name, 2 );
return;
}
//
// to get multiple values from a function
// we call the function passing NAMES of variables
//
a = 10;
b = 20;
printf("a = %g\\n", a );
printf("b = %g\\n", b );
//
fun_multiple_results( "a", "b" ); // pass the names of variables
//
printf("a = %g\\n", a ); // see new values assigned to variables
printf("b = %g\\n", b )
Of course we can use arguments passed by name for two-way communication – we can use them as both inputs and outputs as shown in the following example that swaps the values of arguments
function Swap( var1name, var2name )
{
temp1 = VarGet( var1name ); // read the value from variable
temp2 = VarGet( var2name );
VarSet( var1name, temp2 ); // write the value to variable
VarSet( var2name, temp1 );
}
// Initial values
x = 5;
y = 37;
//
printf("Before swap x = %g, y = %g\\n", x, y );
//
Swap( "x", "y" ); // pass names of variables
//
printf("After swap x = %g, y = %g\\n", x, y )
The code above will produce output like this:
Before swap x = 5, y = 37
After swap x = 37, y = 5
So it is clear that variables were passed to the function, swapped and returned successfully.
Filed by Tomasz Janeczko at 2:19 pm under AFL
Comments Off on A function with multiple return values