PreviousUpNext

10.11.2  Package Syntax

The simplest syntax for defining a package looks like:

    package binary_tree {

        Binary_Tree
            = LEAF
            | NODE { key:   Float,

                     left_kid:  Binary_Tree,
                     right_kid: Binary_Tree
                   }
            ;

        fun print_tree LEAF
                =>
                ();

            print_tree (NODE { key, left_kid, right_kid })
                =>
                {   print "(";
                    print_tree left_kid;
                    printf "%2.1f" key;
                    print_tree right_kid;
                    print ")";
                };
        end;
    };

Here the reserved word package introduces the package name binary_tree, while the curly braces delimit the scope of the package, which in this case exports one type, Binary_Tree and one function, print_tree.

Other packages may then make such references as

    binary_tree::Binary_Tree
    binary_tree::LEAF
    binary_tree::NODE
    binary_tree::print_tree

in the course of making use of the functionality so implemented.

Since binary_tree is a fairly long name, another package might well define a shorter synonym for local use by doing

    package tree = binary_tree;

after which it could instead refer to

    tree::Binary_Tree
    tree::LEAF
    tree::NODE
    tree::print_tree

Alternatively, if it is a small package working heavily with binary trees, it might simply import everything from package binary_tree wholesale into its own namespace by doing

    include package   binary_tree;

after which it could simply refer to

    Binary_Tree
    LEAF
    NODE
    print_tree

just as though they had been locally defined.


Comments and suggestions to: bugs@mythryl.org

PreviousUpNext