up previous next
define --
define a function
|
Define F(X_1, .., X_n) C EndDefine
Define F(X_1, .., opt X_n) C EndDefine
Define F(...) C EndDefine
return FUNCTION |
1. INTRODUCTION. This command adds the user-defined function
F
to
the library. The function
F
can be called in the following way:
F(E_1,...,E_n)
where the
E_i
's are expressions.
The result of the evaluation of each expression
E_i
is assigned
to the respective formal parameter
X_i
, and the command sequence
C
is executed.
If, during the execution of
C
, a statement
Return E
is
executed, then the result of the evaluation of
E
is the
return-value of the function
F
. If no
Return
command is
executed, or
Return
is executed without argument, then the
return-value is
Null
.
/**/ define square(X)
/**/ return X^2;
/**/ enddefine;
/**/ square(5);
25
|
or a variable number of arguments
/**/ define strange(...) --> all args are in the list ARGV
/**/ if len(ARGV) = 0 then return 1234; endif;
/**/ if len(ARGV) > 4 then return last(ARGV)^2; endif;
/**/ error("Wrong number for arguments for \"strange\"!");
/**/ enddefine;
/**/ strange();
1234
/**/ strange(1, 4, "a", 5, 10);
100
/**/ -- strange(1,2); --> !!! ERROR !!! as expected
|
2. SCOPE. Every variable defined or modified by the command sequence
C
is considered local to the function unless the variable is global
or relative to a
ref
parameter.
See
ref
to learn about passing function arguments
by reference,
i.e. so that the function can change the value of an existing variable.
See
TopLevel
for the use of global variables.
/**/ Define Example_1(L)
/**/ L := L + 5;
/**/ Return L;
/**/ EndDefine;
/**/ L := 0;
/**/ Example_1(L);
5
/**/ L; -- L is unchanged despite the function call.
0
|
3. VARIABLE NUMBER OF PARAMETERS. It is also possible to have
some optional arguments or a variable number of arguments:
-- OPTIONAL ARGUMENTS must be in the last positions
/**/ define deg0(f, opt x)
/**/ if f=0 then return 0; endif;
/**/ if IsDefined(x) then return deg(f,x); endif;
/**/ return deg(f);
/**/ enddefine;
/**/ use P ::= QQ[x,y,z];
/**/ deg0(zero(P));
0
/**/ deg0(x^2+y);
2
/**/ deg0(x^2+y, y);
1
-- VARIABLE number of ARGUMENTS
/**/ Define MySum(...) --> arguments are in the LIST "ARGV"
/**/ If len(ARGV) = 0 Then Return 12345; EndIf;
/**/ ans := 0;
/**/ Foreach N In ARGV Do ans := ans+N; EndForeach;
/**/ Return ans;
/**/ EndDefine;
/**/ MySum(1,2,3,4,5);
15
/**/ MySum();
12345
|
The old statement,
Help S;
is OBSOLETE!