@c -*-texinfo-*-
@node Builtin Predicates, Tcp, Overview, Top
@comment  node-name,  next,  previous,  up
@chapter Builtin Predicates 
@menu
* Control::                     Control 
* Loading::                     Loading, Consulting and Compiling 
* IO::                          Input and Output Primitives 
* Arithmetic::                  Arithmetic
* TypePrimitives::              Type Primitives 
* Term Comparison::             Term Comparison 
* ProgramState::                Examining the Program State 
* ExecutionAndError::           Execution and Error Handling 
* ModifyingDatabase::           Modifying the Database 
* Properties::                  Property Management 
* Metalogical::                 Metalogical Primitives 
* GrammarRules::                Grammar Rules 
* ListHandling::                List Handling
* StringsAndAtoms::             String and Atom Handling 
* Threads::                     Threads 
* Parlog::                      Prolog - Parlog Interface 
* Miscellaneous::               Miscellaneous Primitives 
@end menu

@node Control, Loading,  , Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Control 

@table @code
@item @var{+C1}, @var{+C2}
@findex ,/2
This is the conjunction operator.  @var{C1} is evaluated and then @var{C2}
is evaluated.  The conjunction succeeds if and only if both calls succeed.

@item @var{+C1} ; @var{+C2}
@findex ;/2
This is the disjunction operator.  The call succeeds if either @var{C1}
or @var{C2} succeeds. @var{C1} is evaluated first. Only when all
possible evaluation paths for C1 have been explored will backtracking
lead to an evaluation of @var{C2}.

A @code{!/0} evaluated in the disjunction not only prevents backtracking
within the disjunction, it also prevents backtracking to find
alternative solutions to calls that precede the disjunction in the
clause or query in which the disjunction appears.

A @code{!/0} evaluated within the @var{C1} branch also prevents the use
of @var{C2}.

@item !
@findex !/0
This is the backtracking control primitive. After it has been evaluated
in a clause a backtrack to the @code{!/0} call will be interpreted as
failure of the call C that invoked the clause. That is, it prevents the
search for alternative solutions to any calls that precede the
@code{!/0} in the body of the clause, and it will also prevent the use
of other clauses to try to solve C.

Placed at the top level in a query conjunction it will prevent
backtracking to find alternative solutions to calls that precede it in
the query. See the description of the logical operators @code{;/2} and
@code{->/2} for the effect of @code{!/0} inside these operators.

@item call(@var{+Goal})
@findex call/1
The call is equivalent to the call @var{Goal}, except where @var{Goal}
is @code{!/0} or includes @code{!/0}.  A @code{!/0} evaluated inside
@var{Goal} only has a local effect. It only affects backtracking to find
alternative solutions to calls that precede the @code{!/0} within
@var{Goal}.

@item not @var{+Call}
@findex not/1
This is the negation as failure operator. The call succeeds if and only if
@var{Call} fails.

@item \+ @var{+Call}
@findex \+/1
Same as @code{not/1}.

@item @var{+Test} -> @var{+Call}
This is the conditional evaluation operator. The @code{->/2} call
succeeds if and only if @var{Test} succeeds and @var{Call} succeeds. An
@code{if @dots{} then @dots{} else} construction may be created by
combining the conditional evaluation operator with the disjunction
operator `@code{;/2}' i.e. @* @code{@var{Test} -> @var{Call} ;
@var{Else}.} @* As with disjunctions and conjunctions, a @code{!/0}
evaluated in @var{Test} or @var{Call} not only has a local effect, but
also the same effects as a @code{!/0} evaluated just before the
@code{->/2} call.

@item true
@findex true/0
This call always succeeds.

@item otherwise
@findex otherwise/0
Same as @code{true/0}.

@item fail
@findex fail/0
This call does not match anything and always fails.

@item false
@findex false/0
Same as @code{fail/0}.

@item repeat
@findex repeat/0
This call always succeeds and repeatedly succeeds each time the
evaluation backtracks to the call. It is defined as:

@example
repeat.
repeat :- repeat.
@end example

@item succeed(@var{+Call})
@findex succeed/1
@var{Call} is evaluated and @code{succeed/1} succeeds, regardless of
whether @var{Call} succeeded or failed. Its definition is:

@example
succeed(Call) :-
        Call,
        !.
succeed(Call).
@end example

@item one(@var{+Goal})
@findex one/1
@var{Goal} must be a call term: @code{one/1} is used to find just one
solution to @var{Goal}.
@end table

@node Loading, IO, Control, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Loading, Consulting and Compiling 

@menu
* LoadIntro::                   Introduction 
* Style::                       Style Warnings
* LoadingDynamic::              Loading Dynamic Code 
* LoadingStatic::               Loading Static Code 
@end menu

@node LoadIntro, Style,  , Loading
@comment  node-name,  next,  previous,  up
@subsection Introduction 

@cindex consulting
@cindex compiling
@cindex loading
In ICP there is a distinction between dynamic (consulted) and static
(compiled) code. When a file is loaded into the runtime system, it is
stored either in the system or user partition.  Predicates in the system
partition can not be modified as they are necessary for running the
prolog system. Dynamic code is allways in the user partition.

@menu
* SearchPath::                  The Search Path 
* DynamicCode::                 Dynamic Code 
* StaticCode::                  Static Code 
@end menu

@node SearchPath, DynamicCode,  , LoadIntro
@comment  node-name,  next,  previous,  up
@subsubsection The Search Path 

@cindex search path
@cindex file extensions
@cindex file location
Source files are assumed to have the suffix @file{.pl} while compiled
files have the extension @file{.icp}. Many predicates dealing with files
will automatically append these extensions to files if they are not
present. Thus for example the goal
@example
?- consult(foo).
@end example
will result in the file @file{foo.pl} being consulted.

The locations in the Unix file system which will be searched to locate 
the specified file are determined by the Unix environment variable 
@file{ICP_PATH}. This must be a colon separated list, for example
@example
ICP_PATH=.:$HOME/icp/binary:$HOME/icp/source
@end example
ICP appends to the user defined path directories in the installation 
directory of ICP. If the variable @file{ICP_PATH} is not set, the search 
path is set as if the variable were set to the following value
@example
ICP_PATH=.:$HOME/icp/binary:$HOME/icp/source:$ICP_INSTALLDIR/prolog/$ARCH
@end example
where @file{$ICP_INSTALLDIR} is the ICP instalation directory and
@file{$ARCH} is the machine architecture as reported by the unix command
@file{/bin/arch} (eg @file{sun3} or @file{sun4}).

@node DynamicCode, StaticCode, SearchPath, LoadIntro
@comment  node-name,  next,  previous,  up
@subsubsection Dynamic Code

@cindex dynamic code
Dynamic code is code which can be modified dynamically by the user by
@code{assert/1} and, @code{retract/1} (@pxref{ModifyingDatabase}). In
addition dynamic code is `visible' in that it can be accessed by
@code{clause/2} and listed by @code{listing/0} and @code{listing/1}
(@pxref{ProgramState}). Dynamic code can also be traced.

Dynamic code can be created either by consulting a file using
@code{consult/1}, @code{reconsult/1} (@pxref{LoadingDynamic}), or by the
dynamically asserting clauses.

@node StaticCode,  , DynamicCode, LoadIntro
@comment  node-name,  next,  previous,  up
@subsubsection Static Code 

@cindex static code
Static code is generated by the compiler. In contrast to dynamic code it
is `hidden' from the user; the definition of a static clause can not be
accessed directly and it is forbiden to dynamically modify it. Static
code is optimized and thus executes much faster than dynamic code.

Compiled code is generated by the @code{compile/2} and @code{compile/3}
calls (@pxref{LoadingStatic}). The compiler saves the ICP object code in
a file with the extension @file{.icp}. Once a file has been compiled it
must be loaded into the ICP process.

@node Style, LoadingDynamic, LoadIntro, Loading
@comment  node-name,  next,  previous,  up
@subsection Style Warnings

@cindex style checking
ICP has a style checker which can help in detecting errors if a
particular style is used. Thus is as follows.

@enumerate
@item All clauses for a predicate should be contiguous --- clauses for
one procedure should not be interspaced with clauses for another.
@item Variables which appear only once in a clause should be written as
@samp{_} or a name beginning with an @samp{_}.
@end enumerate

If this style is not adhered to ICP can write warnings to
@code{user_error}.
@example
@cartouche
WARNING: Clauses for a/1 are not together in the source file
WARNING: Singleton variables, clause  2 of b/1:  [X] 
@end cartouche
@end example

The style checking can be controled by the predicates
@code{style_check/1} and @code{no_style_check/1}.

@table @code
@item style_check(@var{Type})
@findex style_check/1
@item

@table @code
@item all
turns on/off all style checking
@item discontiguous
turns on/off checking for discontiguous clauses
@item single_var
turns on/off checking for single occurence of variables. Variables whose
name begins with an underscore (@code{_}) are not flagged.
@end table

@item no_style_check(@var{Type})
@findex no_style_check/1
@end table

@node LoadingDynamic, LoadingStatic, Style, Loading
@comment  node-name,  next,  previous,  up
@subsection Loading Dynamic Code 

@table @code
@item consult(@var{+File})
@findex consult/1
@cindex consult
@var{File} is either the atom @code{user}, or the name of some source
file.  In the case of @var{File} not being the atom @code{user}, the file
is read and all clauses defined in it are asserted into the internal
database at the end.  Thus if a predicate defined in the file already
has a definition in the internal database, the effect is to expand the
definition of this predicate.  Consultation terminates when the end of
the file is reached.

If a syntax error is found during consultation then the string `@kbd{**
SYNTAX ERROR **}' is written out followed by all the text up to the
offending token, followed by the string `@kbd{*HERE*}', followed by all
those tokens which proceed the next period or the end of the file being
consulted. A syntax-error message is also displayed. Consultation
continues after this period.

On encountering a clause for a system predicate or for a currently defined
static predicate, @code{consult/1} ends the current session, displays
an error message, and then fails.

In the special case where @var{File} is the atom @code{user}
@code{consult/1} reads from the terminal (standard input) rather than a
file. Consultation terminates when a @code{end_of_file} token is read
(caused by typing @kbd{@key{CTL}-D}).  If a syntax error is found during
consultation then the string `@kbd{** SYNTAX ERROR **}' is written out,
together with the line of text in which the error occurred.  A
syntax-error message is also displayed.

The top-level goal
@example
?- [File1, ..., FileN].
@end example
is syntactic sugar for the goals
@example
?- consult(File1), ..., consult(FileN).
@end example

@item reconsult(@var{+File})
@findex reconsult/1
@cindex reconsult
Like @code{consult/1} except that all predicates previously
(re)consulted for this file are abolished before asserting the new
definitions.
@end table

@node LoadingStatic,  , LoadingDynamic, Loading
@comment  node-name,  next,  previous,  up
@subsection Loading Static Code 

@table @code
@item compile(@var{+File})
@findex compile/1
@cindex compile
@code{compile/1} is used to generate static object code for the
relations in @var{File}. @var{File} is either the atom @code{user}, or
the name of some source file. The predicates defined in file @var{File}
are compiled and written out to the corresponding object file.
Completion of suffixes is performed, with the object file having the
extension @file{.icp}.

@table @code
@item compiling user
If @var{File} is @kbd{user} then the relations the user wishes to
generate code for are to be entered directly at the terminal.  Each
relation is compiled to a separate segment which is automatically
loaded.  If a syntax error is found during compilation then the string
`@kbd{** SYNTAX ERROR **}' is written out, together with the line of
text in which the error occurred. A syntax-error message is also
displayed.  Compilation ends when the user types a @kbd{@key{CTL}-D}.
@item compiling a @file{.pl} file
If @var{File} is the name of a @file{.pl} file then @code{compile/1}
obtains the relations the user wishes to generate code for by reading
the file in question. All the relations are compiled into a single
segment which, on successful completion of compilation is written out to
the file `@var{File}@file{.icp}'. If a syntax error is found during
compilation then the string `@kbd{** SYNTAX ERROR **}' is written out,
followed by all the text up to the offending token, followed by the
string `@kbd{*HERE*}', followed by all those tokens which precede the
next period or the end of the file being compiled. A syntax-error
message is also displayed.  @code{compile/1} then continues reading from
the first character following the period.  Compilation ends when an end
of file is reached.  On encountering an invalid clause, @code{compile/1}
displays an error message and continues as if the offending clause had
not been read.
@end table

@item compile(@var{+File},@var{+Public})
@findex compile/2
Same as @code{compile/1} except that on loading the code resulting from
compilation, only the successfully compiled relations of @var{File}
whose predicates appear in the @var{Public} list, become accessible
other than to predicates in the same segment.  Predicates of arity zero
may appear in @var{Public} as simple atoms.

@item compile(@var{+File},@var{+Public},@var{+Mode})
@findex compile/3
Same as @code{compile/2} except that the third argument allows for
non-standard compilation modes to be adopted. If @var{Mode} is the atom
@code{single} then the relations of @var{File} are compiled into a single
segment, otherwise @var{Mode} must be the atom @code{multiple} and each
relation of @var{File} is compiled into a separate segment.

Single mode generates faster and more compact code, but multiple mode is
more flexible because individual predicates may be redefined. An analogy
is that predicates compiled in multiple mode are like black boxes while
those compiled in multiple mode have replaceable parts. The default is
single mode for compiling files and multiple mode for compiling
@code{user}.

@item load(@var{+File})
@findex load/1
If @var{File} is an atom, loads the object code contained in file
`@var{File}@file{.icp}'.  @code{load/1} notifies the user of the file being
loaded and returns after typing the word `@kbd{done}'. Files containing
built-in predicates are not loaded (a warning is given). If the file to
be loaded contains any predicate which is already defined, then the
predicate is abolished before loading takes place.  The @file{.icp} files are
first looked for in the current directory, and then in the subdirectory
`@file{binary}'. If the source file is newer than the compiled file, the
source file is compiled before the load.

If @var{File} is a list, is equivalent to repeatedly calling
@code{load/1} with the members of @var{Files}.

@item load(@var{+File}, @var{+Type})
@findex load/2
As @code{load/1} but of type @var{Type}, where @var{Type} is one of the
atoms @code{system} or @code{user} determining whether the predicates
should be placed in a system or user partition.

@item ensure_loaded(@var{+File})
@findex ensure_loaded/1
If the filename @var{File} is an atom, and the file has not been loaded
yet, this behaves in the same way as @code{load/1}.  If the file was
previously loaded, then @code{ensure_loaded/1} succeeds trivially.

If @var{File} is a list, this is equivalent to repeatedly calling
@code{ensure_loaded/1} with the members of @var{Files}.

@item loadicp(@var{+File})
@findex loadicp/1
Loads a compiled file. This is a form of loading which disables
automatic compilation and which does not handle lists of files.  If
@var{File} does not have the suffix @file{.icp} then @var{File}.icp is
loaded.

@item loadicp(@var{+File}, @var{+Type})
@findex loadicp/2
As @code{loadicp/1} but of type @var{Type}, where @var{Type} is one of
the atoms @code{system} or @code{user} determining whether the predicates
should be placed in a system or user partition.

@item rebuild(@var{+File})
@findex rebuild/0
Is used to recompile all system files that need it.

@item make(@var{+File})
@findex make/1
Is used to recompile a file if the source file is newer than the object
file.  All predicates defined in the file @var{File} are made public.

@item make(@var{+File}, @var{+Public})
@findex make/2
Is used to recompile a file if the source file is newer than the object
file.  All predicates in the list @var{Public} are made public, unless
@var{Public} is the empty list (@code{[]}) in which case all predicates
in the file are made public.

@item system(@var{+OnOff})
@findex system/1
Normally system predicates can not be re-loaded, an attempt to do so
results in a message of the form
@example
@cartouche
| ?- compile(user).
write(A):-foo(A).
cannot redefine system predicate(s): write/1.
@end cartouche
@end example
The call @code{?- system(on).} causes subsequent calls to
@code{compile/2} to allow redefinition of system predicates. To restore
the normal operation, the call @code{?- system(off).} should be used.
@end table

@node IO, Arithmetic, Loading, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Input and Output Primitives 
Input and output can be performed either on Prolog terms or on
individual characters. Furthermore output is relative to @emph{streams}
which refer either to files or to the terminal. The system always has a
@emph{current input} and @emph{current output} stream, which are by
default the keyboard and screen respectively.

@menu
* IOTerms::                     Input and Output of Terms
* IOChars::                     Input and Output of Characters
* StreamHandling::              File and Stream Handling
@end menu

@node IOTerms, IOChars,  , IO
@comment  node-name,  next,  previous,  up
@subsection Input and Output of Terms
Most of these predicates use the current input or output streams but have a
version where the stream may be specified. In this case the extra argument for
the stream, @var{Stream}, is the first argument of the predicate.
The stream versions of the predicates are
implemented in terms of the current input/output versions and the predicates of
section @ref{StreamHandling}. Hence if multiple reads or writes are to be
performed on a stream,
it is more efficient to set the current input or output to the stream than
to use the stream I/O primitives.

@table @code
@item read(@var{-T})
@itemx read(@var{+Stream},@var{-T})
@findex read/1
@findex read/2
@var{T} is unified with the next term that can be read (wrt the current
operator declarations) from the current input stream.  The term must be
followed by a period followed by a layout character. @code{read/1} does
nothing until these characters, which are consumed but are not a part of
the term, have been read. Any variable names in the read-in term are
converted into variables.

If a syntax error is found, an error message
is written out to @code{user_error}.  If the current input stream is
@code{user_input} then only the line of text in which the error occurred
is displayed. If instead the current input stream is associated with a
file, then all the text up to the offending token is displayed, followed
by the string `@kbd{*HERE*}', followed by all those tokens which precede
the next period or the end of file. @code{read/1} then tries again as if
it had started reading from the first character following the period.
Eventually, either some term is successfully read, or an end of file is
reached, whence @var{T} is unified with the @code{end_of_file} atom.  If
the input stream is a terminal, @code{read/1} will suspend if there are
no characters to be read.

@item write(@var{?X})
@itemx write(@var{+Stream},@var{?X})
@findex write/1
@findex write/2
Term @var{X} is written to the current output stream (wrt the current
operator declarations). Terms of the form @code{'$VAR'(N)} are treated
in a special way: On N being 0, 1, @dots{}, 27, 28, @dots{} write
outputs @samp{A}, @samp{B}, @dots{}, @samp{A1}, @samp{B1}, etc.

@item writeq(@var{?X})
@itemx writeq(@var{+Stream},@var{+X})
@itemx writeq(@var{+Stream}, @var{?X}, @var{+VarNames})
@findex writeq/1
@findex writeq/2
@findex writeq/3
Same as @code{write/1} except that it quotes those atoms that would need
to be quoted on input.

In the 3 argument version, atoms in the list @var{VarNames} are not quoted.
This gives a way of printing the original variable names provided the
term was read using @code{gread/3}.

@item display(@var{?X})
@itemx display(@var{+Stream},@var{+X})
@findex display/1
@findex display/2
Term @var{X} is written to the current output stream ignoring operators.
Variables are displayed as underscore names. This is particularly useful
for seeing the structure of terms containing multiple operators.

@item write_canonical(@var{?X})
@itemx write_canonical(@var{+Stream},@var{+X})
@findex write_canonical/1
@findex write_canonical/2
Term @var{X} is written to the current output stream ignoring operators.
Variables are displayed as underscore names. Atoms that would need to be
quoted on input are quoted. This is useful for writing out terms that
will be read back using @code{read/1-2}.

@item portray(@var{?Term})
@upindex portray/1
This is a user defined predicate which can be used to override the
default system ways of printing terms.

@item print(@var{?Term})
@itemx print(@var{+Stream}, @var{?Term})
@findex print/1
@findex print/2
This primitive allows user control over the output of terms. The print
primitive looks for the program @code{portray/1}. If there is no
definition for portray, the effect of print is exactly the same as for
@code{writeq/1}.

If the portray program is defined, then it is called to output the
@var{Term}. If @code{portray/1} succeeds, then @code{print/1} succeeds
and exits.

If the call to @code{portray/1} fails, and @var{Term} is atomic, then
@var{Term} will be output using @code{display/1}.

If the call to @code{portray/1} fails, and @var{Term} is compound, then
the principal functor of @var{Term} will be output using
@code{display/1}, and @code{portray/1} will be called recursively on the
arguments of @var{Term}.

If the call to @code{portray/1} fails, and @var{Term} is a list, then
the list will be output using bracket notation with @code{print/1} being
called for each element.

@item format(@var{Format}, @var{Arguments})
@itemx format(@var{Stream}, @var{Format}, @var{Arguments})
@findex format/2
@findex format/3
Provides a means of writing formatted data.  The following description
is extracted from the Sicstus Prolog on-line manual.

Print @var{Arguments} onto @var{Stream} according to format
@var{Format}.  @var{Format} is a list of formatting characters. If
@var{Format} is an atom then @code{name/2} will be
used to translate it into a list of characters.  Thus @refill

@example
| ?- format("Hello world!", []).
@end example

@noindent
has the same effect as

@example
| ?- format('Hello world!', []).
@end example

@code{format/3} is a Prolog interface to the C @code{stdio} function
@code{printf()}.  It is due to Quintus Prolog.  @refill

@var{Arguments} is a list of items to be printed. If there is only one item
it may be supplied as an atom. If there are no items then an empty list should
be supplied. @refill

The default action on a format character is to print it. The character @kbd{~}
introduces a control sequence. To print a @kbd{~} repeat it: @refill

@example
| ?- format("Hello ~~world!", []).
@end example

@noindent
will result in

@example
Hello ~world!
@end example

A format may be spread over several lines. The control sequence @kbd{\c}
followed by a @key{LFD} will translate to the empty string: @refill

@example
| ?- format("Hello \c
world!", []).
@end example

@noindent
will result in

@example
Hello world!
@end example

The general format of a control sequence is @samp{~@var{N}@var{C}}.
The character @var{C} determines the type of the control sequence.
@var{N} is an optional numeric argument. An alternative form of @var{N}
is @samp{*}. @samp{*} implies that the next argument in @var{Arguments}
should be used as a numeric argument in the control sequence. Example: @refill

@example
| ?- format("Hello~4cworld!", [0'x]).
@end example

@noindent
and

@example
| ?- format("Hello~*cworld!", [4,0'x]).
@end example

@noindent
both produce

@example
Helloxxxxworld!
@end example

The following control sequences are available.

@table @samp
@item ~a
The argument is an atom. The atom is printed without quoting. @refill
@item ~@var{N}c
(Print character.)  The argument is a number that will be interpreted as an
ASCII code. @var{N} defaults to one and is interpreted as the number of
times to print the character. @refill
@item ~@var{N}e
@itemx ~@var{N}E
@itemx ~@var{N}f
@itemx ~@var{N}g
@itemx ~@var{N}G
(Print float). The argument is a float.  The float and @var{N} will be
passed to the C @code{printf()} function as @refill

@example
printf("%.@var{N}e", @var{Arg})
printf("%.@var{N}E", @var{Arg})
printf("%.@var{N}f", @var{Arg})
printf("%.@var{N}g", @var{Arg})
printf("%.@var{N}G", @var{Arg})
@end example

If @var{N} is not supplied the action defaults to

@example
printf("%e", @var{Arg})
printf("%E", @var{Arg})
printf("%f", @var{Arg})
printf("%g", @var{Arg})
printf("%G", @var{Arg})
@end example
@item ~@var{N}d
(Print decimal.) The argument is an integer. @var{N} is interpreted as the
number of digits after the decimal point. If @var{N} is 0 or missing, no
decimal point will be printed. Example: @refill

@example
| ?- format("Hello ~1d world!", [42]).
| ?- format("Hello ~d world!", [42]).
@end example

@noindent
will print as

@example
Hello 4.2 world!
Hello 42 world!
@end example

@noindent
respectively.
@item ~@var{N}D
(Print decimal.) The argument is an integer. Identical to @samp{~@var{N}d}
except that @samp{,} will separate groups of three digits to the left of the
decimal point. Example: @refill

@example
| ?- format("Hello ~1D world!", [12345]).
@end example

@noindent
will print as

@example
Hello 1,234.5 world!
@end example

@item ~@var{N}r
(Print radix.) The argument is an integer. @var{N} is interpreted as a radix.
@var{N} should be >= 2 and <= 36. If @var{N} is missing the radix defaults to
8. The letters @samp{a-z} will denote digits larger than 9. Example: @refill

@example
| ?- format("Hello ~2r world!", [15]).
| ?- format("Hello ~16r world!", [15]).
@end example

@noindent
will print as

@example
Hello 1111 world!
Hello f world!
@end example

@noindent
respectively.
@item ~@var{N}R
(Print radix.) The argument is an integer. Identical to @samp{~Nr} except
that the letters @samp{A-Z} will denote digits larger than 9. Example: @refill

@example
| ?- format("Hello ~16R world!", [15]).
@end example

@noindent
will print as

@example
Hello F world!
@end example

@item ~@var{N}s
(Print string.) The argument is a list of ASCII codes. Exactly @var{N}
characters will be printed. @var{N} defaults to the length of the string.
Example: @refill

@example
| ?- format("Hello ~4s ~4s!", ["new","world"]).
| ?- format("Hello ~s world!", ["new"]).
@end example

@noindent
will print as

@example
Hello new  worl!
Hello new world!
@end example

@noindent
respectively.
@item ~i
(Ignore argument.) The argument may be of any type. The argument will be
ignored. Example: @refill

@example
| ?- format("Hello ~i~s world!", ["old","new"]).
@end example

@noindent
will print as

@example
Hello new world!
@end example

@item ~k
(Print canonical.) The argument may be of any type. The argument will be
passed to @code{write_canonical/2}. Example: @refill

@example
| ?- format("Hello ~k world!", [[a,b,c]]).
@end example

@noindent
will print as

@example
Hello .(a,.(b,.(c,[]))) world!
@end example

@item ~p
(print.) The argument may be of any type. The argument will be passed to
@code{print/2}. Example: @refill

@example
| ?- assert((portray([X|Y]) :- print(cons(X,Y)))).
| ?- format("Hello ~p world!", [[a,b,c]]).
@end example

@noindent
will print as

@example
Hello cons(a,cons(b,cons(c,[]))) world!
@end example

@item ~q
(Print quoted.) The argument may be of any type. The argument will be
passed to @code{writeq/2}. Example: @refill

@example
| ?- format("Hello ~q world!", [['A','B']]).
@end example

@noindent
will print as

@example
Hello ['A','B'] world!
@end example

@item ~w
(write.) The argument may be of any type. The argument will be passed to
@code{write/2}. Example: @refill

@example
| ?- format("Hello ~w world!", [['A','B']]).
@end example

@noindent
will print as

@example
Hello [A,B] world!
@end example

@item ~@var{N}n
(Print newline.) Print @var{N} newlines. @var{N} defaults to 1.
Example: @refill

@example
| ?- format("Hello ~n world!", []).
@end example

@noindent
will print as

@example
Hello
 world!
@end example
@end table

@item gread(@var{-T})
@itemx gread(@var{+Stream},@var{-T})
@itemx gread(@var{+Stream},@var{-T},@var{-V})
@findex gread/1
@findex gread/2
@findex gread/3
Same as @code{read/1} except that the variable names which occur in the
read-in term appear in @var{T} as quoted atoms, rather than being
converted into variables.

In the 3 argument version @var{V} is instantiated to the list
of atoms that are the variable names of the read-in term.
@example
@cartouche
| ?- gread(user_input, T, V).
foo(X, a(Y, X)).

T = foo('X',a('Y','X'))
V = ['X','Y'] 
@end cartouche
@end example

@item writeseq(@var{+X})
@itemx writeseq(@var{+Stream},@var{+X})
@findex writeseq/1
@findex writeseq/2
Uses @code{write/1} to write the elements of the list @var{X} in
sequence and separated by single spaces.

@item writeqseq(@var{+X})
@itemx writeqseq(@var{+Stream},@var{+X})
@findex writeqseq/1
@findex writeqseq/2
Uses @code{writeq/1} to write the elements of the list @var{X} in
sequence and separated by single spaces.

@item writenl(@var{?X})
@itemx writenl(@var{+Stream},@var{+X})
@findex writenl/1
@findex writenl/2
Starts a new line on the current output stream after having used
@code{write/1} to write @var{X}.

@item writeqnl(@var{?X})
@itemx writeqnl(@var{+Stream},@var{+X})
@findex writeqnl/1
@findex writeqnl/2
Starts a new line on the current output stream after having used
@code{writeq/1} to write @var{X}.

@item writeseqnl(@var{+X})
@itemx writeseqnl(@var{+Stream},@var{+X})
@findex writeseqnl/1
@findex writeseqnl/2
Starts a new line on the current output stream after having used
@code{write/1} to write the elements of @var{X} in sequence and
separated by single spaces.
@example
@cartouche
| ?- writeseqnl([a1,'A2',4]).
a1 A2 4 

yes
@end cartouche
@end example

@item writeqseqnl(@var{+X})
@itemx writeqseqnl(@var{+Stream},@var{+X})
@findex writeqseqnl/1
@findex writeqseqnl/2
Starts a new line on the current output stream after having used
@code{writeq/1} to write the elements of @var{X} in sequence and
separated by single spaces.

@item write_term(@var{?Term})
@itemx write_term(@var{+Stream}, @var{?Term})
@findex write_term/1
@findex write_term/2
Same as @code{write/1} except that the term will be written in an
encoded form which can only be decoded by @code{read_term/1}. This is
more efficient than @code{write/1} because the structure of the term is
preserved in the encoding.

@item read_term(@var{-Term})
@itemx read_term(@var{+Stream}, @var{-Term})
@findex read_term/1
@findex read_term/2
Reads an encoded term from the current input stream. The encoded version
of a term is read by @code{read_term/1} at a greater speed than
@code{read/1} can read the original term.  @code{write_term/1} and
@code{read_term/1} can be used to write to files large terms that
require frequent reading.

@item portray_clause(@var{?Clause})
@findex portray_clause/1
Displays a clause in the same way as @code{listing/1}. In fact
@code{listing/1} and @code{listing/2} use @code{portray/1}.
@end table

@node IOChars, StreamHandling, IOTerms, IO
@comment  node-name,  next,  previous,  up
@subsection Input and Output of Characters
Most of these predicates use the current input or output streams but have a
version where the stream may be specified. In this case the extra argument for
the stream, @var{Stream}, is the first argument of the predicate.
The stream versions of the predicates are
implemented in terms of the current input/output versions and the predicates of
section @ref{StreamHandling}. Hence if multiple reads or writes are to be
performed on a stream,
it is more efficient to set the current input or output to the stream than
to use the stream io primitives.

@table @code
@item get0(@var{-C})
@itemx get0(@var{+Stream}, @var{-C})
@findex get0/1
@findex get0/2
Reads the next character (ASCII code) from the current input stream and
instantiates @var{C} to it. The predicate returns 26 (@kbd{@key{CTL}-Z})
on @code{end_of_file}.

@item get(@var{-C})
@itemx get(@var{+Stream}, @var{-C})
@findex get/1
@findex get/2
Reads the next character (ASCII code) from the current input stream and
instantiates @var{C} to it, ignoring non printable characters (ascii
code < 33 or > 126). The predicate returns 26 on @code{end_of_file}.

@item skip(@var{+N})
@itemx skip(@var{+Stream}, @var{+N})
@findex skip/1
@findex skip/2
Skips over characters from the current input stream to the first
occurrence of the character with ASCII code @var{N}.

@item put(@var{+N})
@itemx put(@var{+Stream}, @var{+N})
@findex put/1
@findex put/2
Writes @var{N} to the current output stream. @var{N} should be either a
valid ASCII code or an integer expression.

@item nl
@itemx nl(@var{+Stream})
@findex nl/0
@findex nl/1
Starts a new line on the current output stream.

@item tab(@var{+N})
@itemx tab(@var{+Stream}, @var{+N})
@findex tab/1
@findex tab/2
N (>=0) spaces are written to the current output stream.

@item tty_get0(@var{-C})
@findex tty_get0/1
Reads the next character (ASCII code) from the current terminal input
stream and instantiates @var{C} to it. This is used when an input
character must come from the keyboard, not necessarily the current
stream.

@item unget(@var{+N})
@findex unget/1
Puts ASCII code @var{N} back onto the current input stream.
@end table

@node StreamHandling,  , IOChars, IO
@comment  node-name,  next,  previous,  up
@subsection File and Stream Handling

Input and output streams are represented as unique prolog terms having the
following form where @code{N} is an integer.

@table @code
@item stream(N)
refers to the terminal or files 
@item memory(N)
refers to ram files, which can be converted to and from prolog atoms.
@end table

There are also three streams which are opened automatically by the system

@table @code
@item user_input
The standard input channel (`C' @kbd{stdin})
@item user_output
The standard output channel (`C' @kbd{stdout})
@item user_error
The standard error channel (`C' @kbd{stderr})
@end table

@table @code
@item open(@var{+F},@var{+M},@var{-Stream})
@findex open/3
Opens file @var{F} in mode @var{M} on file-stream @var{Stream}. @var{M}
must be one of @code{read}, @code{write} and @code{append}.

@item close(@var{+Stream})
@findex close/1
Closes the stream corresponding to @var{Stream}.

@item set_input(@var{+Stream})
@findex set_input/1
Makes @var{Stream} the current input stream.

@item set_output(@var{+Stream})
@findex set_output/1
Makes @var{Stream} the current output stream.

@item current_input(@var{-Stream})
@findex current_input/1
Instantiates @var{Stream} with the current input stream.

@item current_output(@var{-Stream})
@findex current_output/1
Instantiates @var{Stream} with the current output stream.

@item open_ram(@var{+C},@var{+M},@var{-Stream})
@findex open_ram/3
Opens ram-file @var{C} in mode @var{M} on memory-stream @var{Stream}.
@var{M} must be one of @code{read}, @code{write} and @code{append}.
When opening a ram-file in @code{read} or @code{append} mode @var{C}
must be an atom representing the file's contents.   This atom is
usually the result of a @code{ram_const/2} call.  When opening the file
in @code{write} mode, argument @var{C} is ignored and the file is
created empty.

@item open_ram(@var{+C}, @var{+M}, @var{-Stream}, @var{+Size})
@findex open_ram/4
As @code{open_ram/3} but allows the size of the ram file to be specified.

@item ram_const(@var{+F}, @var{-C})
@findex ram_const/2
Converts the contents of the ram-file @var{+F} into an atom @var{-C}.
Typically, @var{-C} is subsequently used as the first argument of an
@code{open_ram/3} call to access the contents of the ram-file.

@item ram_pipe(@var{-Out},@var{-In})
@findex ram_pipe/2
Creates a pseudo-pipe by allocating a ram file with two references to
it.  The first reference @var{Out} is opened in write mode, and the
second reference @var{In} is opened in read mode.  This allows one
thread to pass terms to another.  It is the responsiblity of the
programmer to make sure that there is data available before it is read.
For pipes with blocking read and write, see @code{pipe/2} in chapter 14.
The advantage of ram pipes is that they can be made the subject of
current input and current output.

@item tty(@var{+Name},@var{-Read},@var{-Write})
@findex tty/3
Creates a new window with title @var{Name} and two streams --- @var{Read}
and @var{Write}.  Input typed in the new window can be read from stream
@var{Read}.  Output written to stream @var{Write} will appear in the
window.

@item flush_output(@var{+Stream})
@findex flush_output/1
@var{Stream} must be a stream open for output. @var{Output} to a stream
is not necessarily sent immediately; it is buffered. This predicate
flushes the output buffer for the specified stream and thus ensures that
everything that has been written to the stream is actually sent at that
point.

@item flush
@findex flush/0
Same as @code{flush_output/1} except that the flushed stream
is the current output stream.

@item file_exists(@var{+F})
@findex file_exists/1
Succeeds if file @var{F} exists.
@end table

@node Arithmetic, TypePrimitives, IO, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Arithmetic

@table @code
@item @var{-X} is @var{+Y}
@findex is/2
@var{X} is the result of evaluating arithmetic expression @var{Y}.

An arithmetic expression is either an number, or a variable which is
bound to a number, or a singleton list whose head is an integer (in this
case the value of the expression is the integer itself), or a single
character in double quotes (in this case the value of the expression is
the ASCII code of the character), or a compound expression. A compound
expression is a tuple whose functor is an arithmetic operator and whose
arguments are arithmetic expressions. A description of the allowed
compound expressions, together with the result of their evaluation
follows:

@table @code
@item -@var{E}
negative of @var{E}
@item @var{E1} + @var{E2}
sum of @var{E1} and @var{E2}
@item @var{E1} ++ @var{E2}
integer sum of integers @var{E1} and @var{E2}
@item @var{E1} - @var{E2}
difference of @var{E1} and @var{E2}
@item @var{E1} -- @var{E2}
integer difference of integers @var{E1} and @var{E2}
@item @var{E1} * @var{E2}
product of @var{E1} and @var{E2}
@item @var{E1} ** @var{E2}
integer product of integers @var{E1} and @var{E2}
@item @var{E1} / @var{E2}
quotient of @var{E1} and @var{E2}
@item @var{E1} // @var{E2}
integer part of quotient of integers @var{E1} and @var{E2}
@item @var{E1} mod @var{E2}
remainder of the integer division of @var{E1} and @var{E2}
@item @var{E1} ^ @var{E2}
@var{E1} raised to the power @var{E2}
@item @var{E1} << @var{E2}
integer @var{E1} shifted left by @var{E2} bits
@item @var{E1} >> @var{E2}
integer @var{E1} shifted right by @var{E2} bits
@item \@var{E}
bitwise logical negation of integer @var{E}
@item @var{E1} /\ @var{E2}
bitwise logical And of integers @var{E1} and @var{E2}
@item @var{E1} \/ @var{E2}
bitwise logical Or of integers @var{E1} and @var{E2}
@item int(@var{E})
integer truncation of @var{E} towards 0
@item abs(@var{E})
absolute value of @var{E}
@item sign(@var{E})
sign of @var{E}: -1 if negative, 1 if positive and 0 if 0
@item ceil(@var{E})
round up to next higher integer
@item floor(@var{E})
round down to next lower integer
@item sin(@var{E})
sine of an angle @var{E} in radians
@item cos(@var{E})
cosine of an angle @var{E} in radians
@item tan(@var{E})
tangent of an angle @var{E} in radians
@item sin(@var{E})
arcsine of @var{E} (in radians) in the range -pi/2 to pi/2
@item acos(@var{E})
arcosine of @var{E} (in radians) in the range 0 to pi
@item atan(@var{E})
arctangent of @var{E} (in radians) in the range -pi/2 to pi/2
@item atan2(@var{E1}, @var{E2})
arctangent of @var{E1}/@var{E2} (in radians) in the range -pi to pi
@item sinh(@var{E})
hyperbolic sine of an angle @var{E} in radians
@item cosh(@var{E})
hyperbolic cosine of an angle @var{E} in radians
@item tanh(@var{E})
hyperbolic tangent of an angle @var{E} in radians
@item exp(@var{E})
natural anti-logarithm of @var{E}
@item log(@var{E})
natural logarithm of @var{E}
@item log10(@var{E})
logarithm (base 10) of @var{E}
@item sqrt(@var{E})
square root of @var{E}
@item pow(@var{E1}, @var{E2})
@var{E1} raised to the power @var{E2}
@item pi
value of pi
@item rand
random integer in the range 0 to 32767
@item deg2rad(@var{E})
number of radians in @var{E} degrees
@item rad2deg(@var{E})
number of degrees in @var{E} radians
@item integer(@var{E})
the integer component (integer closest to 0) of @var{E}'s value.
@item float(@var{E})
@var{E}'s value.
@end table
@end table

@menu
* ArithmeticComparison::        Arithmetic Comparison 
@end menu

@node ArithmeticComparison,  ,  , Arithmetic
@comment  node-name,  next,  previous,  up
@subsection Arithmetic Comparison 

@table @code
@item @var{+X} =:= @var{+Y}
@findex =:=/2
@var{X} is equal to @var{Y}.

@item @var{+X} =\= @var{+Y}
@var{X} is not equal to @var{Y}.

@item @var{+X} < @var{+Y}
@var{X} is less than @var{Y}.

@item @var{+X} > @var{+Y}
@var{X} is greater than @var{Y}.

@item @var{+X} =< @var{+Y}
@var{X} is less than or equal to @var{Y}.

@item @var{+X} >= @var{+Y}
@var{X} is greater than or equal to @var{Y}.
@end table

@node TypePrimitives, Term Comparison, Arithmetic, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Type Primitives 

@table @code
@item tag(@var{+Term},@var{-Tag})
@findex tag/2
@var{Tag} is bound to an integer in the range 0-6 which uniquely identifies
@var{Term}'s type. The tag values are as follows:

@table @code
@item @var{Tag}=0
variable
@item @var{Tag}=1
integer
@item @var{Tag}=2
floating point
@item @var{Tag}=3
atom
@item @var{Tag}=4
nil (empty list)
@item @var{Tag}=5
list
@item @var{Tag}=6
tuple
@end table

@item var(@var{?X})
@findex var/1
Succeeds if @var{X} is an uninstantiated variable.

@item nonvar(@var{?X})
@findex nonvar/1
Succeeds if @var{X} is instantiated.

@item atom(@var{?X})
@findex atom/1
Succeeds if @var{X} is an atom.

@item integer(@var{?X})
@findex integer/1
Succeeds if @var{X} is an integer.

@item float(@var{?X})
@findex float/1
Succeeds if @var{X} is a floating point number.

@item number(@var{?X})
@findex number/1
Succeeds if @var{X} is a number (integer or floating point).

@item atomic(@var{?X})
@findex atomic/1
Succeeds if @var{X} is an atom or a number.

@item list(@var{?X})
@findex list/1
Succeeds if @var{X} is a list (empty or non-empty).

@item compound(@var{?X})
@findex compound/1
The call succeeds if and only if @var{X} is bound to a tuple or a non-empty
list.

@item tuple(@var{?X})
@findex tuple/1
Succeeds if @var{X} is a tuple.

@item tuple(@var{?X},@var{-N})
@findex tuple/2
Succeeds if @var{X} is a functor of arity @var{N}-1 (@var{N} >= 1).

@item length(@var{?Term},@var{?N})
@findex length/2
If @var{Term} is a list with a non variable length, @var{N} will be 
bound to its length.

If @var{N} is an integer then @var{Term} will be instantiated to a list with 
@var{N} elements.

If @var{Term} is a tuple, @var{N} will be unified with the tuple's arity
plus one.

@item @var{?T1} = @var{?T2}
@findex =/2
Defined as if by the clause "@code{Z=Z.}"; that is, @var{T1} and @var{T2} are
unified.

@item @var{?T1} \= @var{?T2}
Succeeds if an only if the call @code{T1=T2} fails; that is, if @var{T1} and
@var{T2} are not unifiable.

@item functor(@var{?Term},@var{?Name},@var{?Arity})
@findex functor/3
@var{Term} is a term with functor @var{Name} and arity @var{Arity}.
Atomic terms are taken to have arity 0 and functor identical to the
term. If @var{Term} is a variable the arity must be an integer >= 0 and
@var{Name} a valid ICP tuple functor.
@example
@cartouche
| ?- functor(foo(a1, a2, a3), Name, Arity).

Name = foo
Arity = 3

| ?- functor(Term, foo, 3).

Term = foo(_132,_133,_134) 

| ?- functor(foo, Name, Arity).

Name = foo
Arity = 0

| ?- functor(T, f(Z), 2).

Unbound variable : Z 
T = f(Z)(_113,_114) 

@end cartouche
@end example

@item arg(@var{+N},@var{+Tup},@var{-Arg})
@findex arg/3
If @var{N} is a positive integer less than or equal to the arity of tuple
@var{Tup} then @var{Arg} is unified with @var{Tup}'s @var{N}th
argument.
@example
@cartouche
| ?- arg(2, foo(a1, a2, a3), Arg).

Arg = a2 
@end cartouche
@end example

@item nth0(@var{?N},@var{+List},@var{?El})
@findex nth0/3
If @var{N} is a positive integer, this finds the nth element @var{?El} in
a list @var{+List}, counting the first element as 0.  If @var{N} is a
variable, then the position of the element @var{?El} is calculated.

@item nth1(@var{?N},@var{+List},@var{?El})
@findex nth1/3
If @var{N} is a positive integer, this finds the nth element @var{?El} in
a list @var{+List}, counting the first element as 1.  If @var{N} is a
variable, then the position of the element @var{?El} is calculated.

If @var{N} is a positive integer less than or equal to the arity of tuple
@var{Tup} then @var{Arg} is unified with @var{Tup}'s @var{N}th
argument.

@item @var{?X} =.. @var{?Y}
@findex =../2
@var{Y} is a list. Its head is the functor of @var{X} and its (possibly empty) 
tail is a list of @var{X}'s arguments.
@end table

@node Term Comparison, ProgramState, TypePrimitives, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Term Comparison 
@menu
* StandardOrderTerms::          The Standard Order on Terms
* TermComparisonPreds::         Term Comparison Predicates 
@end menu

@node StandardOrderTerms, TermComparisonPreds,  , Term Comparison
@comment  node-name,  next,  previous,  up
@subsection The Standard Order on Terms

If two terms are of a different type, then the ordering is as follows: @*
variable < number < symbol < nil < list < tuple

If two terms have the same type then:

@itemize @bullet
@item
variables are compared by their machine address
@item
numbers are compared using `@code{</2}'.
@item
symbols are compared lexicographically, using the ASCII ordering.
@item
lists are compared by their first element.  If equal, the tails are
compared.
@item
tuples are compared first by arity, then by each of the arguments.
@end itemize

@node TermComparisonPreds,  , StandardOrderTerms, Term Comparison
@comment  node-name,  next,  previous,  up
@subsection Term Comparison Predicates 

@table @code

@item compare(@var{?Op},@var{?T1},@var{?T2})
@findex compare/3
The result of comparing terms @var{T1} and @var{T2} is @var{Op}, where the
possible values of @var{Op} are:

@table @code
@item  `='
If @var{T1} is identical to @var{T2},
@item `<'
If @var{T1} is before @var{T2} in the Standard Order
@item `>'
If @var{T1} is after @var{T2} in the Standard Order
@end table

@item @var{?T1} == @var{?T2}
Succeeds if the terms currently instantiating @var{T1} and @var{T2} are
literally identical (in particular, variables in equivalent positions in
the two terms must be identical).

@item @var{?T1} \== @var{?T2}
Succeeds if the terms currently instantiating @var{T1} and @var{T2} are not
literally identical.

@item @var{?T1} @@> @var{?T2}
Succeeds if term @var{T1} is after term @var{T2} in the Standard Order.

@item @var{?T1} @@< @var{?T2}
Succeeds if term @var{T1} is before term @var{T2} in the Standard Order.

@item @var{?T1} @@>= @var{?T2}
Succeeds if term @var{T1} is not before term @var{T2} in the Standard Order.

@item @var{?T1} @@=< @var{?T2}
Succeeds if term @var{T1} is not after term @var{T2} in the Standard Order.
@end table

@node ProgramState, ExecutionAndError, Term Comparison, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Examining the Program State 

@table @code
@item defined(@var{+PredArity})
@findex defined/1
Succeeds if @var{PredArity} is currently defined.
@example
@cartouche
| ?- defined(defined/1).

yes
@end cartouche
@end example

@item predicate(@var{?Pred},@var{?Term})
@findex predicate/2
Succeeds if it can unify @var{Pred} with the name of a currently defined
predicate and @var{Term} with the most general tuple with the same arity
(i.e. a tuple with distinct variables for all of its arguments) and
having @var{Pred} as its functor and the predicate's arity as its arity.
@example
@cartouche
| ?- predicate(Pred, Term).

Pred = mod%f
Term = mod%f(_149,_150,_151) 

| ?- predicate(predicate, Term).

Term = predicate(_143,_144) 
@end cartouche
@end example

@item current_predicate(@var{?Pred},@var{?Term})
@findex current_predicate/2
Succeeds if it can unify @var{Pred} with the name of a user-defined
predicate and @var{Term} with the most general tuple (i.e. a tuple with
distinct variables for all of its arguments) having @var{Pred} as its
functor and the predicate's arity as its arity.
@example
@cartouche
| ?- current_predicate(Pred, Term).

Pred = system_file
Term = system_file(_153) 

| ?- current_predicate(foo, Term).

no
| ?- assert(foo(1,2)), current_predicate(foo, Term).

Term = foo(_466,_467) 
@end cartouche
@end example

@item system_predicate(@var{?Pred},@var{?Term})
@findex system_predicate/2
Attempts to unify @var{Pred} with the name of a system-predicate and
@var{Term} with the most general tuple with the same arity (i.e. a tuple
with distinct variables for all of its arguments) having @var{Pred} as
its functor.
@example
@cartouche
| ?- system_predicate(Pred, Term).

Pred = mod%f
Term = mod%f(_153,_154,_155) 

| ?- system_predicate(listing, Term).

Term = listing ;

Term = listing(_145) ;

no
@end cartouche
@end example

@item predicate_property(@var{?Term}, @var{?Property})
@findex predicate_property/2
Finds the property associated with predicate @var{Term}. A predicate can
have more than one property. The possible properties are

@table @code
@item static
The predicate is static (i.e. compiled).
@item dynamic
The predicate is dynamic (i.e. consulted or asserted).
@item system
The predicate is a system predicate.
@item user
The predicate is a user defined predicate.
@end table

A predicate can have more than one property
@example
@cartouche
| ?- predicate_property(predicate_property(_,_), Property).

Property = static ;

Property = system ;

no
@end cartouche
@end example

@item clause(@var{?Head},@var{?Body})
@findex clause/2
Searches the database for a clause whose head matches @var{Head} and
whose body matches @var{Body}. This predicate is non-determinate and can
be used to backtrack through all the clauses matching @var{Head} and
@var{Body}. It fails when there are no (further) matching clauses in the
database.

For the purpose of this matching, unit clauses (clauses with no body) are
treated as if they had a body consisting of the single goal 
@code{true/0}.

@item listing
@findex listing/0
Lists to the current output channel all the relations (if any) which are in
the data base.

@item listing(@var{+Pred})
@findex listing/1
All forms of @code{listing/1} can only be used for dynamic predicates.

If @var{Pred} is an atom, lists to the current output channel all the
relations (if any) which are in the data base and have @var{Pred} as
name.

If @var{Pred} is a term of the form @var{Name/Arity} then the predicates 
of the specified name and arity are listed.

If @var{Pred} is a term of the form @var{Name/Arity1-Arity2}, then
listing lists the relations with name Name and arities in the specified
range to the current output channel.

@var{Pred} may also be a list of terms of the above form. Thus the goal
@example
?- listing([foo, bar/2]).
@end example
is equivalent to the goal
@example
?- listing(foo), listing(bar/2).
@end example

@item listfile(@var{+File})
@findex listfile/1
Lists to the current output channel all predicates in file @var{File}.
If @var{File} does not end in @file{.pl} this extension is appended to
the file name.
@end table

@node ExecutionAndError, ModifyingDatabase, ProgramState, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Execution and Error Handling 

Error handling in ICP is based on the idea of catch-and-throw.
The query
@example
	catch(Goal)
@end example
behaves in exactly the same way as
@example
	call(Goal)
@end example
if @var{Goal} succeeds or fails.  However, if an error occurs during
the execution of @var{Goal}, then the behaviour is as if
@code{system_error/2} was called, with the first argument being
@var{Goal} and the second argument bound to the error number.
The error numbers are listed in the appendix.

Note that @code{system_error/2} is called with the argument @var{Goal}
even though the error might have occurred in a subgoal of @var{Goal}. e.g.
in the program,
@example
	p :- q, r.
	q :- s, t.
@end example
and the call
@example
	catch(p)
@end example
the system error handler will report the error occurring in @var{p} even
though the error might have occurred in the subgoal @var{t}.  This has
the advantage that the low-level definition of @var{p} can be hidden.
If the user really wanted to report @var{t} as the culprit goal, this
can be specified by changing the definition of @var{q} to be
@example
	q :- s, catch(t).
@end example
This introduces another nesting level of `catch'.  Errors are always
reported at the innermost catch level.

Errors are normally generated from the execution of built-in
primitives.  Typically, a primitive is called with the wrong
arguments.  However, it is possible to manually force errors
by using @code{throw/1}, where the argument specifies the error
number.  This is also the mechanism for generating any user-defined
errors.

There are cases when we would like to call the system error handler
with a different goal from the one which `caught' the error.  We
can do this using @code{catch/2}.

If the user wishes to handle specific errors but default to the system
error handler for all other cases, then the @code{user_error/2} hook
should be used.

There is yet another form @code{catch/3} which offers the most
control in error-handling.  In this form, any goal may be called
as the error handler to be used.

These different options are described in more detail below.

@table @code
@item catch(@var{+Goal})
@findex catch/1
This defines a catch point.  
@var{Goal} is executed. If @var{Goal} succeeds without any errors, the
call to @code{catch/1} succeeds. If @var{Goal} fails without any errors, the call
to @code{catch/1} fails.  Otherwise, if an error occurs during the execution of
@var{Goal}, the system error handler of ICP is invoked with @var{Goal} and
the error number.

@item throw(@var{+Error})
@findex throw/1
An error with error code @var{Error} is forced. The error is handled by the
error handler associated with the most recent call to catch.

@item catch(@var{+Goal},@var{+BadGoal})
@findex catch/2
Same as @code{catch/1} except that the ICP error handler is invoked
with @var{BadGoal}, rather than @var{Goal}, being the culprit goal.

@item catch(@var{+Goal},@var{+ErrorHandler},@var{-Error})
@findex catch/3
@var{Goal} is executed. If @var{Goal} succeeds without any errors, the call
to @code{catch/3} succeeds. If @var{Goal} fails without any errors, the
call to @code{catch/3} fails. Otherwise, if an error occurs during the
execution of @var{Goal}, @var{Error} is bound to the appropriate error code
and then @var{ErrorHandler} is executed.  This predicate is a hook for
enabling user-defined error handling.  This is very powerful because the
user-defined error handler may contain any number of arguments.  For
simple cases where the error goal and the error number are sufficient,
the @code{user_error/2} hook described next is better.

@item user_error(@var{+Goal}, @var{+Errno})
@upindex user_error/2
Error handlers may be defined by @code{user_error/2}, where
the first argument is the goal at the catch point (not necessarily
the goal that caused the error) and the second argument is
the error number.

Here is a sample error handler.  Note the use of cut for each
clause, and the final catch-all clause that passes the error
to the error handler at the next level up (typically the system
error handler).
@example
user_error(Goal, 403) :- !,	/* predicate not defined error */
	writeseqnl([Goal, 'not defined yet']),
	fail.
user_error(Goal, 600) :- !,	/* divide by 0 error */
	writenl('divide by zero is not possible'),
	fail.
user_error(Goal, Error) :- !,	/* throw to the next level up */
	throw(Error).
@end example

For convenience, access to the system error handlers is provided
via @code{system_error/2} and @code{system_fail/2}.  The difference
between the two is that @code{system_error/2} will cause a return
to the top level ICP prompt, whereas @code{system_fail/2} will
simply fail and cause a backtrack.  Typically, these will be used
in user-defined error handlers for the `uninteresting' cases.

@item system_error(@var{+Goal}, @var{+Error})
@findex system_error/2
Display an error message for the error number @var{Error} and
return to the top level prompt.

@item system_fail(@var{+Goal}, @var{+Error})
@findex system_fail/2
Display an error message for the error number @var{Error} and
then fail.

Undefined predicates are handled slightly differently.  Initially
they are not errors as such, but you may define them to be errors.
So what is so special about undefined predicates ?  Recall that a call
@example
	catch(p)
@end example
creates a catch point.   Any errors that
occur while executing p will cause a throw to the most recent
catch point where it is reported.  The part of the search tree
between the catch and the throw (where the error occurred) is discarded.
This is important
because it means that whatever action we can take to recover from the
error, it can only proceed from the `catch' and not from the point
where the error occurred (which may be deep down the search tree).
This is fine for most errors where we want to continue from a known
point, however for undefined predicates it is not ideal.  Consider
the following program :
@example
	p :- q.
	q :- r.
	r :- s.
@end example
and the call
@example
	| ?- catch(p).
@end example
(Actually the `catch' is redundant here because all top-level queries
are automatically caught)  The system will report the error as
@example
	ERROR 403 : undefined predicate : p/0
@end example
This is confusing because it is 's' that is undefined, not 'p'.
However, this is what happens because the only catch point created
was at 'p'.  Moreover, even if we defined our own error handler to
try to recover, we cannot continue from 's', but instead we are
forced to restart from 'p' again.  The solution is `obvious' - catch
everything !  This solution is very expensive, because it means we
use meta-call for everything.  There must be a better way ...

The solution we adopted in ICP is to consider undefined predicates as
interrupts rather than errors.  With interrupts, we always know the
exact point of interruption and we have the option to continue
execution.  This is more general than the above, because we can get
the same behaviour by making the default action of the interrupt
handler to throw error 403 (undefined predicate error).  Of course,
we can also do other things like load/consult files which may contain
definitions for the culprit goal, or even arbitrarily succeed, fail
or bind the culprit goal interactively to continue the execution.
The interrupt handler just described is exactly the default action in
ICP.

This default action may be changed by setting the `undefined' property
of the thread.  Each thread has a thread identifier which may be
retrieved by the call
@example
	thread(-Id)
@end example
By default, this property is not set and the interactive handler is
invoked whenever an undefined predicate is encountered.  If the
property is set as follows :
@example
	set_prop(Id, undefined, fail)
@end example
then all undefined predicates are assumed to fail silently.
@example
	set_prop(Id, undefined, warning)
@end example
causes all undefined predicates to fail, but a warning message
is displayed.
@example
	set_prop(Id, undefined, error)
@end example
treats all undefined predicates as errors, which means that an error
is thrown to the most recent catch point.  Note that in this case the
exact location of the undefined predicate will be lost as explained
previously.

Even if we installed our own @code{user_error/2}, undefined predicates
will not call the new error handler because undefined predicates are
not (by default) errors.  To invoke the
user-defined error handler, you will
need to specify undefined predicates as being errors.  We do this
like so :
@example
	thread(Id), set_prop(Id, undefined, error)
@end example
as discussed previously.

Now this invokes our error handler as expected.  However, we still
have the problem of the catch point not being where the undefined
predicate occurred.  (This may not be a problem if the programmer
has taken care to put catch calls around all potentially undefined
predicates.  In this case, no more action is required.)   What we
need is not just a replacement for the error handler, we need a
replacement for the `undefined-predicate-interrupt-handler' too !

This interrupt handler is specified using the @code{user_undefined/1} hook.

@item user_undefined(@var{+Goal})
@upindex user_undefined/1
This is a hook to allow users to trap undefined predicate errors.
The argument is the undefined goal.  The user may specify actions
to take and perhaps retry the goal.  Note that this is independent
of any error handler since undefined predicates are not errors unless
explicitly thrown as in the example below.
@example
user_undefined(Goal) :-
	functor(Goal, Pred, Arity),
	writeseqnl(['missing predicate :', Pred/Arity]),
	throw(403).	/* error code for undefined predicate */
@end example

@item system_undefined(@var{+Goal})
@findex system_undefined/1
For convenience, access to the system undefined predicate interrupt
handler is provided.  This will typically be called from a
@code{user_undefined/1} relation.

@item halt
@findex halt/0
Exits ICP.

@item abort
@findex abort/0
Aborts execution and, after warning the user, returns control to the top-level
query handler.

@item op(@var{+Priority},@var{+Type},@var{+Opname})
@findex op/3
Declares an operator with name @var{Opname}.  @var{Priority} should be
an integer between 1 and 1200, which will determine the operator
precedence when the operator's arguments are themselves operator
expressions. The lower the priority number, the tighter binding the
operator.  The type argument is one of

@table @code
@item fx
non associative prefix operator. The subexpression forming the 
argument of the operator must have lower precedence than the operator itself.
@item fy
associative prefix operator. The subexpression forming the argument 
can have the same precedence as the operator.
@item xf
non associative postfix operator.
@item yf
associative postfix operator.
@item xfx
non associative infix operator.
@item xfy
right-associative infix operator.
@item yfx
left-associative infix operator.
@end table

Note that an operator may be declared to be prefix, postfix and
infix all at the same time, though this is confusing and not
recommended.

The precedence and type of an operator may be changed by re-declaring
it.  To remove an operator, re-declare it with precedence 0 for
the relevant type.

When several operators have the same declaration, the @var{Opname}
argument can be a list of operator names.

@item current_op(@var{?Priority},@var{?Type},@var{?Opname})
@findex current_op/3
If @var{Opname} is an atom, the call can be used to find the priority and
type of a given operator. If @var{Opname} is a variable then the call to
current_op may be used to backtrack through operators, and in this case if
either @var{Type} or @var{Priority} is an atom then only operators of that
@var{Type} and/or @var{Priority} will be retrieved.
@end table

@node ModifyingDatabase, Properties, ExecutionAndError, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Modifying the Database 

@table @code
@item assert(@var{+Clause})
@findex assert/1
Adds the specified @var{Clause} to the database as the last clause of its
procedure.

@item asserta(@var{+Clause})
@findex asserta/1
Adds the specified @var{Clause} to the database as the first clause of its
procedure.

@item assertz(@var{+Clause})
@findex assertz/1
Same as @code{assert/1}.

@item assertx(@var{+Clause},@var{+Index})
@findex assertx/2
Adds the specified @var{Clause} to the database. If Index is positive
then the clause is asserted as the @var{Index}th clause of its
procedure. If @var{Index} is negative then the clause is asserted as the
last but @var{Index}th of its procedure. If @var{Index} is zero, or too
large a positive integer, then the clause is asserted as the last one.
If @var{Index} is too large a negative number then the clause is
asserted as the first one.

@item retract(@var{+Clause})
@findex retract/1
If there is a clause in the data base that matches @var{Clause}, then
that clause is deleted and any variables in @var{Clause} are
instantiated by the match. On backtracking there is an attempt to find
another matching clause.  The search always starts at the beginning of
the list of clauses for the relation name of @var{Clause}. The call
fails when there is no matching clause.

@item retractx(@var{+Name},@var{+Arity},@var{+Index})
@findex retractx/3
If the dynamic predicate @var{Name/Arity} is defined, then one of its
clauses, as specified by index, is deleted. If @var{Index} is positive,
then the @var{Index}th clause of the procedure is deleted. If
@var{Index} is negative then the last but @var{Index}th clause of the
procedure is deleted. If @var{Index} is too large a positive integer
then the last clause of the procedure is deleted. If @var{Index} is
zero, or too large a negative number, then the first clause of the
procedure is deleted.

@item retractall(@var{+Clause})
@findex retractall/1
All the data base clauses which match @var{Clause} are deleted, with any
variables in @var{Clause} left uninstantiated. @code{retractall/1} always 
succeeds.

@item abolish(@var{+Pred})
@findex abolish/1
If predicate @var{Pred} is currently defined, then it becomes undefined. 
This can be used to remove definitions for both static and dynamic 
predicates.

@item kill(@var{+Pred})
@findex kill/1
If predicate @var{Pred} is currently defined, then it becomes undefined.
If predicate @var{Pred} is currently defined by a static segment, then
all the predicates which are currently defined by that segment become
undefined.  This gives an easy method to remove all associated
predicate definitions e.g. normally all predicates defined in the same
file.

@item save(@var{+Pred},@var{+File})
@findex save/2
Saves the object code for predicate(s) @var{Pred} to file @var{File}. 
@var{Pred} is either a single predicate or a list of predicates. Only 
those predicates which are defined are saved.

@item save(@var{+Pred},@var{+File},@var{+Mode})
@findex save/3
Opens the file @var{File} in @var{Mode} mode and
saves the object code for predicate(s) @var{Pred}.
@var{Pred} is either a single predicate or a list of predicates. Only 
those predicates which are defined are saved.  @var{Mode} must be
either @code{write} or @code{append}.
@end table

@node Properties, Metalogical, ModifyingDatabase, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Property Management 

@table @code
@item set_prop(@var{+Object},@var{+Property},@var{?Value})
@findex set_prop/3
Sets a property value; @var{Value} becomes the remembered value of the
property @var{Property} of the object @var{Object}. Any previously
remembered value of the @var{Property} of the @var{Object} is lost.

@item get_prop(@var{+Object},@var{+Property},@var{-Value})
@findex get_prop/3
Retrieves the value of a property; @var{Value} is instantiated with the
current value of the @var{Property} of @var{Object}. If there is no
remembered value, the call fails.

@item del_prop(@var{+Object},@var{+Property})
@findex del_prop/2
Removes a property value; the remembered @var{Property} value of
@var{Object} is forgotten. A subsequent call to
@code{get_prop(Object,Property,Value)} will fail. @code{del_prop/2} does
nothing and succeeds if there is no such @var{Object} or @var{Property}.

@item del_props(@var{+Object})
@findex del_props/1
Deletes all properties for a symbol; All the property-value pairs for the
given @var{Object} are forgotten.

@item del_cons(@var{+Property})
@findex del_cons/1
Deletes all symbol values for a property. All the property-value pairs
for the given @var{Property} are forgotten.

@item remember(@var{+Atom},@var{?Value})
@findex remember/2
Stores @var{Value} as the currently stored value of @var{Atom}. Any
previously assigned value is lost.

@item recall(@var{+Atom},@var{-Value})
@findex recall/2
@var{Value} is instantiated with the currently stored value of atom.
@code{recall/2} fails if @var{Atom} has no currently stored value.

@item default_prop(@var{+Atom},@var{-Value},@var{?Default})
@findex default_prop/3
@var{Value} is instantiated with the currently stored value of
@var{Atom}, if there is one. It will be instantiated with @var{Default}
if there is no currently stored value.

@item forget(@var{+Atom})
@findex forget/1
Deletes the stored value associated with @var{Atom}. A @code{recall/2}
on @var{Atom} will now fail.  A call to forget always succeeds, even if
there is no stored value.

@item get_cons(@var{+Property},@var{-List})
@findex get_cons/2
@var{List} is bound to to the list of all the atoms that currently have a
value for the property @var{Property}.

@item get_props(@var{+Object},@var{-List})
@findex get_props/2
@var{List} is bound to the list of all the names of the properties currently
associated with @var{Object}.

@item list_props(@var{+Object},@var{-List})
@findex list_props/2
@var{List} is bound to the list of all the `Property=Value' pairs currently
associated with @var{Object}.
@end table

@node Metalogical, GrammarRules, Properties, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Metalogical Primitives 

@table @code
@item ntpl(@var{+Len},@var{-Tpl})
@findex ntpl/2
@var{Tpl} is instantiated to the most general tuple having @var{Len} as its
positive (>=1) arity, that is, a tuple with distinct variables for its
functor and all of its arguments.
@example
@cartouche
| ?- ntpl(3, Tpl).

Tpl = _125(_126,_127) 
@end cartouche
@end example

@item tohollow(@var{+Ground},@var{-Hollow},@var{+Varnames})
@findex tohollow/3
@var{Varnames} a list of atoms. Only the atoms in the @var{Varnames}
list of atoms are replaced by variables in the @var{Hollow} copy of
@var{Ground}.  Any atom can be on the @var{Varnames} list. The main use
of this call is to convert a term and its associated list of variable
names that has been read in using @code{gread/1}, @code{gread/2} or
@code{gread/3} into a hollow term that can be used in an evaluation.
@example
@cartouche
| ?- tohollow(foo(a,b,c), Hollow, [a,c]).

Hollow = foo(_175,b,_178) 
@end cartouche
@end example

@item tohollow(@var{+Ground},@var{-Hollow},@var{+Varnames},@var{-Vars})
@findex tohollow/4
Essentially the same as the above three argument use except that the
list of variables in @var{Hollow} that have replaced the atoms on
@var{Varnames} is also returned. The i@emph{th} variable on @var{Vars}
is the replacement for the i@emph{th} variable name on @var{Varnames}.
This is useful if you want to subsequently output bindings for these
variables using the original variable names.
@example
@cartouche
| ?- tohollow(foo(a,b,c), Hollow, [a,c], Vars).

Hollow = foo(_189,b,_192)
Vars = [_189,_192] 
@end cartouche
@end example

@item toground(@var{?Hollow},@var{-Ground})
@findex toground/2
Simple use to convert any term into a variable free term. @var{Ground}
is bound to a copy of @var{Hollow} in which all the variables are
replaced by new atoms beginning with underscores. Different variables
are replaced by different underscore names, and there will be no clash
with any atom that begins with underscore which already appears in
@var{Hollow}.
@example
@cartouche
| ?- toground(foo(A,B,C), Ground).

Unbound variables : A, B, C
Ground = foo('_0','_1','_2') 
@end cartouche
@end example

@item toground(@var{?Hollow},@var{-Ground},@var{-Varnames})
@findex toground/3
@var{Varnames} will be bound to the list of all the underscore variable
names that have been used to replace variables in @var{Hollow}.
@example
@cartouche
| ?- toground(foo(A,B,C), Ground, Varnames).

Unbound variables : A, B, C
Ground = foo('_0','_1','_2')
Varnames = ['_0','_1','_2'] 
@end cartouche
@end example

@item toground(@var{?Hollow},@var{-Ground},@var{-Vars},@var{-Varnames})
@findex toground/4
Same as the three argument use except that the
corresponding list of the replaced variables is also returned as the binding
for @var{Vars}.

If there are more variables in @var{Hollow} than given in @var{Vars},
new underscore names are given to the extra variables.  More generally,
the elements of @var{Vars} can be any terms. Non-variable terms on
@var{Vars}, and the corresponding atoms on @var{Varnames} are ignored -
but the lists must still be of the same length. This relaxation allows
lists of names and variables returned by some previous use of
@code{tohollow/3} or @code{tohollow/4} to be used as arguments to
@code{toground/4} without having to remove variables that may have been
bound by the intervening evaluation.
@example
@cartouche
| ?- toground(foo(A,B,C), Ground, Vars, Varnames).

Unbound variables : A, B, C
Ground = foo('_0','_1','_2')
Vars = [A,B,C]
Varnames = ['_0','_1','_2'] 
@end cartouche
@end example

@item toground(@var{?Hollow},@var{-Ground},@var{+Vars},@var{+Varnames},@var{-Usednames})
@findex toground/5
@var{Varnames} a list of atoms, @var{Vars} a list of variables which may
appear in @var{Hollow}. The @var{Varnames} list of atoms will be used to
replace the variables of @var{Vars} in @var{Hollow} in the order in
which they are given - the first variable of @var{Vars} is replaced by
the first atom on the @var{Varnames} list, and so on.

Finally, @var{Usednames} is bound to the complete list of the actual variable
names that have been used to replace variables in @var{Hollow}.
@example
@cartouche
| ?- toground(foo(A,B,C),Ground,[A,B,C],['W','X','Y'],Usednames).

Unbound variables : A, B, C
Ground = foo(W,X,Y)
Usednames = [W,X,Y] 
@end cartouche
@end example

@item varsin(@var{?Term}, @var{-Vars})
@findex varsin/2
@var{Vars} is a list of the variables appearing in term @var{Term}
@example
@cartouche
| ?- varsin((foo(X,Y) :- bar(X,Y,1,Z)), Vars).

Unbound variables : X, Y, Z
Vars = [X,Y,Z]
@end cartouche
@end example

@item forall(@var{+Gen},@var{+Test})
@findex forall/2
This call succeeds if for all the solutions of @var{Gen}, @var{Test} is
true.
@example
@cartouche
| ?- forall(member(X, [1,2,1,3,5,2,-1]), X<3).

no
| ?- forall(member(X, [1,2,1,3,5,2,-1]), write(X)). 
121352-1
Unbound variable : X 
@end cartouche
@end example

@item findall(@var{?Term},@var{+Call},@var{-List})
@findex findall/3
@var{List} will be unified with a list of instantiations of @var{Term}, one
for each successful evaluation of @var{Call}. 
@example
@cartouche
| ?- findall(X, (member(X, [1,2,1,3,5,2,-1]), X < 3), List).

Unbound variable : X 
List = [1,2,1,2,-1] 
@end cartouche
@end example

The instantiations of term correspond to the different solution bindings
for the variables in @var{Call}. At the end of the evaluation no
variable in @var{Call} will be bound. All the `local' variables in
@var{Call}, the variables which do not appear in @var{Term}, or in any
other condition in the clause or query in which the @code{findall/3} is
used, are implicitly existentially quantified.  All `global' variables
of @var{Call}, variables that are also used in other conditions in the
clause or query, should be bound to variable free terms before the
@code{findall/3} is evaluated.

Note that @code{findall/3} is faster then @code{bagof/3} (see below)
and should be used instead of @code{bagof/3} when there will be no unbound
global variables in the @var{Call} for which solutions are to be found.
@example
@cartouche
| ?- findall(Y, (member(X, [1,2]), Y is X+1), List).

Unbound variables : X, Y
List = [2,3] ;

no
@end cartouche
@end example

@item bagof(@var{?Eterm},@var{+ExistentialCall},@var{?List})
@findex bagof/3
@var{ExistentialCall} must be a term of the form
@code{@var{v1}^@var{v2}^@dots{}@var{vk}^@var{Call}} where @var{Call} is
a call term, and @code{@var{v1},@dots{},@var{vk}} (k>=0) are variables
in @var{Call} (when k=0 just the @var{Call} is given).  At the time of
the call, @var{Call} will generally contain variables.  The variables in
@var{Call} that are not in either @var{Eterm} or the sequence
@code{@var{v1},@dots{},@var{vk}} of variables preceding @var{Call} are
the global variables of the @code{bagof/3} call.
@code{@var{v1},@dots{},@var{vk}} are the existentially quantified
variables of @var{Call}.

@code{bagof/3} partitions the list of all the values of @var{Eterm} for
all the solutions of @var{Call} by different solution values for these global
variables.

That is, suppose that in the space of all the successful evaluations of
@var{Call} there are @emph{n} different sets of bindings for its global
variables.  Then @code{bagof/3} will backtrack giving @emph{n} different
answers.  Each answer will comprise a set of bindings for the global
variables, and a corresponding value for @var{List} which comprises the
instances of @var{Eterm} for different solutions of @var{Call} that make
this assignment to the global variables.
@example
@cartouche
| ?- bagof(Y, (member(X, [1,2]), Y is X+1), List).

Unbound variable : Y 
X = 1
List = [2] ;

Unbound variable : Y 
X = 2
List = [3] ;

no
| ?- bagof(Y, X^(member(X, [1,2]), Y is X+1), List).

Unbound variables : X, Y
List = [2,3] ;

no
@end cartouche
@end example

@item setof(@var{?Eterm},@var{+ExistentialCall},@var{?List})
@findex setof/3
Same as @code{bagof/3} except that the bindings for @var{List} will be
ordered lists of terms without duplicates. The terms are ordered by the
@code{@@</2} primitive as a list of increasing terms.
@example
@cartouche
| ?- bagof(Y, X^(member(X, [2,1,2,3,0,4]), Y is X+1), List).

Unbound variables : X, Y
List = [3,2,3,4,1,5] 

| ?- setof(Y, X^(member(X, [2,1,2,3,0,4]), Y is X+1), List).

Unbound variables : X, Y
List = [1,2,3,4,5] 
@end cartouche
@end example

@item map(@var{+Rel},@var{+Inlist})
@findex map/2
For each use of @code{map/2}, the term @var{Rel} may be either a relation
name or a call term of the form reln(arg1, @dots{}, argn) whose principal
functor reln is a relation name.

If @var{Rel} is a unary relation name, this call will test if all the
elements of a list @var{Inlist} satisfy @var{Rel}.  If @var{Rel} is a
compound term of the form @code{reln(@var{Arg1},@dots{},@var{Argn})}
then the call tests if all the elements @var{El} of the list @var{Inlist}
satisfy @code{reln(@code{Arg1},@dots{},@var{Argn},@var{El})}.

@item map(@var{+Rel},@var{?Inlist},@var{?Outlist})
@findex map/3
If @var{Inlist} is given, @code{map/3} will produce a list @var{Outlist}
such that each element of @var{Outlist} is in the relation @var{Rel} to
the corresponding element of @var{Inlist}. Alternatively, @code{map/3}
may be used to check that a given @var{Outlist} is in this relationship
to @var{Inlist}.

@item map(@var{+Rel},@var{+Inlist},@var{+Invalue},@var{?Outvalue})
@findex map/4
The given @var{Rel} is applied to `accumulate' the elements of
@var{Inlist} using @var{Invalue} as the initial value of the cumulated
term.  The variable @var{Outvalue} is bound to the final cumulated term.

@item map(@var{+Rel},@var{+Inlist},@var{+Outlist},@var{+Invalue},@var{?Outvalue})
@findex map/5
The given @var{Rel} is applied both to produce an @var{Outlist} from
@var{Inlist}, and to `accumulate' the elements of @var{Inlist} using
@var{Invalue} as the initial value of the cumulated term.
@end table

@node GrammarRules, ListHandling, Metalogical, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Transformations on Reading
There are two forms of program transformations which can be done by ICP
when reading in files.

The first is using @code{term_expansion/2} is based on a clause by
clause transformation and is primarily used for converting grammar
rules.  The implementation of grammar rules is the same as that of
Quintus Prolog @cite{Quintus Prolog Development Environment}, Quintus
Computer Systems, Inc., Mountain View, California, USA.  The grammar
rule translator used is based on a public domain program written by
Richard O'Keefe.

The second method allows users to define a complete transformation on a
file determined by the file name extension.

@menu
* Dcg::                         Definite Clause Grammars 
* FileTrans::                   File Transformations
@end menu

@node Dcg, FileTrans,  , GrammarRules
@comment  node-name,  next,  previous,  up
@subsection Definite Clause Grammars 
A grammar rule takes the form
@example
head --> body
@end example

@table @code
@item expand_term(@var{+Term1}, @var{-Term2})
@findex expand_term/2
This predicate is used by @code{consult/1} and @code{compile/1} 
to determine the transformation of terms before they are asserted or 
compiled. @var{Term1} is the input term and @var{Term2} the output term.
By default, only terms corresponding to grammar rules are transormed; in 
all other cases @var{Term2} is identical to @var{Term1}. This 
performance may be changed if the user predicate @code{term_expansion/2} 
is defined.

@item phrase(@var{+Phrase}, @var{?List})
@findex phrase/2
This predicate determines whether a list @var{List} is a phrase of type 
@var{Phrase}

@item phrase(@var{+Phrase}, @var{?List}, @var{?Rest})
@findex phrase/3

@item 'C'(@var{?S1}, @var{?Terminal}, @var{?S2})
@findex 'C'/3
This predicate is used in expessing grammar rules and is defined by the 
clause
@example
'C'([X|S], X, S).
@end example

@item term_expansion(@var{+Term1}, @var{-Term2})
@upindex term_expansion/2
The standard transformation of terms before compilation or consultation 
can be overridden by defining this predicate. It can be used to define 
different `sugared' syntaxes.

@item query_expansion(@var{+Term1}, @var{-Term2})
@upindex query_expansion/2
A user query may be transformed before calling the goal by defining this
predicate. If it succeeds, @var{Term2} will be executed but the variable
bindings will be printed as usual upon completion.
@end table

@node FileTrans,  , Dcg, GrammarRules
@comment  node-name,  next,  previous,  up
@subsection File Transformations

The transformations in the previous section are at the clause level.
A more powerful method of transformation is at the level of files,
since this allows contextual transformation of clauses.  For example,
when writing a preprocessor for an object-oriented extension to Prolog,
we may wish to generate default inheritance clauses for objects
depending on whether the object has an explicit superclass defined
in the same file.  This requires a global view of all the clauses
in a file rather than the simple clause-level transformations.

File-level transformations are specified by defining a new file
extension type and a user hook relation to read (and transform) the
new file type.   The user hook relation is either @code{user_consult/3}
or @code{user_compile/3}.
An example of the use of these predicates is shown in
@file{$ICP_INSTALLDIR/skilaki/source/icp_comp.pl}.

@table @code
@item user_file_type(@var{?Ext}, @var{?Type})
@upindex user_file_type/2
This declaration allows the user to define an alternative compilation or
consultation for files with the extension @var{Ext}. The term @var{Type}
may be used to select which paticular transformations to perform on
reading the file.

@item read_prolog_file(@var{-Preds})
@findex read_prolog_file/1
This predicate reads an entire file using any user-defined hooks,
returning the predicates in the list @var{Preds}.

@item user_consult(@var{+Type}, @var{+FileName}, @var{-Preds})
@upindex user_consult/3
On consultation, if a @code{user_file_type/2} declaration exists for the
file, the system calls this predicate having already opened the file
@var{FileName} and set current input to it.  This should read and
process the file returning a list of predicates as specified below.
These predicates will then be asserted into the database automatically.

The file may be read using @code{read_prolog_file/1} and post-processed
into the list @var{Preds}.  The intended usage is to allow more
flexible transformations than grammer rules would allow.

@example
@cartouche
user_file_type('.foo', foo_type).

user_consult(foo_type, File, Preds) :-
	read_prolog_file(Source),
	process(Source, Preds).
@end cartouche
@end example

@item user_compile(@var{+Type}, @var{+FileName}, @var{-Preds})
@upindex user_compile/3
As @code{user_consult/3} but  @var{Preds} are automatically compiled
rather than asserted.
@end table

In all the above predicates, 
@var{Preds} is a list of terms of the form
@code{pr(@var{Pred}/@var{Arity},@var{List})} where @var{Pred} is
the predicate name (an atom), @var{Arity} is an integer and
@var{List} is a list
representing the clauses for this predicate. Each term in this list is
of the form @code{@var{VarNames}-@var{GroundClause}}, where @var{VarNames}
is a list of atoms representing the variable names in the ground clause
@var{GroundClause}.

@node ListHandling, StringsAndAtoms, GrammarRules, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section List Handling

@table @code
@item qsort(@var{+List},@var{-Sorted},@var{+Test})
@findex qsort/3
Test must be the name of a binary relation. The call succeeds if @var{Sorted}
can be unified with the result of sorting @var{List} with respect to
@var{Test}.

@item append(@var{?List1},@var{?List2},@var{?List3})
@findex append/3
Succeeds if @var{List3} is @var{List1} followed by @var{List2}.

@item member(@var{?El},@var{?List})
@findex member/2
Succeeds if @var{El} is a member of list @var{List}.  This may be
used to backtrack over the whole list.

@item memberchk(@var{?El},@var{?List})
@findex memberchk/2
Succeeds if @var{El} is a member of list @var{List}.  This is different
from @code{member/2} since it does not backtrack.

@item on(@var{?El},@var{?List})
@findex on/2
Same as @code{member/2}

@item occ(@var{?X},@var{?L})
@findex occ/2
Succeeds if term @var{X} occurs in unsafe list @var{L}. An unsafe list 
is one which has a variable as the tail. If @var{X} is not
in @var{L} then it is put there.

@item no_occ(@var{?X},@var{?L})
@findex no_occ/2
Succeeds if term @var{X} is not in unsafe list @var{L}.

@item remove(@var{?Item},@var{-List},@var{-Remainder})
@findex remove/3
Succeeds if @var{Remainder} is the list @var{List} with the element
@var{Item} removed. If @var{Item} does not occur in @var{List}, the call to
remove fails. If @var{Item} occurs in @var{List} more than once, subsequent
occurrences will be removed on backtracking.

@item delete(@var{?Item},@var{-List},@var{-Remainder})
@findex delete/3
Same as @code{remove/2}

@item reverse(@var{?List},@var{?Revlist})
@findex reverse/2
Succeeds if @var{Revlist} is the list @var{List} with the order of its
elements reversed.
@end table

@node StringsAndAtoms, Threads, ListHandling, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section String and Atom Handling 

@table @code
@item name(@var{?X},@var{?L})
@findex name/2
@var{X} is that atom or integer such that @var{L} is a list of the
ASCII codes for its printed representation.
@example
@cartouche
| ?- name(hello, List), name(Hello, List).

List = [104,101,108,108,111]
Hello = hello 

| ?- A1='12', name(A1, List), name(A2, List).

A1 = '12'
List = [49,50]
A2 = 12 

| ?- A1='12', name(A1, List), name(A2, List), A1=A2.

no

| ?- A1=12, name(A1, List), name(A2, List).

A1 = A2 = 12
List = [49,50]

@end cartouche
@end example

@item atom_chars(@var{?X},@var{?L})
@findex atom_chars/2
@var{X} is the atom such that @var{L} is a list of the
ASCII codes for its printed representation.
@example
@cartouche
| ?- A1='12', atom_chars(A1, List), atom_chars(A2, List).

A1 = A2 = '12'
List = [49,50] 

| ?- A1='12', atom_chars(A1, List), atom_chars(A2, List), A1=A2.

A1 = A2 = '12'
List = [49,50] 

| ?- A1=12, atom_chars(A1, List).

no

@end cartouche
@end example

@item number_chars(@var{?X},@var{?L})
@findex number_chars/2
@var{X} is the number such that @var{L} is a list of the
ASCII codes for its printed representation.

@example
@cartouche
| ?- A1='12', number_chars(A1, List).

no

| ?- A1=12, number_chars(A1, List), number_chars(A2, List).

A1 = A2 = 12
List = [49,50]

@end cartouche
@end example

@item numbervars(@var{?Term}, @var{+Start}, @var{-End})
@findex numbervars/3
Transforms each of the variables in @var{Term} into ground terms of the
form @code{'$Var'(@var{N})} where @var{N} is an integer greater than or
equal to the integer @var{Start}.
@example
@cartouche
| ?- numbervars(a(X,Y), 0, End), display(a(X,Y)).
a($VAR(0),$VAR(1))
X = A
Y = B
End = 2 
@end cartouche
@end example
The first variable in @var{Term} gets @var{N} equal to @var{Start} 
while the second distinct variable gets @var{Start}+1 and so on. 
@var{End} is the value of @var{N} when the last variable has been 
grounded.

@item concat(@var{?X},@var{?Y},@var{?Z})
@findex concat/3
@var{Z} is instantiated to the atom formed by concatenating the printed
representation of @var{X} with that of @var{Y}. The limit of the size of
a single atom is 255 characters. If you try to construct a new atom with
more than 255 characters the extra trailing characters will simply be
ignored.
@example
@cartouche
| ?- concat(foo, bar, Full).

Full = foobar 

| ?- concat(Start, bar, foobar).

Start = foo 

| ?- concat(foo, End, foobar).

End = bar 
@end cartouche
@end example

@item concat_atom(@var{?List},@var{?Atom})
@findex concat_atom/2
This primitive concatenates a list of constants @var{?List} into a single
atom @var{?Atom}.  The constants may be numbers or atoms.

@item pname(@var{?T},@var{?N})
@findex pname/2
This primitive converts between a Prolog term and an atom representing its
print name.  If @var{T} is bound, @var{N} is bound to the atom of the print
name of @var{T}.

If @var{N} is bound, @var{T} is bound to the term whose print name is
@var{N}.
@example
@cartouche
| ?- pname(a(X, 2), N).

Unbound variable : X 
N = 'a(_0,2)' 

| ?- pname(T, 'a(X, 2)').

T = a(_243,2) 
@end cartouche
@end example

@item pname(@var{?T},@var{?N},@var{?VNames},@var{?Vars})
@findex pname/4
Same as @code{pname/2} but with better control of the print name of
variables.  If @var{Vnames} is given is a variable, @var{N} is bound to
the atom of the print name of @var{T}, with each variable in list
@var{Vars} being represented by the corresponding atom in list
@var{VNames}.  In the second form, @var{T} is bound to the term whose
print name is @var{N}, @var{Vars} is bound to a list of variables found
in the term and @var{VNames} is bound to a list of the corresponding
print names.
@example
@cartouche
| ?- pname(a(X, 2), N, ['V1'], [X]).

Unbound variable : X 
N = 'a(V1,2)' 

| ?- pname(T, 'a(X, 2)', VNames, Vars).

T = a(_273,2)
VNames = ['X']
Vars = [_273] 
@end cartouche
@end example
This predicate is useful for meta-programming.

@item copy_term(@var{?Term}, @var{?CopyTerm})
@findex copy_term/2
Creates a copy of term @var{Term} with new variables but preserving bindings
@example
@cartouche
| ?- copy_term(a(X, b(G,X)), Copy).

Unbound variables : G, X
Copy = a(_141,b(_146,_141)) 
@end cartouche
@end example

@item gensym(@var{+Prefix}, @var{-Atom})
@findex gensym/2
Creates an atom @var{Atom} whose prefix is @var{Prefix} and whose suffix is an
integer. Successive calls to @code{gensym/2} are guaranteed to give
different atoms.
@example
@cartouche
| ?- gensym(a,Atom1), gensym(a,Atom2), gensym(b, Atom3).

Atom1 = a1
Atom2 = a2
Atom3 = b1 
@end cartouche
@end example
@end table

@node Threads, Parlog, StringsAndAtoms, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Threads 

In the description below, a pipe is a communication channel between two
threads or processes.  A pipe has two end which are called ports.  An output
port is where terms enter the pipe (i.e. written out by a thread), and an
input port is where the terms leave the pipe (i.e. read in by a thread).

@table @code
@item fork(@var{+Goal})
@findex fork/1
Forks a child thread to run @var{Goal}.  The current thread is not suspended.
The child thread must wait for a @code{resume} call or a time slice
to start executing.

@item fork(@var{+Goal},@var{-Th})
@findex fork/2
Creates a child thread to run @var{Goal}, a thread identifier @var{Th} is
returned. The current thread is not suspended. The child thread must wait for
a @code{resume} call or a time slice to start executing.

@item qprolog(@var{+Goal})
@findex qprolog/1
Similar functionality to @code{fork/1}, but without the overhead of
creating a new thread.
The @var{Goal} is executed in a background reserved thread.  Use this in
preference to @code{fork/1} only when @var{Goal} is simple, since complex
queries will delay other calls to @code{qprolog/1}.

@item new_thread(@var{-Th})
@findex new_thread/1
This creates a new thread structure and binds @var{Th} to an integer
identifier for the thread.  This low-level primitive is typically not used by
the user directly.

@item thread(@var{?Th})
@findex thread/1
Returns the identifier of the current thread.

@item kill_thread(@var{+Th})
@findex kill_thread/1
Kills the specified thread and reclaims the memory space.

@item suspend
@findex suspend/0
Sets the status of the current thread to unrunnable.  Note that this does not
immediately suspend the thread, but merely removes it from the run
queue.  The thread must be explicitly named in order to resume it.

@item suspend(@var{+Th})
@findex suspend/1
Sets the status of the thread @var{Th} to unrunnable.  This removes
the specified thread from the run queue.  The thread must be
explicitly resumed using @code{resume/1} to continue executing.

@item resume
@findex resume/0
Non-specific scheduler.  The next thread in the circular run queue resumes
execution.

@item resume(@var{+Th})
@findex resume/1
Resume execution of the specified thread.  This is the only way to change
the status of a thread from unrunnable to runnable.
If @var{Th} is 0, the next runnable thread is resumed.
@code{resume/1} returns an error if @var{Th} is not a currently valid
thread.

@item timeslice(@var{+N})
@findex timeslice/1
If N is the integer 0, time-slicing is switched off.
This has the effect of preventing other runnable threads from
executing, thus giving the current thread exclusive use of the processor.
If N is any other integer, time-slicing is resumed.  This primitive
is used when atomicity is required or when critical code regions are
entered.

@item pipe(@var{-OP}, @var{-IP})
@findex pipe/2
Creates a new pipe and binds @var{OP} to the output end and @var{IP} to
the input end of the pipe.  Terms which are written to @var{OP} may be
read from @var{IP}.  The structure of a port term is
@code{port(@var{N})} where @var{N} is an integer.

@item write_pipe(@var{+OP}, @var{?T})
@findex write_pipe/2
Outputs the term @var{T} to the output port @var{OP}.  @var{OP} must be an
output port owned by the current thread, otherwise the primitive fails.
Ownership of a port is automatically set to the current thread if there is no
current owner.  Note that creation of a pipe does not set ownership for the
ports.  Thus a pipe may be created by one thread and used by another thread.
If any thread is suspended on a read, @code{write_pipe/2} wakes it after
@var{T} is written out to the pipe.

@item look_pipe(@var{+IP}, @var{-T})
@findex look_pipe/2
Copies a term @var{T} from the input port @var{IP}.  The term is not removed
from the pipe.  @var{IP} must be an input port owned by the current thread,
otherwise the primitive fails.  Ownership of a port is automatically set to
the current thread if there is no current owner.  The pipe is `locked' before
the term is read.  This is to prevent multiple readers accessing the pipe
simultaneously.  The lock is not released by this primitive (see
@code{commit_read/1}).  @code{look_pipe/2} suspends if the port is
already locked or if the pipe is empty.  If the output port of the pipe is
closed, @code{look_pipe/2} binds @var{T} to the constant @code{end_of_file}.

@item commit_read(@var{+IP})
@findex commit_read/1
Removes the term previously read by @code{look_pipe/2} from the pipe and
unlock the pipe.  @var{IP} must be an input port owned by the current thread,
otherwise the primitive fails.  @code{commit_read/1} fails if the pipe is
not locked (i.e. no previous @code{look_pipe/2}).

@item read_pipe(@var{+IP}, @var{?T})
@findex read_pipe/2
Reads a term @var{T} from the input port @var{IP}.  Semantically, this is
equivalent to @code{look_pipe(@var{IP},@var{T})} followed sequentially by
@code{commit_read(@var{IP})}.

@item empty_pipe(@var{+IP})
@findex empty_pipe/1
Is true if pipe @var{IP} has no data to be read. %LOOK

@item is_iport(@var{+Port})
@findex is_iport/1
Is true if @var{Port} is an input port.

@item is_oport(@var{+Port})
@findex is_oport/1
Is true if @var{Port} is an output port.

@item unlock(@var{+Port})
@findex unlock/1
Unlocks a pipe which has been locked by a previous @code{look_pipe/2}.
The port must be owned by the current thread, otherwise the primitive fails.
This is used in the case where the term read is not the one expected.  The
pipe is unlocked so that another thread can re-read the same term.

@item close_port(@var{+Port})
@findex close_port/1
Closes the specified port.  The port must be owned by the current
thread, otherwise the primitive fails.  @code{close_port/1} suspends if
the pipe is locked and fails if the port has a suspended operation
pending.  If an output port is closed, subsequent (and suspended) reads
from the input port will return @code{end_of_file}.  Closing an input
port does not affect the output port.  If both ports are closed, space
used for the pipe is reclaimed.

@item release_port(@var{+Port})
@findex release_port/1
Releases ownership of the port to allow other threads to use it.  The port
must be owned by the current thread, otherwise the primitive fails.
@code{release_port/1} suspends if the pipe is locked.

@item shell
@findex shell/0
This starts a read-eval-print loop in a new window to handle Prolog queries.
It is usually used as the goal to be executed in a new forked thread.

@item exit
@findex exit/0
Kills the current thread and resumes another runnable thread, if any. This is
usually used to exit a shell as started above a la Unix.
@end table

@node Parlog, Miscellaneous, Threads, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Prolog - Parlog Interface 

@table @code
@item xparlog
@findex xparlog/0
Starts the parlog thread and redirects its console input and output to a new
window under X11.
It also opens a pipe for
communication between the prolog and parlog processes.
The new window may be used to type parlog queries
directly or you may use @code{parlog/1} to call it from prolog.
Only one parlog thread may be started.

@item parlog
@findex parlog/0
Switches the query handler from prolog to parlog.  The first time that
@code{parlog/0} is called, a parlog thread is started and a pipe is opened
for communication between the prolog and parlog processes.  Subsequent
calls just switch to the existing parlog thread.  This primitive is
useful when X Windows is not available or if you wish to run ICP in an
Emacs buffer.  To get back to prolog, type the parlog query @code{prolog/0}.

@item parlog(@var{+Goal})
@findex parlog/1
Passes a goal @var{Goal} to the parlog thread to solve.

@item close_parlog
@findex close_parlog/0
Closes the communication port to parlog.
@end table

@node Miscellaneous,  , Parlog, Builtin Predicates
@comment  node-name,  next,  previous,  up
@section Miscellaneous Primitives 

@table @code
@item unix(@var{+A})
@findex unix/1
Execute the atom @var{A} as a unix command.

@item cd(@var{+A})
@findex cd/1
Change current directory to @var{A}.

@item cd
@findex cd/0
Change current directory to the user's home directory.

@item ls
@findex ls/0
Execute the unix command @file{ls} to list the current directory.

@item ls(@var{Dir)}
@findex ls/1
Execute the unix command @file{ls} to list the directory @var{Dir}.

@item pwd
@findex pwd/0
Display the path name of the current directory.

@item edit(@var{+File}, @var{+Editor})
@findex edit/2
Edit the file @var{File} using the editor, @var{Editor}.  If the filename
does not have an extension, the suffix `@file{.pl}' will be added.

@item edit(@var{+File})
@findex edit/1
Edit the file @var{File} using the editor, stored as property
@code{editor} (by default @file{vi}).  If the filename does not have an
extension, the suffix `@file{.pl}' will be added.

@item vi(@var{+File})
@findex vi/1
Edit the file @var{File} using the @file{vi} editor.

@item out_of_date(@var{+File}, Type)
@findex out_of_date/2
Is true if the file @var{File}(@file{.icp}) is older than file
@var{File}(@var{.Type}). The files are can exist anywhere on the current
search path.

@item max(@var{+I},@var{+J},@var{-K})
@findex max/3
@var{K} is bound to the greater of @var{I} and @var{J}.

@item arb_member(@var{?El},@var{?Term})
@findex arb_member/2
Succeeds if @var{El} is a subterm of @var{Term}. This is a deterministic
test.

@item not_arb_member(@var{?El},@var{?Term})
@findex not_arb_member/2
Succeeds if @var{El} is not a subterm of @var{Term}.

@item address(@var{?V},@var{-Address})
@findex address/2
Binds @var{Address} to the heap-address of variable @var{V}.

@item time(@var{-Time})
@findex time/1
Binds @var{Time} to CPU time (in 60ths of a second) since last call.

@item realtime(@var{-Time})
@findex realtime/1
Binds @var{Time} to the time since 00:00:00 GMT, Jan. 1, 1970 measured in
seconds (the Unix epoch).

@item ctime(@var{?Time, ?Year, ?Month, ?Day, ?Hour, ?Minutes, ?Seconds})
@findex ctime/7
If @var{Time} is a number (as returned by realtime/1), binds the remaining
arguments with the corresponding integer representations. Alternatively
if the other arguments are integers, instantiates @var{Time}.

@item statistics(@var{?Keyword}, @var{-List})
@findex statistics/2
This gives various execution statistics. These statistics pertain to the
thread in which the call is issued. For each of the values of
@var{Keyword}, @var{List} is unified with a list of values.

@table @code
@item runtime
@code{List = [@var{Time1},@var{Time2}]} where the times are since the
start of prolog execution and since the last call to @code{statistics/2}
with @code{@var{Keyword} = runtime}. Both times are in milliseconds.

@item garbage_collection
@code{List = [@var{Number},@var{Bytes},@var{Time}]} where @code{Number}
is the number of garbage collections, @var{Bytes} the total number of
bytes collected and @var{Time} the time, in milliseconds, spent doing the
garbage collection.
@end table

@item errno(@var{?Number}, @var{-Message})
@findex errno/2
If @var{Number} is a variable,
instantiates @var{Number} to the `C' error number (@kbd{errno}) of the
underlying system. @var{Message} is the textual message for the error.

If @var{Number} is a number, @var{Message} is the textual message for the error
corresponding to this number.

@item getenv(@var{+EnvName}, @var{-Value})
@findex getenv/2
Gets the value @var{Value} of the Unix environment variable @var{EnvName}.

@item debugicp
@findex debugicp/0
Drops into the WAM-level ICP debugger.

@item noref
@findex noref/0
Displays on @code{user_error} a listing which gives the name and arity of
the currently referenced but undefined static predicates.

@item window_label(@var{+Name})
@findex window_label/1
Sets the name in the xterm title bar to @var{Name}.

@item icon_label(@var{+Name})
@findex icon_label/1
Sets the name in the xterm icon to @var{Name}.

@item get_prolog_flag(@var{+Flag}, @var{-Value})
@findex get_prolog_flag/2
Gets the value,  @var{Value}, of the flag @var{Flag} for the thread in
which the goal appears. The currently supported flags are

@table @code
@item debug
The values can be one of the atoms @code{on}, @code{off}
@item undefined_predicate
The values can be one of @code{fail} @code{warning} @code{error}. The
default is @code{error}.
@end table

@item set_prolog_flag(@var{+Flag}, @var{-Value})
@findex set_prolog_flag/2
Sets the value,  @var{Value}, of the flag @var{Flag} for the thread in
which the goal appears. The currently supported flags are

@item argc(@var{-Number})
@findex argc/1
The number of arguments passed to prolog at initialization. These must
be prefixed by @code{-z}.

@item argv(@var{-List})
@findex argv/1
The list of arguments passed to prolog at initialization. These must
be prefixed by @code{-z}.

@item cursor(@var{+Stream}, @var{?Pos})
@findex cursor/2
If @var{Pos} is a variable, this returns the position in the stream @var{Stream}.
If @var{Pos} is an integer, the stream position is set to its value.

@item shell_escape
@findex shell_escape/0
Prompts the user for a goal to be executed.  This is a useful menu
option to provide so that queries can be made from deep
inside a user program.

@item get_path(@var{-PathList})
@findex get_path/1
This predicate returns a list of the directories which will be searched when
prolog is trying to locate a file.

@item set_path(@var{+PathList})
@findex set_path/1
This predicate can be used to set the directories which will be searched when
prolog is trying to locate a file.  @var{PathList} is a list of directories,
each of which is an atom.
@end table

