This is Info file icp.info, produced by Makeinfo-1.55 from the input
file prolog.texi.

This file documents the IC Prolog ][ system version 0.96, dated
28 September 1993.

Copyright (C) 1992,1993 Imperial College, London.  All rights reserved.


File: icp.info,  Node: Top,  Next: Overview,  Prev: (dir),  Up: (dir)

ICP
***

IC Prolog ][ is an implementation of Prolog whose major features include
multiple threads, Parlog, TCP primitives and Mailboxes. It is designed
for the development of distributed applications.  This info file
documents version 0.96, last updated on 28 September 1993.

* Menu:

* Overview::                    Introduction
* Builtin Predicates::          Reference for builtin predicates
* Tcp::                         TCP/IP inter-process communication
* Mailboxes::                   Mailbox inter-process communication
* Foreign Interface::           How to interface to C code
* Tracer::                      Guide to using the Tracer
* Operators::                   Table of pre-defined operators
* Error Codes::                 Error numbers and what they mean
* Low Level::                   Internal primitives (not useful !)
* PredicateIndex::              Index of system predicates
* UserPredicateIndex::          Index of user-definable predicates
* ConceptIndex::                Index of concepts


 -- The Detailed Node Listing --

Overview

* Introduction::                Introduction
* CommandLine::                 Command line Options
* Startup::                     Startup
* Syntax::                      Syntax
* Notation::                    Notation

Syntax

* Integers::                    Integers
* FloatingPoint::               Floating Point Numbers
* Atoms::                       Atoms
* Variables::                   Variables
* Tuples::                      Tuples
* Lists::                       Lists
* CharacterEscaping::           Character Escaping

Builtin Predicates

* 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

Loading, Consulting and Compiling

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

Introduction

* SearchPath::                  The Search Path
* DynamicCode::                 Dynamic Code
* StaticCode::                  Static Code

Input and Output Primitives

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

Arithmetic

* ArithmeticComparison::        Arithmetic Comparison

Term Comparison

* StandardOrderTerms::          The Standard Order on Terms
* TermComparisonPreds::         Term Comparison Predicates

Transformations on Reading

* Dcg::                         Definite Clause Grammars
* FileTrans::                   File Transformations

TCP Interface

* TcpIntro::                    Introduction to TCP/IP
* TcpConnected::                Connection Oriented Protocol
* TcpConnectionless::           Connectionless Oriented Protocol
* TcpMisc::                     Miscellaneous TCP Predicates
* TcpLow::                      Low Level TCP primitives
* TcpEg::                       Simple TCP Examples

Simple TCP Examples

* TcpEgConnected::              Connected Sockets
* TcpEgConnectionless::         Connectionless Sockets
* TcpEgBroadcast::              Broadcast Sockets

Mailbox-based communication model

* MbxIntroduction::             Introduction to Mailboxes
* MailboxServer::               Mailbox Server
* RestrictedAccess::            Restricting Access
* StartingMailboxes::           Starting Mailboxes
* MailboxPrimitives::           Mailbox Primitives

Introduction to Mailboxes

* MessagePeeking::              Message Peeking
* TwowayCommunication::         Two-way Communication
* MultiwayCommunication::       Multi-way Communication

Mailbox Server

* RegisteringMailboxNames::     Registering Mailbox Names

Mailbox Primitives

* MbxInit::                     Opening, Modifying and Closing Mailboxes
* MbxIO::                       Reading and Writing from Mailboxes
* MbxMisc::                     Miscellaneous Mailbox Predicates

Foreign Language Interface

* ForeignPredicates::           Foreign Language Predicates

Foreign Language Predicates

* ForeignComp::


File: icp.info,  Node: Overview,  Next: Builtin Predicates,  Prev: Top,  Up: Top

Overview
********

* Menu:

* Introduction::                Introduction
* CommandLine::                 Command line Options
* Startup::                     Startup
* Syntax::                      Syntax
* Notation::                    Notation


File: icp.info,  Node: Introduction,  Next: CommandLine,  Up: Overview

Introduction
============

ICP is an Edinburgh style prolog based on the WAM. In addition it
includes the following special features.

`threads'
     ICP allows multiple threads in a single process. This allows the
     solving of multiple goals in pseudo parallel, achieved through the
     use of pre-emptive time-slicing.

`parlog'
     ICP includes a parlog engine. A parlog thread can be started and
     facilities are provided for parlog to call prolog and vice versa.

`Logic & Objects'
     Logic & Objects is a object-oriented layer on top of Prolog.

`TCP'
     A TCP interface allows for the communication between processes
     over a communication network.

`Mailboxes'
     Mailbox is a high-level communication model that is simple and yet
     has many more features than TCP.

`user-defined error handling'
     Users may define their own procedures for handling and recovering
     from errors.

`user-defined file types'
     Users may define their own file types and then supply hooks for
     reading and transforming terms in those files.  This is a
     generalisation of term expansion.

Source files are assumed to have the suffix ``.pl'' while compiled
files have the extension ``.icp''. Built in predicates dealing with
these files will automatically append these extensions to files if they
are not present.


File: icp.info,  Node: CommandLine,  Next: Startup,  Prev: Introduction,  Up: Overview

Command line Options
====================

`-s Stack'
     The initial size of the stack can be specified.  The unit is
     K-cells, with the default being 16 (K-cells); e.g. to double the
     size of the stack, specify `-s 32'.

`-h Heap'
     The initial size of the heap can be specified.  The unit is
     K-cells, with the default being 48 (K-cells); e.g. to double the
     size of the heap, specify `-h 96'.

`-f File'
     Uses file `File' (instead of default ~/icp.pl) as the startup file
     for Prolog component of ICP.

`-ff File'
     Uses file `File' (instead of default ~/icp.par) as the
     initialisation file for Parlog component of ICP.

`-n'
     Skips Prolog startup file processing; i.e. does not read ~/.icp.pl.

`-nn'
     Skips Parlog startup file processing; i.e. does not read
     ~/.icp.par.

`-z String'
     `String' is executed by Prolog at startup time.

`-zz String'
     `String' is executed by Parlog at startup time.

`-F Charset'
     `Charset' may be one of `latin1' (default), `greek' or `mac'.  This
     defines the character encoding which categorizes characters into
     upper case, lower case or graphic characters.  This is used to
     determine variable names (beginning with upper case) and unquoted
     atoms (all lower case).

`-b File'
     Allows the selection of an alternative boot file. The boot file
     determines which system files are loaded at start up time and
     initialises the system.  This option is rarely used.


File: icp.info,  Node: Startup,  Next: Syntax,  Prev: CommandLine,  Up: Overview

Startup
=======

When ICP is started it looks for the file `$HOME/.icp.pl' which if
found is consulted.  This is commonly used to declare operators, load
specific foreign code or prolog libraries.  Lines of commands to be
executed at startup time should be preceded by `:-' or `?-'.  `:-' and
`?-' commands may be scattered throughout the file, but the behaviour
is as if all the `:-' commands (in the same order) are at the start of
the file and all the `?-' commands (in the same order) are at the end
of the file.  The clauses in the body of the file are asserted into the
dynamic database.  Commands that write output should specify the stream
explicitly and not to rely on the default current output stream.

After the startup file has been processed, the commands passed from the
command line through -z options are executed.

When the parlog sub-system is started up, it goes through a similar
process using the startup file `$HOME/.icp.par' and the -zz options.
Parlog may be started up in many ways - in the `$HOME/.icp.pl', as a -z
command line option, or as a Prolog query.


File: icp.info,  Node: Syntax,  Next: Notation,  Prev: Startup,  Up: Overview

Syntax
======

The syntax of ICP is compatible with Quintus Prolog (1) `Quintus Prolog
Development Environment', Quintus Computer Systems, Inc., Mountain
View, California, USA.

* Menu:

* Integers::                    Integers
* FloatingPoint::               Floating Point Numbers
* Atoms::                       Atoms
* Variables::                   Variables
* Tuples::                      Tuples
* Lists::                       Lists
* CharacterEscaping::           Character Escaping

---------- Footnotes ----------

(1)  Quintus is a trademark of Quintus Computer Systems Inc., USA


File: icp.info,  Node: Integers,  Next: FloatingPoint,  Up: Syntax

Integers
--------

An integer consists of a sequence of digits optionally preceded by a
minus sign `-'.  These are normally interpreted as base 10 integers.
It is possible to enter integers in other bases (2 through 36).  To
enter an integer in a base other than 10, first enter the base in
decimal, followed by an apostrophe (`'') and then the string of digits.
If a base greater than 10 is used, the characters `a'-`z' or `A'-`Z'
are used to stand for digits 10 through 35.  For example:
     	8'21	= 17 decimal
     	16'FF	= 255 decimal
     	36'Z	= 35 decimal

As a special case, base 0 allows characters to represent their ASCII
codes.  Examples:
     	0'A	= 65
     	0'[	= 91


File: icp.info,  Node: FloatingPoint,  Next: Atoms,  Prev: Integers,  Up: Syntax

Floating Point Numbers
----------------------

A floating point number consists of a sequence of digits with an
embedded decimal point (`.'), optionally preceded by a minus sign (`-')
and optionally followed by an exponent consisting of an upper or lower
case `e' and a signed base 10 integer.  Note that there must be at
least one digit before, and one digit after, the decimal point.


File: icp.info,  Node: Atoms,  Next: Variables,  Prev: FloatingPoint,  Up: Syntax

Atoms
-----

An atom may take any of the following forms:

  1. A sequence of alphanumeric characters (including underscore),
     starting with a lower case letter

  2. A sequence of one or more characters from the set: `# $ & * + - . /
     : < = > ?  \ ^ ` ~'

  3. A sequence of characters delimited by single quotes (`'').  If the
     single quote character is included it must be written twice.

  4. the special atoms `!' `;' or `{}'


File: icp.info,  Node: Variables,  Next: Tuples,  Prev: Atoms,  Up: Syntax

Variables
---------

A variable is a sequence of alphanumeric characters (including
underscore) starting with a capital letter or an underscore (`_').
Variables which only occur once in the clause are called anonymous
variables and may be written as an underscore on its own.


File: icp.info,  Node: Tuples,  Next: Lists,  Prev: Variables,  Up: Syntax

Tuples
------

A tuple is written as functor (which may be any term), followed by a
left bracket `(', followed by 0 or more comma separated terms, and
ending with a right bracket `)'.  Note that the functor is not limited
to being an atom as in the case of Quintus Prolog.  There must be no
whitespace characters between the functor and the left bracket.  The
following are valid ICP tuples:
             foo(X)
             bar()
             3(a,b,c)
             Var(foo,bar)
             person(john,33)(X,Y,Z)

Note that a tuple with 0 arity is not the same as the functor by itself
i.e.  `X() = X' fails.

Atomic functors may be declared as operators which would allow the tuple
to be written without the brackets.  Operators may be declared to be
prefix, postfix or infix.  Infix operators can be further defined as
none, left or right associative.


File: icp.info,  Node: Lists,  Next: CharacterEscaping,  Prev: Tuples,  Up: Syntax

Lists
-----

A list is just a shorthand notation for ``./2'' tuples.  A list is
written as a left square-bracket `[' followed by 0 or more comma
separated terms and ending with a right-square bracket `]'.  The list
may also be written in ``./2'' notation.  e.g. `[1,2,3]' unifies with
`.(1,.(2,.(3,[])))'.  For convenience, a list of ASCII codes may be
written as a string delimited by double-quotes (`"').  e.g.  `"ABC" =
[65,66,67]'.  To include the double-quote character in the string, it
must be written twice.


File: icp.info,  Node: CharacterEscaping,  Prev: Lists,  Up: Syntax

Character Escaping
------------------

In quoted atoms, double-quote delimited lists or base 0 notation, escape
sequences can be used to denote characters.  This is used to avoid
ambiguity and to enter unusual characters.  ICP has the following
escape sequences:

`\a'
     alarm/bell (ASCII 7)

`\b'
     backspace (ASCII 8)

`\t'
     tab (ASCII 9)

`\n'
     newline (ASCII 10)

`\v'
     vertical tab (ASCII 11)

`\f'
     formfeed (ASCII 12)

`\r'
     carriage return (ASCII 13)

`\e'
     escape (ASCII 27)

`\s'
     space (ASCII 32)

`\d'
     delete (ASCII 127)

`\<octal string>'
     the character with ASCII code `<octal string>' base 8.  e.g.
     `\007' is the bell character and `\040' is the space character
     (ASCII 32).

`\^<control char>'
     the character whose ASCII code is the `<control char>' mod 32.
     e.g. `\^P' is `CTL-P'.

`\<layout char>'
     no character, where `<layout char>' is a character with ASCII code
     =< 32 or >= 127.  This is most useful when splitting atoms over two
     lines where the ignored newline character is preceded by a
     backslash.

`\c'
     no character, also all characters up to, but not including, the
     next non-layout character are ignored.

`\<other>'
     the character `<other>', where `<other>' is any character not
     defined above.


File: icp.info,  Node: Notation,  Prev: Syntax,  Up: Overview

Notation
========

Built-in predicates are introduced with a template such as *bag_of*(?X,
+GOAL, -SET) where X, GOAL and SET are the arguments. The significance
of the leading characters is as follows.

`+'
     The argument is a (non variable) input.

`-'
     The argument is an output. The output value is unified with the
     original value.

`?'
     The argument is neither of the above. This might be because the
     argument can be used both as an input and as an output argument,
     or because while the argument is an input, it can be an
     uninstantiated variable.

Often, a tuple or predicate is represented by the term NAME/ARITY,
where NAME is the function symbol and ARITY is the number of arguments
of the term.
             Term            Representation
             ----            --------------
             foo(X,Y)        foo/2
             bar             bar/0
             not Goal        not/1
             1+2             +/2


File: icp.info,  Node: Builtin Predicates,  Next: Tcp,  Prev: Overview,  Up: Top

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


File: icp.info,  Node: Control,  Next: Loading,  Up: Builtin Predicates

Control
=======

`+C1, +C2'
     This is the conjunction operator.  C1 is evaluated and then C2 is
     evaluated.  The conjunction succeeds if and only if both calls
     succeed.

`+C1 ; +C2'
     This is the disjunction operator.  The call succeeds if either C1
     or C2 succeeds. C1 is evaluated first. Only when all possible
     evaluation paths for C1 have been explored will backtracking lead
     to an evaluation of C2.

     A `!/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 `!/0' evaluated within the C1 branch also prevents the use of C2.

`!'
     This is the backtracking control primitive. After it has been
     evaluated in a clause a backtrack to the `!/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 `!/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
     `;/2' and `->/2' for the effect of `!/0' inside these operators.

`call(+GOAL)'
     The call is equivalent to the call GOAL, except where GOAL is
     `!/0' or includes `!/0'.  A `!/0' evaluated inside GOAL only has a
     local effect. It only affects backtracking to find alternative
     solutions to calls that precede the `!/0' within GOAL.

`not +CALL'
     This is the negation as failure operator. The call succeeds if and
     only if CALL fails.

`\+ +CALL'
     Same as `not/1'.

`+TEST -> +CALL'
     This is the conditional evaluation operator. The `->/2' call
     succeeds if and only if TEST succeeds and CALL succeeds. An `if
     ... then ... else' construction may be created by combining the
     conditional evaluation operator with the disjunction operator
     ``;/2'' i.e.
     `TEST -> CALL ; ELSE.'
     As with disjunctions and conjunctions, a `!/0' evaluated in TEST
     or CALL not only has a local effect, but also the same effects as
     a `!/0' evaluated just before the `->/2' call.

`true'
     This call always succeeds.

`otherwise'
     Same as `true/0'.

`fail'
     This call does not match anything and always fails.

`false'
     Same as `fail/0'.

`repeat'
     This call always succeeds and repeatedly succeeds each time the
     evaluation backtracks to the call. It is defined as:

          repeat.
          repeat :- repeat.

`succeed(+CALL)'
     CALL is evaluated and `succeed/1' succeeds, regardless of whether
     CALL succeeded or failed. Its definition is:

          succeed(Call) :-
                  Call,
                  !.
          succeed(Call).

`one(+GOAL)'
     GOAL must be a call term: `one/1' is used to find just one
     solution to GOAL.


File: icp.info,  Node: Loading,  Next: IO,  Prev: Control,  Up: Builtin Predicates

Loading, Consulting and Compiling
=================================

* Menu:

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


File: icp.info,  Node: LoadIntro,  Next: Style,  Up: Loading

Introduction
------------

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


File: icp.info,  Node: SearchPath,  Next: DynamicCode,  Up: LoadIntro

The Search Path
...............

Source files are assumed to have the suffix `.pl' while compiled files
have the extension `.icp'. Many predicates dealing with files will
automatically append these extensions to files if they are not present.
Thus for example the goal
     ?- consult(foo).
will result in the 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
`ICP_PATH'. This must be a colon separated list, for example
     ICP_PATH=.:$HOME/icp/binary:$HOME/icp/source
ICP appends to the user defined path directories in the installation
directory of ICP. If the variable `ICP_PATH' is not set, the search
path is set as if the variable were set to the following value
     ICP_PATH=.:$HOME/icp/binary:$HOME/icp/source:$ICP_INSTALLDIR/prolog/$ARCH
where `$ICP_INSTALLDIR' is the ICP instalation directory and `$ARCH' is
the machine architecture as reported by the unix command `/bin/arch'
(eg `sun3' or `sun4').


File: icp.info,  Node: DynamicCode,  Next: StaticCode,  Prev: SearchPath,  Up: LoadIntro

Dynamic Code
............

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

Dynamic code can be created either by consulting a file using
`consult/1', `reconsult/1' (*note LoadingDynamic::.), or by the
dynamically asserting clauses.


File: icp.info,  Node: StaticCode,  Prev: DynamicCode,  Up: LoadIntro

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 `compile/2' and `compile/3' calls
(*note LoadingStatic::.). The compiler saves the ICP object code in a
file with the extension `.icp'. Once a file has been compiled it must
be loaded into the ICP process.


File: icp.info,  Node: Style,  Next: LoadingDynamic,  Prev: LoadIntro,  Up: Loading

Style Warnings
--------------

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

  1. All clauses for a predicate should be contiguous -- clauses for
     one procedure should not be interspaced with clauses for another.

  2. Variables which appear only once in a clause should be written as
     `_' or a name beginning with an `_'.

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

The style checking can be controled by the predicates `style_check/1'
and `no_style_check/1'.

`style_check(TYPE)'
`'
    `all'
          turns on/off all style checking

    `discontiguous'
          turns on/off checking for discontiguous clauses

    `single_var'
          turns on/off checking for single occurence of variables.
          Variables whose name begins with an underscore (`_') are not
          flagged.

`no_style_check(TYPE)'

File: icp.info,  Node: LoadingDynamic,  Next: LoadingStatic,  Prev: Style,  Up: Loading

Loading Dynamic Code
--------------------

`consult(+FILE)'
     FILE is either the atom `user', or the name of some source file.
     In the case of FILE not being the atom `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 ``**
     SYNTAX ERROR **'' is written out followed by all the text up to the
     offending token, followed by the string ``*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, `consult/1' ends the current session,
     displays an error message, and then fails.

     In the special case where FILE is the atom `user' `consult/1'
     reads from the terminal (standard input) rather than a file.
     Consultation terminates when a `end_of_file' token is read (caused
     by typing `CTL-D').  If a syntax error is found during
     consultation then the string ``** 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
          ?- [File1, ..., FileN].
     is syntactic sugar for the goals
          ?- consult(File1), ..., consult(FileN).

`reconsult(+FILE)'
     Like `consult/1' except that all predicates previously
     (re)consulted for this file are abolished before asserting the new
     definitions.


File: icp.info,  Node: LoadingStatic,  Prev: LoadingDynamic,  Up: Loading

Loading Static Code
-------------------

`compile(+FILE)'
     `compile/1' is used to generate static object code for the
     relations in FILE. FILE is either the atom `user', or the name of
     some source file. The predicates defined in file FILE are compiled
     and written out to the corresponding object file.  Completion of
     suffixes is performed, with the object file having the extension
     `.icp'.

    `compiling user'
          If FILE is `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 ``** 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 `CTL-D'.

    `compiling a `.pl' file'
          If FILE is the name of a `.pl' file then `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 `FILE`.icp''. If a syntax error is
          found during compilation then the string ``** SYNTAX ERROR
          **'' is written out, followed by all the text up to the
          offending token, followed by the string ``*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.  `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,
          `compile/1' displays an error message and continues as if the
          offending clause had not been read.

`compile(+FILE,+PUBLIC)'
     Same as `compile/1' except that on loading the code resulting from
     compilation, only the successfully compiled relations of FILE
     whose predicates appear in the PUBLIC list, become accessible
     other than to predicates in the same segment.  Predicates of arity
     zero may appear in PUBLIC as simple atoms.

`compile(+FILE,+PUBLIC,+MODE)'
     Same as `compile/2' except that the third argument allows for
     non-standard compilation modes to be adopted. If MODE is the atom
     `single' then the relations of FILE are compiled into a single
     segment, otherwise MODE must be the atom `multiple' and each
     relation of 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 `user'.

`load(+FILE)'
     If FILE is an atom, loads the object code contained in file
     `FILE`.icp''.  `load/1' notifies the user of the file being loaded
     and returns after typing the word ``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
     `.icp' files are first looked for in the current directory, and
     then in the subdirectory ``binary''. If the source file is newer
     than the compiled file, the source file is compiled before the
     load.

     If FILE is a list, is equivalent to repeatedly calling `load/1'
     with the members of FILES.

`load(+FILE, +TYPE)'
     As `load/1' but of type TYPE, where TYPE is one of the atoms
     `system' or `user' determining whether the predicates should be
     placed in a system or user partition.

`ensure_loaded(+FILE)'
     If the filename FILE is an atom, and the file has not been loaded
     yet, this behaves in the same way as `load/1'.  If the file was
     previously loaded, then `ensure_loaded/1' succeeds trivially.

     If FILE is a list, this is equivalent to repeatedly calling
     `ensure_loaded/1' with the members of FILES.

`loadicp(+FILE)'
     Loads a compiled file. This is a form of loading which disables
     automatic compilation and which does not handle lists of files.  If
     FILE does not have the suffix `.icp' then FILE.icp is loaded.

`loadicp(+FILE, +TYPE)'
     As `loadicp/1' but of type TYPE, where TYPE is one of the atoms
     `system' or `user' determining whether the predicates should be
     placed in a system or user partition.

`rebuild(+FILE)'
     Is used to recompile all system files that need it.

`make(+FILE)'
     Is used to recompile a file if the source file is newer than the
     object file.  All predicates defined in the file FILE are made
     public.

`make(+FILE, +PUBLIC)'
     Is used to recompile a file if the source file is newer than the
     object file.  All predicates in the list PUBLIC are made public,
     unless PUBLIC is the empty list (`[]') in which case all predicates
     in the file are made public.

`system(+ONOFF)'
     Normally system predicates can not be re-loaded, an attempt to do
     so results in a message of the form
          | ?- compile(user).
          write(A):-foo(A).
          cannot redefine system predicate(s): write/1.
     The call `?- system(on).' causes subsequent calls to
     `compile/2' to allow redefinition of system predicates. To restore
     the normal operation, the call `?- system(off).' should be used.


File: icp.info,  Node: IO,  Next: Arithmetic,  Prev: Loading,  Up: Builtin Predicates

Input and Output Primitives
===========================

Input and output can be performed either on Prolog terms or on
individual characters. Furthermore output is relative to *streams*
which refer either to files or to the terminal. The system always has a
*current input* and *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


File: icp.info,  Node: IOTerms,  Next: IOChars,  Up: IO

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, 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 *Note 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.

`read(-T)'
`read(+STREAM,-T)'
     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.
     `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
     `user_error'.  If the current input stream is `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 ``*HERE*'', followed by all those tokens which precede
     the next period or the end of file. `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 T is unified with the `end_of_file'
     atom.  If the input stream is a terminal, `read/1' will suspend if
     there are no characters to be read.

`write(?X)'
`write(+STREAM,?X)'
     Term X is written to the current output stream (wrt the current
     operator declarations). Terms of the form `'$VAR'(N)' are treated
     in a special way: On N being 0, 1, ..., 27, 28, ... write outputs
     `A', `B', ..., `A1', `B1', etc.

`writeq(?X)'
`writeq(+STREAM,+X)'
`writeq(+STREAM, ?X, +VARNAMES)'
     Same as `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 VARNAMES are not
     quoted.  This gives a way of printing the original variable names
     provided the term was read using `gread/3'.

`display(?X)'
`display(+STREAM,+X)'
     Term 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.

`write_canonical(?X)'
`write_canonical(+STREAM,+X)'
     Term 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 `read/1-2'.

`portray(?TERM)'
     This is a user defined predicate which can be used to override the
     default system ways of printing terms.

`print(?TERM)'
`print(+STREAM, ?TERM)'
     This primitive allows user control over the output of terms. The
     print primitive looks for the program `portray/1'. If there is no
     definition for portray, the effect of print is exactly the same as
     for `writeq/1'.

     If the portray program is defined, then it is called to output the
     TERM. If `portray/1' succeeds, then `print/1' succeeds and exits.

     If the call to `portray/1' fails, and TERM is atomic, then TERM
     will be output using `display/1'.

     If the call to `portray/1' fails, and TERM is compound, then the
     principal functor of TERM will be output using `display/1', and
     `portray/1' will be called recursively on the arguments of TERM.

     If the call to `portray/1' fails, and TERM is a list, then the
     list will be output using bracket notation with `print/1' being
     called for each element.

`format(FORMAT, ARGUMENTS)'
`format(STREAM, FORMAT, ARGUMENTS)'
     Provides a means of writing formatted data.  The following
     description is extracted from the Sicstus Prolog on-line manual.

     Print ARGUMENTS onto STREAM according to format FORMAT.  FORMAT is
     a list of formatting characters. If FORMAT is an atom then
     `name/2' will be used to translate it into a list of characters.
     Thus

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

     has the same effect as

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

     `format/3' is a Prolog interface to the C `stdio' function
     `printf()'.  It is due to Quintus Prolog.

     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.

     The default action on a format character is to print it. The
     character `~' introduces a control sequence. To print a `~' repeat
     it:

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

     will result in

          Hello ~world!

     A format may be spread over several lines. The control sequence
     `\c' followed by a LFD will translate to the empty string:

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

     will result in

          Hello world!

     The general format of a control sequence is `~NC'.  The character
     C determines the type of the control sequence.  N is an optional
     numeric argument. An alternative form of N is `*'. `*' implies
     that the next argument in ARGUMENTS should be used as a numeric
     argument in the control sequence. Example:

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

     and

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

     both produce

          Helloxxxxworld!

     The following control sequences are available.

    `~a'
          The argument is an atom. The atom is printed without quoting.

    `~Nc'
          (Print character.)  The argument is a number that will be
          interpreted as an ASCII code. N defaults to one and is
          interpreted as the number of times to print the character.

    `~Ne'
    `~NE'
    `~Nf'
    `~Ng'
    `~NG'
          (Print float). The argument is a float.  The float and N will
          be passed to the C `printf()' function as

               printf("%.Ne", ARG)
               printf("%.NE", ARG)
               printf("%.Nf", ARG)
               printf("%.Ng", ARG)
               printf("%.NG", ARG)

          If N is not supplied the action defaults to

               printf("%e", ARG)
               printf("%E", ARG)
               printf("%f", ARG)
               printf("%g", ARG)
               printf("%G", ARG)

    `~Nd'
          (Print decimal.) The argument is an integer. N is interpreted
          as the number of digits after the decimal point. If N is 0 or
          missing, no decimal point will be printed. Example:

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

          will print as

               Hello 4.2 world!
               Hello 42 world!

          respectively.

    `~ND'
          (Print decimal.) The argument is an integer. Identical to
          `~Nd' except that `,' will separate groups of three digits to
          the left of the decimal point. Example:

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

          will print as

               Hello 1,234.5 world!

    `~Nr'
          (Print radix.) The argument is an integer. N is interpreted
          as a radix.  N should be >= 2 and <= 36. If N is missing the
          radix defaults to 8. The letters `a-z' will denote digits
          larger than 9. Example:

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

          will print as

               Hello 1111 world!
               Hello f world!

          respectively.

    `~NR'
          (Print radix.) The argument is an integer. Identical to `~Nr'
          except that the letters `A-Z' will denote digits larger than
          9. Example:

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

          will print as

               Hello F world!

    `~Ns'
          (Print string.) The argument is a list of ASCII codes.
          Exactly N characters will be printed. N defaults to the
          length of the string.  Example:

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

          will print as

               Hello new  worl!
               Hello new world!

          respectively.

    `~i'
          (Ignore argument.) The argument may be of any type. The
          argument will be ignored. Example:

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

          will print as

               Hello new world!

    `~k'
          (Print canonical.) The argument may be of any type. The
          argument will be passed to `write_canonical/2'. Example:

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

          will print as

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

    `~p'
          (print.) The argument may be of any type. The argument will
          be passed to `print/2'. Example:

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

          will print as

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

    `~q'
          (Print quoted.) The argument may be of any type. The argument
          will be passed to `writeq/2'. Example:

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

          will print as

               Hello ['A','B'] world!

    `~w'
          (write.) The argument may be of any type. The argument will
          be passed to `write/2'. Example:

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

          will print as

               Hello [A,B] world!

    `~Nn'
          (Print newline.) Print N newlines. N defaults to 1.  Example:

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

          will print as

               Hello
                world!

`gread(-T)'
`gread(+STREAM,-T)'
`gread(+STREAM,-T,-V)'
     Same as `read/1' except that the variable names which occur in the
     read-in term appear in T as quoted atoms, rather than being
     converted into variables.

     In the 3 argument version V is instantiated to the list of atoms
     that are the variable names of the read-in term.
          | ?- gread(user_input, T, V).
          foo(X, a(Y, X)).
          
          T = foo('X',a('Y','X'))
          V = ['X','Y']

`writeseq(+X)'
`writeseq(+STREAM,+X)'
     Uses `write/1' to write the elements of the list X in sequence and
     separated by single spaces.

`writeqseq(+X)'
`writeqseq(+STREAM,+X)'
     Uses `writeq/1' to write the elements of the list X in sequence
     and separated by single spaces.

`writenl(?X)'
`writenl(+STREAM,+X)'
     Starts a new line on the current output stream after having used
     `write/1' to write X.

`writeqnl(?X)'
`writeqnl(+STREAM,+X)'
     Starts a new line on the current output stream after having used
     `writeq/1' to write X.

`writeseqnl(+X)'
`writeseqnl(+STREAM,+X)'
     Starts a new line on the current output stream after having used
     `write/1' to write the elements of X in sequence and separated by
     single spaces.
          | ?- writeseqnl([a1,'A2',4]).
          a1 A2 4
          
          yes

`writeqseqnl(+X)'
`writeqseqnl(+STREAM,+X)'
     Starts a new line on the current output stream after having used
     `writeq/1' to write the elements of X in sequence and separated by
     single spaces.

`write_term(?TERM)'
`write_term(+STREAM, ?TERM)'
     Same as `write/1' except that the term will be written in an
     encoded form which can only be decoded by `read_term/1'. This is
     more efficient than `write/1' because the structure of the term is
     preserved in the encoding.

`read_term(-TERM)'
`read_term(+STREAM, -TERM)'
     Reads an encoded term from the current input stream. The encoded
     version of a term is read by `read_term/1' at a greater speed than
     `read/1' can read the original term.  `write_term/1' and
     `read_term/1' can be used to write to files large terms that
     require frequent reading.

`portray_clause(?CLAUSE)'
     Displays a clause in the same way as `listing/1'. In fact
     `listing/1' and `listing/2' use `portray/1'.


File: icp.info,  Node: IOChars,  Next: StreamHandling,  Prev: IOTerms,  Up: IO

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, 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 *Note 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.

`get0(-C)'
`get0(+STREAM, -C)'
     Reads the next character (ASCII code) from the current input
     stream and instantiates C to it. The predicate returns 26 (`CTL-Z')
     on `end_of_file'.

`get(-C)'
`get(+STREAM, -C)'
     Reads the next character (ASCII code) from the current input
     stream and instantiates C to it, ignoring non printable characters
     (ascii code < 33 or > 126). The predicate returns 26 on
     `end_of_file'.

`skip(+N)'
`skip(+STREAM, +N)'
     Skips over characters from the current input stream to the first
     occurrence of the character with ASCII code N.

`put(+N)'
`put(+STREAM, +N)'
     Writes N to the current output stream. N should be either a valid
     ASCII code or an integer expression.

`nl'
`nl(+STREAM)'
     Starts a new line on the current output stream.

`tab(+N)'
`tab(+STREAM, +N)'
     N (>=0) spaces are written to the current output stream.

`tty_get0(-C)'
     Reads the next character (ASCII code) from the current terminal
     input stream and instantiates C to it. This is used when an input
     character must come from the keyboard, not necessarily the current
     stream.

`unget(+N)'
     Puts ASCII code N back onto the current input stream.

