[Up] [Contents] [Index] [Summary]

4.4 Importing Predicates into a Module

As explained before, in the predicate based approach adapted by SWI-Prolog, each module has it's own predicate space. In SWI-Prolog, a module initially is completely empty. Predicates can be added to a module by loading a module file as demonstrated in the previous section, using assert or by importing them from another module.

Two mechanisms for importing predicates explicitly from another module exist. The use_module/[1,2] predicates load a module file and import (part of the) public predicates of the file. The import/1 predicate imports any predicate from any module.

use_module(+File)
Load the file(s) specified with File just like ensure_loaded/1. The files should all be module files. All exported predicates from the loaded files are imported into the context module. The difference between this predicate and ensure_loaded/1 becomes apparent if the file is already loaded into another module. In this case ensure_loaded/1 does nothing; use_module will import all public predicates of the module into the current context module.

use_module(+File, +ImportList)
Load the file specified with File (only one file is accepted). File should be a module file. ImportList is a list of name/arity pairs specifying the predicates that should be imported from the loaded module. If a predicate is specified that is not exported from the loaded module a warning will be printed. The predicate will nevertheless be imported to simplify debugging.

import(+Head)
Import predicate Head into the current context module. Head should specify the source module using the <module>:<term> construct. Note that predicates are normally imported using one of the directives use_module/[1,2]. import/1 is meant for handling imports into dynamically created modules.

It would be rather inconvenient to have to import each predicate referred to by the module, including the system predicates. For this reason each module is assigned a default module. All predicates in the default module are available without extra declarations. Their definition however can be overruled in the local module. This schedule is implemented by the exception handling mechanism of SWI-Prolog: if an undefined predicate exception is raised for a predicate in some module, the exception handler first tries to import the predicate from the module's default module. On success, normal execution is resumed.


Section Index