previous  next
2.9.2. First Example of a Package
The following is an example of a package.  It could be typed into a
window as-is during a CoCoA session, but we will assume that it is
stored in a file in the CoCoA directory under the name "one.pkg."

>SAMPLE PACKAGE<
Package $contrib/toypackage

Define IsOne(N)
  If N = 1 Then Return TRUE Else Return FALSE EndIf;
EndDefine;

Define Test(N)
  If $.IsOne(N) Then
    Print 'The number 1.'
  Else
    Print 'Not the number 1.'
  EndIf;
EndDefine;

EndPackage; -- of toypackage
=====================================

Below is output from a CoCoA session in which this package was used:

Example

<<'one.pkg';  -- read in the package
Test(1);  -- error here because the function 'Test' is not defined

-------------------------------
ERROR: Unknown operator Test
CONTEXT: Test(1)
-------------------------------
$contrib/toypackage.Test(1); -- this is the name of the function
                                  -- we are looking for
The number 1.
-------------------------------
Alias Toy := $contrib/toypackage;  -- use an alias to save typing
Toy.Test(3);                     
Not the number 1.
-------------------------------
Toy.IsOne(3);
FALSE
-------------------------------

Once the package is read, the user can choose a "substitute prefix"
using the 'Alias' command and in that way avoid conflicts between
functions in various packages and save on typing.

Note one other thing: the function 'IsOne' is used in the definition
of 'Test'.  In that case, it is referred to as '$.IsOne'.  Otherwise,
CoCoA would look for a global function, outside of the package, called
'IsOne'.  Forgetting this kind of reference is a common source of
errors when constructing a package.