JSL also has a function called Function to extend the macro concept with a local context arguments. Suppose that you want to create a function that takes the square root but tolerates negative arguments, returning zero rather than errors. You first specify the local arguments in a list with braces { } and then state the expression directly. You do not need to enclose the expression in Expr because Function stores it as an expression implicitly.
myRoot = Function( {x},
If( x > 0, Sqrt( x ), 0 )
);
a = myRoot( 4 ); // result is a is 2
b = myRoot( -1 ); // result is b is 0
In defined functions, the stored function is not accessible directly, even by the Name Expr command. If you need to access the function expression in your script, you have to create the function within an expr() clause. For example,
makeFunction = Expr(
myRoot = Function( {x},
If( x > 0, Sqrt( x ), 0 )
)
);
d = Substitute( Name Expr( MakeFunction ), Expr( x ), Expr( y ) );
Show( d );
makeFunction;
f1 = Function( {x, y, z}); // all arguments are required
f2 = Function( {x, y=2, z=4}); // x is required, y and z are optional
Function( {x = 1, y}, ... )
ex = Function( {x, y = 2, z = 3},
Return( x + y + z )
);
ex( 1, 4 ); // passes in 1 for x and 4 for y; z will be 3. returns 8.
functionName=Function({arg1, ...}, body);
functionName=Function({arg1, ...}, {Default Local}, body);
For the purposes of creation, the use of Default Local localizes all the names that meet the following qualifications:
•
|
add3 = Function( {a, b, c},
{temp},
temp = a + b;
temp + c;
);
X = add3( 1, 5, 9 );
15
add3 = Function( {a, b, c},
{Default Local},
temp = a + b;
temp + c;
);
X = add3( 1, 5, 9 );
15
In both cases, the variable temp is not a global, or, if it is already a global, remains untouched by evaluating the functions.
Using Default Local in user-defined functions can cause some confusion because it is context-sensitive. That is, the same function may behave differently in different contexts (depending on whether same-named outer variables are in scope) because the reference rules for unqualified names are unchanged when using Default Local. To make a function less context-sensitive, enumerate each and every variable that you want to be local. This reduces the confusion and the potential incorrect use of outer scope variable values.