Common Lisp/Advanced topics/Packages
Packages are a facility in Common Lisp to divide the namespace. Packages allow one to isolate all of their function, macro, and variable definitions from the rest of the system. This reduces the number of problems that occur with name collisions, or two people using the same name for different things.
A symbol has the printed form PACKAGE-NAME::SYMBOL-NAME, however, if we are currently in package PACKAGE-NAME, then the printer will just print SYMBOL-NAME. The dynamic variable *PACKAGE* always specifies the current package. When interned, a symbol is interned in the package that *PACKAGE* names, unless the package name is specified via the ‘::’ notation.
A package is defined with DEFPACKAGE. A package may EXPORT any of its symbols in which case they may be designated by PACKAGE-NAME:SYMBOL-NAME, i.e. only one ‘:’. A package may also IMPORT a symbol from any other package. If a symbol is imported that has the same name as a different symbol that was already interned in the package, then an error occurs. You will have to choose one symbol. USE-PACKAGE helps one import the API from a package. The symbols that a package exports and the packages that a package uses may be specified via DEFPACKAGE.
Example: List all Symbols in a Package
editCommon Lisp provides some macros to iterate through the symbols of a package. The two most interesting are: DO-SYMBOLS and DO-EXTERNAL-SYMBOLS. DO-SYMBOLS iterates over the symbols accessible in the package and DO-EXTERNAL-SYMBOLS only iterates over the external symbols (you can see them as the real package API).
To print all exported symbols of a package named "PACKAGE", you can write:
(do-external-symbols (s (find-package "PACKAGE")) (print s))
You can also collect all these symbols in a list by writing:
(let (symbols) (do-external-symbols (s (find-package "PACKAGE")) (push s symbols)) symbols)
Or you can do it with LOOP.
(loop for s being the external-symbols of (find-package "PACKAGE") collect s)
Copyright © 2002-2005 The Common Lisp Cookbook Project http://cl-cookbook.sourceforge.net/