A function argument is optional if it is not referenced when the function is invoked.
func1(x, y)
{
if (x < 0)
return(y);
else
return(x);
}
func1(1) returns: 1
func1(-1) returns: y: Unknown Variable
Optional arguments can be tested using the argc variable:
optfun(a, b)
{
/* default b and/or a if not specified */
if (argc < 2)
{
if (argc < 1) a = 1;
b = 10;
}
return(a * b);
}
optfun(2, 3) returns: 6
optfun(2) returns: 20
optfun() returns: 10
Arguments can also be assigned default values directly in the argument list:
optfun2(a = 1, b = 10)
{
return(a * b);
}
optfun2(2, 3) returns: 6
optfun2(2) returns: 20
optfun2() returns: 10
The default value of an argument can be any valid value. Default values can depend on arguments that occur earlier in the argument list.
optfun3(a = 10, b = 1..3, c = a * b)
{
return(a + b + c);
}
optfun3() returns: {21, 32, 43}
optfun3(1) returns: {3, 5, 7}
optfun3(1, 2) returns: 5
Specifying default argument values in the SPL argument list can greatly simplify the initialization steps of an SPL function.
SPL functions allow
arguments to be supplied either positionally or by
name. Named arguments use the name:value syntax
and may appear in any order.
fun2(a = 1, b = 2)
{
return(a / b);
}
The function can be called using positional arguments:
x = fun2(10, 2);
Or by explicitly naming the arguments:
y = fun2(b:2, a:10);
Both x
and y evaluate to 5.
In the first call, arguments are assigned by position. In the second call,
arguments are matched by name, so the order does not matter.
If a function defines default values for its parameters, only the arguments that override those defaults need to be specified.
u = fun2(2);
v = fun2(b:2);
Here u == 2, and v == 0.5. In the first case, a is set to 2 and b is set to its default value 1. In the second case, b is explicitly set to 2 and a is set to its default value of 1.
Named arguments can make function calls clearer, especially when a function has many parameters or when only a few need to be changed.
The outargc variable indicates how many variables will be assigned by a function. For example:
outtest(x)
{
if (outargc > 1)
{
return(x, x * x);
}
else
{
return(x);
}
}
a = outtest(1..100)
(a, b) = outtest(1..100)
In both assignments, a is set to the series 1..100, however in the first example, the squared series x*x is not calculated since outargc is 1.
outargc allows multi-value functions to be more efficient by testing whether a particular return value even needs to be calculated.