up previous next
define    --    define a function


Syntax
Define F(X_1, .., X_n)   C   EndDefine
Define F(X_1, .., opt X_n)   C   EndDefine
Define F(...)   C   EndDefine
  return FUNCTION

Description
These commands introduce a user-defined function. F is the name comprising letters, digits or underscore, but must start with a letter. X_1 and so on are the parameters (much like local variables). C is the function body.

(1) INTRODUCTION. These commands assign a user-defined function to the variable F; any previous value F held will be lost! The function F can be called in the following obvious way:
    F(E_1,...,E_n)
where the arguments 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.

Example
/**/  define square(X) --> simple fn with 1 parameter
/**/    return X^2;
/**/  enddefine;

/**/  square(5);
25
(2) SCOPE OF VARIABLES. Every parameter and every variable used in the function body C is local to the function unless the variable is a ref parameter, or the variable was declared global by TopLevel .

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.

Example
/**/  Define Add5(N)  // use helpful name for fn
/**/    N := N + 5;
/**/    Return N;
/**/  EndDefine;

/**/  N := 0;
/**/  Add5(N);
5
/**/  N;  --> N is unchanged despite the function call.
0
(3) VARIABLE NUMBER OF PARAMETERS. It is also possible to have some optional parameters or a variable number of parameters. For optional parameters see also IsDefined .

Example
-- (3a) OPTIONAL ARGUMENTS
--      These must be in the last position(s).

/**/  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

--------------------------------------
-- (3b) VARIABLE NUMBER OF PARAMETERS

/**/   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 CoCoA-4 statement, Help S; is now OBSOLETE!
See Also