up previous next
2.2.16 First Functions
CoCoA's gamut of functions can be easily extended with user-defined functions. Longer functions are usually cut-and-pasted from a text editor into a CoCoA session. If the functions are to be used repeatedly, they can be saved in a separate text file and read into a CoCoA session with the Source command. The usual way to define a function is with the syntax:
   Define < FunctionName >(< argument list >) < Commands > EndDefine;
NOTE: Variables defined within a function are usually local to that function and disappear after the function returns. Normally, the only variables accessible within a function are the function's arguments and local variables. (For the exceptions, see the section of the manual entitled Global Memory.)

Example
  Define Square(X)   -- a simple function
    Return X^2;
  EndDefine;
  Square(3);
9
-------------------------------
  Define IsPrime(X)  -- a more complicated function
    If Type(X) <> INT Then Return Error("Expected INT") EndIf;
    I := 2;
    While I^2 <= X Do
      If Mod(X, I) = 0 Then Return False EndIf;
      I := I+1;
    EndWhile;
    Return TRUE;
  EndDefine; -- end of function definition
  IsPrime(4);
FALSE
-------------------------------
  Define Test(A, B)  -- a function with two arguments
    Sum := A+B;
    Prod := A*B;
    PrintLn "The sum of ", A," and ", B," is ", Sum,".";
    Print "The product of ", A," and ", B," is ", Prod,".";
  EndDefine;
  Test(3,5);
The sum of 3 and 5 is 8.
The product of 3 and 5 is 15.
-------------------------------