This file documents the YAP Prolog System version 6.2.2, a high-performance Prolog compiler developed at LIACC, Universidade do Porto. YAP is based on David H. D. Warren's WAM (Warren Abstract Machine), with several optimizations for better performance. YAP follows the Edinburgh tradition, and is largely compatible with DEC-10 Prolog, Quintus Prolog, and especially with C-Prolog.
This file contains extracts of the SWI-Prolog manual, as written by Jan Wielemaker. Our thanks to the author for his kind permission in allowing us to include his text in this document.
Built In Predicates
Subnodes of Running
Subnodes of Syntax
Subnodes of Tokens
Subnodes of Numbers
Subnodes of Encoding
Subnodes of Loading Programs
Subnodes of Modules
Subnodes of Input/Output
Subnodes of Database
Subnodes of Library
Subnodes of Debugging
Subnodes of Compatibility
Subnodes of Attributes
Subnodes of SWI-Prolog
Subnodes of CLPR
Subnodes of CHR
Subnodes of C-Interface
Subnodes of C-Prolog
Subnodes of SICStus Prolog
Tables
This document provides User information on version 6.2.2 of YAP (Yet Another Prolog). The YAP Prolog System is a high-performance Prolog compiler developed at LIACC, Universidade do Porto. YAP provides several important features:
YAP is based on the David H. D. Warren's WAM (Warren Abstract Machine), with several optimizations for better performance. YAP follows the Edinburgh tradition, and was originally designed to be largely compatible with DEC-10 Prolog, Quintus Prolog, and especially with C-Prolog.
YAP implements most of the ISO-Prolog standard. We are striving at full compatibility, and the manual describes what is still missing. The manual also includes a (largely incomplete) comparison with SICStus Prolog.
The document is intended neither as an introduction to Prolog nor to the implementation aspects of the compiler. A good introduction to programming in Prolog is the book The Art of Prolog, by L. Sterling and E. Shapiro, published by "The MIT Press, Cambridge MA". Other references should include the classical Programming in Prolog, by W.F. Clocksin and C.S. Mellish, published by Springer-Verlag.
YAP 4.3 is known to build with many versions of gcc (<= gcc-2.7.2, >= gcc-2.8.1, >= egcs-1.0.1, gcc-2.95.*) and on a variety of Unixen: SunOS 4.1, Solaris 2.*, Irix 5.2, HP-UX 10, Dec Alpha Unix, Linux 1.2 and Linux 2.* (RedHat 4.0 thru 5.2, Debian 2.*) in both the x86 and alpha platforms. It has been built on Windows NT 4.0 using Cygwin from Cygnus Solutions (see README.nt) and using Visual C++ 6.0.
The overall copyright and permission notice for YAP4.3 can be found in the Artistic file in this directory. YAP follows the Perl Artistic license, and it is thus non-copylefted freeware.
If you have a question about this software, desire to add code, found a bug, want to request a feature, or wonder how to get further assistance, please send e-mail to yap-users AT lists.sourceforge.net. To subscribe to the mailing list, visit the page https://lists.sourceforge.net/lists/listinfo/yap-users.
On-line documentation is available for YAP at:
http://www.ncc.up.pt/~vsc/YAP/
Recent versions of YAP, including both source and selected binaries, can be found from this same URL.
This manual was written by Vítor Santos Costa, Luís Damas, Rogério Reis, and Rúben Azevedo. The manual is largely based on the DECsystem-10 Prolog User's Manual by D.L. Bowen, L. Byrd, F. C. N. Pereira, L. M. Pereira, and D. H. D. Warren. We have also used comments from the Edinburgh Prolog library written by R. O'Keefe. We would also like to gratefully acknowledge the contributions from Ashwin Srinivasian.
We are happy to include in YAP several excellent packages developed under separate licenses. Our thanks to the authors for their kind authorization to include these packages.
The packages are, in alphabetical order:
Logtalk is no longer distributed with YAP. Please use the Logtalk standalone installer for a smooth integration with YAP.
yap2swi
library implements some of the functionality of
SWI's PL interface. Please do refer to the SWI-Prolog home page:
for more information on SWI-Prolog and for a detailed description of its foreign language interface.
To compile YAP it should be sufficient to:
mkdir ARCH
.
cd ARCH
.
../configure ...options...
.
Notice that by default configure
gives you a vanilla
configuration. For instance, in order to use co-routining and/or CLP
you need to do
../configure --enable-coroutining ...options...
Please see Configuration Options for extra options.
YAP uses autoconf
. Recent versions of YAP try to follow GNU
conventions on where to place software.
BINDIR
. This executable is
actually a script that calls the Prolog engine, stored at LIBDIR
.
LIBDIR
is the directory where libraries are stored. YAPLIBDIR is a
subdirectory that contains the Prolog engine and a Prolog library.
INCLUDEDIR
is used if you want to use YAP as a library.
INFODIR
is where to store info
files. Usually
/usr/local/info
, /usr/info
, or /usr/share/info
.
make
.
./yap
.
make install
.
make install-info
will create the info files in the
standard info directory.
make html
will create documentation in html format in the
predefined directory.
In most systems you will need to be superuser in order to do make
install
and make info
on the standard directories.
Compiling YAP with the standard options give you a plain vanilla
Prolog. You can tune YAP to include extra functionality by calling
configure
with the appropriate options:
--enable-rational-trees=yes
gives you support for infinite
rational trees.
--enable-coroutining=yes
gives you support for coroutining,
including freezing of goals, attributed variables, and
constraints. This will also enable support for infinite rational
trees.
--enable-depth-limit=yes
allows depth limited evaluation, say for
implementing iterative deepening.
--enable-low-level-tracer=yes
allows support for tracing all calls,
retries, and backtracks in the system. This can help in debugging your
application, but results in performance loss.
--enable-wam-profile=yes
allows profiling of abstract machine
instructions. This is useful when developing YAP, should not be so
useful for normal users.
--enable-condor=yes
allows using the Condor system that
support High Throughput Computing (HTC) on large collections of
distributively owned computing resources.
--enable-tabling=yes
allows tabling support. This option
is still experimental.
--enable-parallelism={env-copy,sba,a-cow}
allows
or-parallelism supported by one of these three forms. This option is
still highly experimental.
--with-max-workers
allows definition of the maximum
number of parallel processes (its value can be consulted at runtime
using the flag max_workers
).
--with-gmp[=DIR]
give a path to where one can find the
GMP
library if not installed in the default path.
--enable-threads
allows using of the multi-threading
predicates provided by YAP. Depending on the operating system, the
option --enable-pthread-locking
may also need to be used.
--with-max-threads
allows definition of the maximum
number of threads (the default value is 1024; its value can be consulted
at runtime using the flag max_threads
).
Next section discusses machine dependent details.
The default options should give you best performance under
GCC
. Although the system is tuned for this compiler
we have been able to compile versions of YAP under lcc in Linux,
Sun's cc compiler, IBM's xlc, SGI's cc, and Microsoft's Visual C++
6.0.
GCC
.YAP has been developed to take advantage of GCC
(but not to
depend on it). The major advantage of GCC
is threaded code and
explicit register reservation.
YAP is set by default to compile with the best compilation flags we know. Even so, a few specific options reduce portability. The option
--enable-max-performance=yes
will try to support the best
available flags for a specific architectural model. Currently, the option
assumes a recent version of GCC
.
--enable-debug-yap
compiles YAP so that it can be debugged
by tools such as dbx
or gdb
.
Here follow a few hints:
On x86 machines the flags:
YAP_EXTRAS= ... -DBP_FREE=1
tells us to use the %bp
register (frame-pointer) as the emulator's
program counter. This seems to be stable and is now default.
On Sparc/Solaris2 use:
YAP_EXTRAS= ... -mno-app-regs -DOPTIMISE_ALL_REGS_FOR_SPARC=1
and YAP will get two extra registers! This trick does not work on SunOS 4 machines.
Note that versions of GCC can be tweaked to recognize different processors within the same instruction set, e.g. 486, Pentium, and PentiumPro for the x86; or Ultrasparc, and Supersparc for Sparc. Unfortunately, some of these tweaks do may make YAP run slower or not at all in other machines with the same instruction set, so they cannot be made default.
Last, the best options also depends on the version of GCC you are using, and
it is a good idea to consult the GCC manual under the menus "Invoking
GCC"/"Submodel Options". Specifically, you should check
-march=XXX
for recent versions of GCC/EGCS. In the case of
GCC2.7
and other recent versions of GCC
you can check:
486:
YAP_EXTRAS= ... -m486 -DBP_FREE=1
Pentium:
YAP_EXTRAS= ... -m486 -malign-loops=2 -malign-jumps=2 \ -malign-functions=2
PentiumPro and other recent Intel and AMD machines:
GCC
for the best -march
option.
Super and UltraSparcs:
YAP_EXTRAS= ... -msupersparc
MIPS: if have a recent machine and you need a 64 bit wide address
CC="gcc -mabi=64" ./configure --...
Be careful. At least for some versions of GCC
, compiling with
-g
seems to result in broken code.
WIN32: GCC is distributed in the MINGW32 and CYGWIN packages.
http://www.mingw.org
You will need to install the msys
and mingw
packages. You should be able to do configure, make and make install.
If you use mingw32 you may want to search the contributed packages for
the gmp
multi-precision arithmetic library. If you do setup YAP
with gmp
note that libgmp.dll
must be in the path,
otherwise YAP will not be able to execute.
CygWin environment is available from the URL:
http://www.cygwin.com
and mirrors. We suggest using recent versions of the cygwin shell. The compilation steps under the cygwin shell are as follows:
mkdir cyg $YAPSRC/configure --enable-coroutining \\ --enable-depth-limit \\ --enable-max-performance make make install
By default, YAP will use the -mno-cygwin
option to
disable the use of the cygwin dll and to enable the mingw32 subsystem
instead. YAP thus will not need the cygwin dll. It instead accesses
the system's CRTDLL.DLL
C
run time library supplied with
Win32 platforms through the mingw32 interface. Note that some older
WIN95 systems may not have CRTDLL.DLL
, in this case it should
be sufficient to import the file from a newer WIN95 or WIN98 machine.
You should check the default installation path which is set to
/YAP
in the standard Makefile. This string will usually
be expanded into c:\YAP
by Windows.
The cygwin environment does not provide gmp on the MINGW subsystem. You can fetch a dll for the gmp library from http://www.sf.net/projects/mingwrep.
It is also possible to configure YAP to be a part of the cygwin environment. In this case you should use:
mkdir cyg $YAPSRC/configure --enable-max-performance \\ --enable-cygwin=yes make make install
YAP will then compile using the cygwin library and will be installed
in cygwin's /usr/local
. You can use YAP from a cygwin console,
or as a standalone application as long as it can find
cygwin1.dll
in its path. Note that you may use to use
--enable-depth-limit
for Aleph compatibility, and that you may
want to be sure that GMP is installed.
YAP compiles cleanly under Microsoft's Visual C++ release 6.0. We next give a step-by-step tutorial on how to compile YAP manually using this environment.
First, it is a good idea to build YAP as a DLL:
Notice that either the project is named yapdll or you must replace the
preprocessors variable YAPDLL_EXPORTS to match your project names
in the files YAPInterface.h
and c_interface.c
.
Source Files
(use
FileView).
Header Files
.
m4
to generate extra .h from .m4 files and use
configure
to create a config.h
. Or, you can be lazy, and
fetch these files from $YAPSRC\VC\include.
Build.Set Active Configuration
and set Project
Type
to Release
Project.Project Settings.C/C++.Preprocessor.Additional
Include Directories
to include the directories $YAPSRC\H,
$YAPSRC\VC\include, $YAPSRC\OPTYAP and
$YAPSRC\include. The syntax is:
$YAPSRC\H, $YAPSRC\VC\include, $YAPSRC\OPTYAP, $YAPSRC\include
yapdll.dll
and an yapdll.lib
.
yapdll.dll
to your path. The file
yapdll.lib
should also be copied to a location where the linker can find it.
Now you are ready to create a console interface for YAP:
wyap
with File.New
. The project will be a
WIN32 console project, initially empty.
Source Files
.
Header Files
.
Build.Set Active Configuration
and set
Project Type
to Release
.
boot.yap
, so write:
-b $YAPSRC\pl\boot.yap
in Project.Project Settings.Debug.Program Arguments
.
ws2_32.lib yapdll.lib to
to
to Project.Project Settings.Link.Object/Library Modules
You may also need to set the Link Path
so that VC++ will find yapdll.lib
.
Project.Project Settings.C/C++.Preprocessor.Additional
Include Directories
to include the $YAPSRC/VC/include and
$YAPSRC/include.
The syntax is:
$YAPSRC\VC\include, $YAPSRC\include
Build.Start Debug
to boot the system, and then create the saved state with
['$YAPSRC\\pl\\init']. save_program('startup.yss'). ^Z
That's it, you've got YAP and the saved state!
The $YAPSRC\VC directory has the make files to build YAP4.3.17 under VC++ 6.0.
YAP should compile under the Silicon Graphic's cc
compiler,
although we advise using the GNUCC compiler, if available.
64 bit
CC="cc -64" $YAP_SRC_PATH/configure --...
We next describe how to invoke YAP in Unix systems.
Most often you will want to use YAP in interactive mode. Assuming that YAP is in the user's search path, the top-level can be invoked under Unix with the following command:
yap [-s n] [-h n] [-a n] [-c IP_HOST port ] [filename]
All the arguments and flags are optional and have the following meaning:
-?
-s
Size-h
Size-t
Size-L
SizeL
.
-G
Size-T
Size-l
YAP_FILE-L
YAP_FILE-g
Goal-z
Goal-b
BOOT_FILE'$live'/0
.
-c
IP_HOST portfilename
-f
-q
--
unix/1
built-in predicate.
Note that YAP will output an error message on the following conditions:
When restoring a saved state, YAP will allocate the same amount of memory as that in use when the state was saved, unless a different amount is specified by flags in the command line. By default, YAP restores the file ‘startup.yss’ from the current directory or from the YAP library.
YAP can also be used to run Prolog files as scripts, at least in Unix-like environments. A simple example is shown next (do not forget that the shell comments are very important):
#!/usr/local/bin/yap -L -- # # Hello World script file using YAP # # put a dot because of syntax errors . :- write('Hello World'), nl. |
The #!
characters specify that the script should call the binary
file YAP. Notice that many systems will require the complete path to the
YAP binary. The -L
flag indicates that YAP should consult the
current file when booting and then halt. The remaining arguments are
then passed to YAP. Note that YAP will skip the first lines if they
start with #
(the comment sign for Unix's shell). YAP will
consult the file and execute any commands.
A slightly more sophisticated example is:
#!/usr/bin/yap -L -- # # Hello World script file using YAP # . :- initialization(main). main :- write('Hello World'), nl. |
The initialization
directive tells YAP to execute the goal main
after consulting the file. Source code is thus compiled and main
executed at the end. The .
is useful while debugging the script
as a Prolog program: it guarantees that the syntax error will not
propagate to the Prolog code.
Notice that the --
is required so that the shell passes the extra
arguments to YAP. As an example, consider the following script
dump_args
:
#!/usr/bin/yap -L -- #. main( [] ). main( [H|T] ) :- write( H ), nl, main( T ). :- unix( argv(AllArgs) ), main( AllArgs ). |
If you this run this script with the arguments:
./dump_args -s 10000
the script will start an YAP process with stack size 10MB
, and
the list of arguments to the process will be empty.
Often one wants to run the script as any other program, and for this it
is convenient to ignore arguments to YAP. This is possible by using
L --
as in the next version of dump_args
:
#!/usr/bin/yap -L -- main( [] ). main( [H|T] ) :- write( H ), nl, main( T ). :- unix( argv(AllArgs) ), main( AllArgs ). |
The --
indicates the next arguments are not for YAP. Instead,
they must be sent directly to the argv
built-in. Hence, running
./dump_args test
will write test
on the standard output.
We will describe the syntax of YAP at two levels. We first will describe the syntax for Prolog terms. In a second level we describe the tokens from which Prolog terms are built.
Below, we describe the syntax of YAP terms from the different classes of tokens defined above. The formalism used will be BNF, extended where necessary with attributes denoting integer precedence or operator type.
term ----> subterm(1200) end_of_term_marker
subterm(N) ----> term(M) [M <= N]
term(N) ----> op(N, fx) subterm(N-1)
| op(N, fy) subterm(N)
| subterm(N-1) op(N, xfx) subterm(N-1)
| subterm(N-1) op(N, xfy) subterm(N)
| subterm(N) op(N, yfx) subterm(N-1)
| subterm(N-1) op(N, xf)
| subterm(N) op(N, yf)
term(0) ----> atom '(' arguments ')'
| '(' subterm(1200) ')'
| '{' subterm(1200) '}'
| list
| string
| number
| atom
| variable
arguments ----> subterm(999)
| subterm(999) ',' arguments
list ----> '[]'
| '[' list_expr ']'
list_expr ----> subterm(999)
| subterm(999) list_tail
list_tail ----> ',' list_expr
| ',..' subterm(999)
| '|' subterm(999)
Notes:
+ (a,b) [the same as '+'(','(a,b)) of arity one]
versus
+(a,b) [the same as '+'(a,b) of arity two]
Prolog tokens are grouped into the following categories:
Numbers can be further subdivided into integer and floating-point numbers.
Integer numbers are described by the following regular expression:
<integer> := {<digit>+<single-quote>|0{xXo}}<alpha_numeric_char>+
where {...} stands for optionality, + optional repetition (one or
more times), <digit> denotes one of the characters 0 ... 9, |
denotes or, and <single-quote> denotes the character "'". The digits
before the <single-quote> character, when present, form the number
basis, that can go from 0, 1 and up to 36. Letters from A
to
Z
are used when the basis is larger than 10.
Note that if no basis is specified then base 10 is assumed. Note also that the last digit of an integer token can not be immediately followed by one of the characters 'e', 'E', or '.'.
Following the ISO standard, YAP also accepts directives of the
form 0x
to represent numbers in hexadecimal base and of the form
0o
to represent numbers in octal base. For usefulness,
YAP also accepts directives of the form 0X
to represent
numbers in hexadecimal base.
Example: the following tokens all denote the same integer
10 2'1010 3'101 8'12 16'a 36'a 0xa 0o12
Numbers of the form 0'a
are used to represent character
constants. So, the following tokens denote the same integer:
0'd 100
YAP (version 6.2.2) supports integers that can fit the word size of the machine. This is 32 bits in most current machines, but 64 in some others, such as the Alpha running Linux or Digital Unix. The scanner will read larger or smaller integers erroneously.
Floating-point numbers are described by:
<float> := <digit>+{<dot><digit>+}
<exponent-marker>{<sign>}<digit>+
|<digit>+<dot><digit>+
{<exponent-marker>{<sign>}<digit>+}
where <dot> denotes the decimal-point character '.', <exponent-marker> denotes one of 'e' or 'E', and <sign> denotes one of '+' or '-'.
Examples:
10.0 10e3 10e-3 3.1415e+3
Floating-point numbers are represented as a double in the target machine. This is usually a 64-bit number.
Strings are described by the following rules:
string --> '"' string_quoted_characters '"' string_quoted_characters --> '"' '"' string_quoted_characters string_quoted_characters --> '\' escape_sequence string_quoted_characters string_quoted_characters --> string_character string_quoted_characters escape_sequence --> 'a' | 'b' | 'r' | 'f' | 't' | 'n' | 'v' escape_sequence --> '\' | '"' | ''' | '`' escape_sequence --> at_most_3_octal_digit_seq_char '\' escape_sequence --> 'x' at_most_2_hexa_digit_seq_char '\'
where string_character
in any character except the double quote
and escape characters.
Examples:
"" "a string" "a double-quote:"""
The first string is an empty string, the last string shows the use of double-quoting. The implementation of YAP represents strings as lists of integers. Since YAP 4.3.0 there is no static limit on string size.
Escape sequences can be used to include the non-printable characters
a
(alert), b
(backspace), r
(carriage return),
f
(form feed), t
(horizontal tabulation), n
(new
line), and v
(vertical tabulation). Escape sequences also be
include the meta-characters \
, "
, '
, and
`
. Last, one can use escape sequences to include the characters
either as an octal or hexadecimal number.
The next examples demonstrates the use of escape sequences in YAP:
"\x0c\" "\01\" "\f" "\\"
The first three examples return a list including only character 12 (form feed). The last example escapes the escape character.
Escape sequences were not available in C-Prolog and in original versions of YAP up to 4.2.0. Escape sequences can be disable by using:
:- yap_flag(character_escapes,off).
Atoms are defined by one of the following rules:
atom --> solo-character atom --> lower-case-letter name-character* atom --> symbol-character+ atom --> single-quote single-quote atom --> ''' atom_quoted_characters ''' atom_quoted_characters --> ''' ''' atom_quoted_characters atom_quoted_characters --> '\' atom_sequence string_quoted_characters atom_quoted_characters --> character string_quoted_characters
where:
<solo-character> denotes one of: ! ; <symbol-character> denotes one of: # & * + - . / : < = > ? @ \ ^ ` ~ <lower-case-letter> denotes one of: a...z <name-character> denotes one of: _ a...z A...Z 0....9 <single-quote> denotes: '
and string_character
denotes any character except the double quote
and escape characters. Note that escape sequences in strings and atoms
follow the same rules.
Examples:
a a12x '$a' ! => '1 2'
Version 4.2.0
of YAP removed the previous limit of 256
characters on an atom. Size of an atom is now only limited by the space
available in the system.
<variable-starter><variable-character>+
where
<variable-starter> denotes one of: _ A...Z <variable-character> denotes one of: _ a...z A...Z
If a variable is referred only once in a term, it needs not to be named
and one can use the character _
to represent the variable. These
variables are known as anonymous variables. Note that different
occurrences of _
on the same term represent different
anonymous variables.
Punctuation tokens consist of one of the following characters:
( ) , [ ] { } |
These characters are used to group terms.
Any characters with ASCII code less than or equal to 32 appearing before a token are ignored.
All the text appearing in a line after the character % is taken to
be a comment and ignored (including %). Comments can also be
inserted by using the sequence /*
to start the comment and
*/
to finish it. In the presence of any sequence of comments or
layout characters, the YAP parser behaves as if it had found a
single blank character. The end of a file also counts as a blank
character for this purpose.
YAP now implements a SWI-Prolog compatible interface to wide characters and the Universal Character Set (UCS). The following text was adapted from the SWI-Prolog manual.
YAP now supports wide characters, characters with character codes above 255 that cannot be represented in a single byte. Universal Character Set (UCS) is the ISO/IEC 10646 standard that specifies a unique 31-bits unsigned integer for any character in any language. It is a superset of 16-bit Unicode, which in turn is a superset of ISO 8859-1 (ISO Latin-1), a superset of US-ASCII. UCS can handle strings holding characters from multiple languages and character classification (uppercase, lowercase, digit, etc.) and operations such as case-conversion are unambiguously defined.
For this reason YAP, following SWI-Prolog, has two representations for atoms. If the text fits in ISO Latin-1, it is represented as an array of 8-bit characters. Otherwise the text is represented as an array of wide chars, which may take 16 or 32 bits. This representational issue is completely transparent to the Prolog user. Users of the foreign language interface sometimes need to be aware of these issues though.
Character coding comes into view when characters of strings need to be read from or written to file or when they have to be communicated to other software components using the foreign language interface. In this section we only deal with I/O through streams, which includes file I/O as well as I/O through network sockets.
Although characters are uniquely coded using the UCS standard internally, streams and files are byte (8-bit) oriented and there are a variety of ways to represent the larger UCS codes in an 8-bit octet stream. The most popular one, especially in the context of the web, is UTF-8. Bytes 0...127 represent simply the corresponding US-ASCII character, while bytes 128...255 are used for multi-byte encoding of characters placed higher in the UCS space. Especially on MS-Windows the 16-bit Unicode standard, represented by pairs of bytes is also popular.
Prolog I/O streams have a property called encoding which
specifies the used encoding that influence get_code/2
and
put_code/2
as well as all the other text I/O predicates.
The default encoding for files is derived from the Prolog flag
encoding
, which is initialised from the environment. If the
environment variable LANG ends in "UTF-8", this encoding is
assumed. Otherwise the default is text
and the translation is
left to the wide-character functions of the C-library (note that the
Prolog native UTF-8 mode is considerably faster than the generic
mbrtowc()
one). The encoding can be specified explicitly in
load_files/2
for loading Prolog source with an alternative
encoding, open/4
when opening files or using set_stream/2
on
any open stream (not yet implemented). For Prolog source files we also
provide the encoding/1
directive that can be used to switch
between encodings that are compatible to US-ASCII (ascii
,
iso_latin_1
, utf8
and many locales).
For
additional information and Unicode resources, please visit
http://www.unicode.org/.
YAP currently defines and supports the following encodings:
octet
ascii
iso_latin_1
,
but generates errors and warnings on encountering values above
127.
iso_latin_1
text
mbrtowc()
and
wcrtomb()
. This may be the same as one of the other locales,
notably it may be the same as iso_latin_1
for western
languages and utf8
in a UTF-8 context.
utf8
ascii
.
See above.
unicode_be
unicode_le
Note that not all encodings can represent all characters. This implies
that writing text to a stream may cause errors because the stream
cannot represent these characters. The behaviour of a stream on these
errors can be controlled using open/4
or set_stream/2
(not
implemented). Initially the terminal stream write the characters using
Prolog escape sequences while other streams generate an I/O exception.
From Stream Encoding, you may have got the impression text-files are
complicated. This section deals with a related topic, making live often
easier for the user, but providing another worry to the programmer.
BOM or Byte Order Marker is a technique for
identifying Unicode text-files as well as the encoding they use. Such
files start with the Unicode character 0xFEFF
, a non-breaking,
zero-width space character. This is a pretty unique sequence that is not
likely to be the start of a non-Unicode file and uniquely distinguishes
the various Unicode file formats. As it is a zero-width blank, it even
doesn't produce any output. This solves all problems, or ...
Some formats start of as US-ASCII and may contain some encoding mark to
switch to UTF-8, such as the encoding="UTF-8"
in an XML header.
Such formats often explicitly forbid the the use of a UTF-8 BOM. In
other cases there is additional information telling the encoding making
the use of a BOM redundant or even illegal.
The BOM is handled by the open/4
predicate. By default, text-files are
probed for the BOM when opened for reading. If a BOM is found, the
encoding is set accordingly and the property bom(true)
is
available through stream_property/2
. When opening a file for
writing, writing a BOM can be requested using the option
bom(true)
with open/4
.
Loading Programs
consult(
+F)
In YAP consult/1
does not remove previous clauses for
the procedures defined in F. Moreover, note that all code in YAP
is compiled.
reconsult(
+F)
[
+F]
consult(F)
.
[-
+F]
reconsult(F)
Example:
?- [file1, -file2, -file3, file4].
will consult file1
file4
and reconsult file2
and
file3
.
compile(
+F)
reconsult/1
.
load_files(
+Files,
+Options)
consult
. Execution is controlled by the
following flags:
autoload(+
Autoload)
true
predicates
are loaded on first call. Currently
not supported.
derived_from(+
File)
encoding(+
Encoding)
expand(+
Bool)
true
, run the
filenames through expand_file_name/2
and load the returned
files. Default is false, except for consult/1
which is
intended for interactive use.
if(+
Condition)
true
the file unconditionally,
changed
loads the file if it was not loaded before, or has
been modified since it was loaded the last time, not_loaded
loads the file if it was not loaded before.
imports(+
ListOrAll)
all
and the file is a module file, import all public
predicates. Otherwise import only the named predicates. Each
predicate is referred to as <name>/<arity>
. This option has
no effect if the file is not a module file.
must_be_module(+
Bool)
use_module/[1,2]
.
silent(+
Bool)
stream(+
Input)
This option is added to allow compiling from non-file locations such as databases, the web, the user (see consult/1) or other servers.
compilation_mode(+
Mode)
compact
clauses are compiled and no source code is stored;
if it is source
clauses are compiled and source code is stored;
if it is assert_all
clauses are asserted into the data-base.
ensure_loaded(
+F) [ISO]
ensure_loaded/1
loads them if they have note been previously
loaded, otherwise advertises the user about the existing name clashes
and prompts about importing or not those predicates. Predicates which
are not public remain invisible.
When the files are not module files, ensure_loaded/1
loads them
if they have not been loaded before, does nothing otherwise.
F must be a list containing the names of the files to load.
make
sun% pl -g make -o my_program -c file ...
If `my_program' is started it will first reconsult all source files
that have changed since the compilation.
include(
+F) [ISO]
include
directive includes the text files or sequence of text
files specified by F into the file being currently consulted.
This section presents a set of built-ins predicates designed to set the environment for the compiler.
source_mode(-
O,+
N)
source
listing/0
, listing/1
and clause/2
for those
clauses.
The same as source_mode(_,on)
or as declaring all newly defined
static procedures as public
.
no_source
source
.
The same as source_mode(_,off)
.
compile_expressions
do_not_compile_expressions
?- source, do_not_compile_expressions. yes ?- [user]. | p(X) :- X is 2 * (3 + 8). | :- end_of_file. ?- compile_expressions. yes ?- [user]. | q(X) :- X is 2 * (3 + 8). | :- end_of_file. :- listing. p(A):- A is 2 * (3 + 8). q(A):- A is 22.
hide(+
Atom)
unhide(+
Atom)
hide_predicate(+
Pred)
current_predicate/2
,
listing
, and friends.
expand_exprs(-
O,+
N)
on
or off
) and unify
O with the previous state, where On is equivalent to
compile_expressions
and off
is equivalent to
do_not_compile_expressions
. This predicate was kept to maintain
compatibility with C-Prolog.
path(-
D)
consult/1
, reconsult/1
and restore/1
and
should not be taken for the system search path.
add_to_path(+
D)
add_to_path(+
D,+
N)
first
or last
.
remove_from_path(+
D)
style_check(+
X)
single_var
discontiguous
multiple
multifile
all
sicstus
or iso
language mode.
The style_check/1
built-in is now deprecated. Please use the
set_prolog_flag/1
instead.
no_style_check(+
X)
style_check/1
.
The no_style_check/1
built-in is now deprecated. Please use the
set_prolog_flag/1
instead.
multifile
P [ISO]
Multifile declarations affect reconsult/1
and compile/1
:
when a multifile predicate is reconsulted, only the clauses from the
same file are removed.
Since YAP4.3.0 multifile procedures can be static or dynamic.
discontiguous(+
G) [ISO]
initialization(+
G) [ISO]
initialization(+
Goal,+
When)
initialization/1
, but allows for specifying when
Goal is executed while loading the program-text:
now
after_load
restore
library_directory(+
D)
library(
File)
are searched by the predicates
consult/1
, reconsult/1
, use_module/1
or
ensure_loaded/1
.
file_search_path(+
NAME,-
DIRECTORY)
file_search_path(library,A) :- library_directory(A). file_search_path(system,A) :- prolog_flag(host_type,A).
Thus, [library(A)]
will search for a file using
library_directory/1
to obtain the prefix.
library_directory(+
D)
library(
File)
are searched by the predicates
consult/1
, reconsult/1
, use_module/1
or
ensure_loaded/1
.
prolog_file_name(+
Name,-
FullPath)
prolog_to_os_filename(+
PrologPath,-
OsPath)
expand_file_name(+
WildCard,-
List)
If the pattern contains wildcard characters, only existing files and directories are returned. Expanding a pattern' without wildcard characters returns the argument, regardless on whether or not it exists.
Before expanding wildcards, the construct $var is expanded to the value
of the environment variable var and a possible leading ~ character is
expanded to the user's home directory. In Windows, the home directory is
determined as follows: if the environment variable HOME
exists,
this is used. If the variables HOMEDRIVE
and HOMEPATH
exist (Windows-NT), these are used. At initialisation, the system will
set the environment variable HOME
to point to the YAP home
directory if neither HOME
nor HOMEPATH
and
HOMEDRIVE
are defined.
public
P [ISO extension]
clause/2
procedure and through the listing
family of
built-ins.
Note that all dynamic procedures are public. The source
directive
defines all new or redefined predicates to be public.
Since YAP4.3.0 multifile procedures can be static or dynamic.
Conditional compilation builds on the same principle as
term_expansion/2
, goal_expansion/2
and the expansion of
grammar rules to compile sections of the source-code
conditionally. One of the reasons for introducing conditional
compilation is to simplify writing portable code.
Note that these directives can only be appear as separate terms in the input. Typical usage scenarios include:
if(+
Goal)
expand_goal/2
before execution.
If an error occurs, the error is printed and processing proceeds as if
Goal has failed.
else
endif
elif(+
Goal)
:- else. :-if(Goal) ... :- endif.
In a sequence
as below, the section below the first matching elif is processed, If
no test succeeds the else branch is processed.
:- if(test1). section_1. :- elif(test2). section_2. :- elif(test3). section_3. :- else. section_else. :- endif.
save(+
F)
save(+
F,-
OUT)
Unify OUT with 1 when saving the file and OUT with 0 when
restoring the saved state.
save_program(+
F)
save_program(+
F, :
G)
restore(+
F)
YAP always tries to find saved states from the current directory first. If it cannot it will use the environment variable YAPLIBDIR, if defined, or search the default library directory.
Module systems are quite important for the development of large applications. YAP implements a module system compatible with the Quintus Prolog module system.
The YAP module system is predicate-based. This means a module consists of a set of predicates (or procedures), such that some predicates are public and the others are local to a module. Atoms and terms in general are global to the system. Moreover, the module system is flat, meaning that we do not support a hierarchy of modules. Modules can automatically import other modules, though. For compatibility with other module systems the YAP module system is non-strict, meaning both that there is a way to access predicates private to a module and that it is possible to declare predicates for a module from some other module.
YAP allows one to ignore the module system if one does not want to use it. Last note that using the module system does not introduce any significant overheads.
The YAP module system applies to predicates. All predicates belong to a
module. System predicates belong to the module primitives
, and by
default new predicates belong to the module user
. Predicates from
the module primitives
are automatically visible to every module.
Every predicate must belong to a module. This module is called its source module.
By default, the source module for a clause occurring in a source file
with a module declaration is the declared module. For goals typed in
a source file without module declarations, their module is the module
the file is being loaded into. If no module declarations exist, this is
the current type-in module. The default type-in module is
user
, but one can set the current module by using the built-in
module/1
.
Note that in this module system one can explicitly specify the source mode for a clause by prefixing a clause with its module, say:
user:(a :- b).
In fact, to specify the source module for a clause it is sufficient to specify the source mode for the clause's head:
user:a :- b.
The rules for goals are similar. If a goal appears in a text file with a module declaration, the goal's source module is the declared module. Otherwise, it is the module the file is being loaded into or the type-in module.
One can override this rule by prefixing a goal with the module it is supposed to be executed in, say:
nasa:launch(apollo,13).
will execute the goal launch(apollo,13)
as if the current source
module was nasa
.
Note that this rule breaks encapsulation and should be used with care.
A new module is defined by a module
declaration:
module(+
M,+
L)
[predicate_name/arity,...]
.
The public predicates of a module file can be made accessible by other
files through the directives use_module/1
, use_module/2
,
ensure_loaded/1
and the predicates consult/1
or
reconsult/1
. The non-public predicates
of a module file are not visible by other files; they can, however, be
accessed by prefixing the module name with the
:/2
operator.
The built-in module/1
sets the current source module:
module(+
M,+
L, +
Options)
module/2
, this directive defines the file where it
appears in as a module file; it must be the first declaration in the file.
M must be an atom specifying the module name; L must be a
list containing the module's public predicates specification, in the
form [predicate_name/arity,...]
.
The last argument Options must be a list of options, which can be:
filename
library(file)
hide(
Opt)
false
, keep source code for current module, if
true
, disable.
module(+
M)
:
File, when
loading the file.
By default, all procedures to consult a file will load the modules defined therein. The two following declarations allow one to import a module explicitly. They differ on whether one imports all predicate declared in the module or not.
use_module(+
F)
use_module(+
F,+
L)
use_module(?
M,?
F,+
L)
The module system must know whether predicates operate on goals or clauses. Otherwise, such predicates would call a goal in the module they were defined, instead of calling it in the module they are currently executing. So, for instance, consider a file example.pl:
:- module(example,[a/1]). a(G) :- call(G)
We import this module with use_module(example)
into module
user
. The expected behavior for a goal a(p)
is to
execute goal p
within the module user
. However,
a/1
will call p
within module example
.
The meta_predicate/1
declaration informs the system that some
arguments of a predicate are goals, clauses, clauses heads or other
terms related to a module, and that these arguments must be prefixed
with the current source module:
meta_predicate
G1,....,
GnIf the argument is :
, it does not refer directly to a predicate
but must be module expanded. If the argument is an integer, the argument
is a goal or a closure and must be expanded. Otherwise, the argument is
not expanded. Note that the system already includes declarations for all
built-ins.
For example, the declaration for call/1
and setof/3
are:
:- meta_predicate call(0), setof(?,0,?).
The previous example is expanded to the following code which explains,
why the goal a(p)
calls p
in example
and not in
user
. The goal call(G)
is expanded because of the
meta-predicate declaration for call/1
.
:- module(example,[a/1]). a(G) :- call(example:G)
By adding a meta-predicate declaration for a/1
, the goal
a(p)
in module user will be expanded to a(user:p)
thereby preserving the module information.
:- module(example,[a/1]). :- meta_predicate a(:). a(G) :- call(G)
An alternate mechanism is the directive module_transparent/1
offered for compatibility with SWI-Prolog.
module_transparent +
Predsdynamic/1
). Each goal associated with a transparent declared
predicate will inherit the context module from its parent goal.
It is sometimes convenient to re-export predicates originally defined in a different module. This is often useful if you are adding to the functionality of a module, or if you are composing a large module with several small modules. The following declarations can be used for that purpose:
reexport(+
F)
reexport(+
F,+
Decls)
as
NewName”, meaning that the predicate with indicator PI is
to be exported under name NewName.
except
(List)
In this case, all predicates not in List are exported. Moreover,
if “PI as
NewName” is found, the predicate with
indicator PI is to be exported under name NewName as
before.
Re-exporting predicates must be used with some care. Please, take into account the following observations:
reexport
declarations must be the first declarations to
follow the module
declaration.
reexport
and use_module
, but
all predicates reexported are automatically available for use in the
current module.
reexport
declaration and then just recompiling the file
may result in incorrect execution.
Built-ins, Debugging, Syntax, Top
This chapter describes the predicates for controlling the execution of Prolog programs.
In the description of the arguments of functors the following notation will be used:
+
P, +
Q [ISO]
Example:
p(X) :- q(X), r(X).
should be read as "p(X) if q(X) and r(X)".
+
P ; +
Q [ISO]
Example:
p(X) :- q(X); r(X).
should be read as "p(X) if q(X) or r(X)".
true [ISO]
fail [ISO]
false
! [ISO]
example:
member(X,[X|_]). member(X,[_|L]) :- member(X,L).
With the above definition
?- member(X,[1,2,3]).
will return each element of the list by backtracking. With the following definition:
member(X,[X|_]) :- !. member(X,[_|L]) :- member(X,L).
the same query would return only the first element of the
list, since backtracking could not "pass through" the cut.
\+ +
P [ISO]
This predicate might be defined as:
\+(P) :- P, !, fail. \+(_).
if P did not include "cuts".
not +
P'\+
P'
.
This predicate is kept for compatibility with C-Prolog and previous
versions of YAP. Uses of not/1
should be replace by
(\+)/1
, as YAP does not implement true negation.
+
P -> +
Q [ISO]
+P -> +Q
+P -> +Q; +R
These two predicates could be defined respectively in Prolog as:
(P -> Q) :- P, !, Q.
and
(P -> Q; R) :- P, !, Q. (P -> Q; R) :- R.
if there were no "cuts" in P, Q and R.
Note that the commit operator works by "cutting" any alternative solutions of P.
Note also that you can use chains of commit operators like:
P -> Q ; R -> S ; T.
Note that (->)/2
does not affect the scope of cuts in its
arguments.
+
Condition *-> +
Action ; +
ElseThe construct A *-> B, i.e. without an Else branch, is
translated as the normal conjunction A, B.
repeat [ISO]
In the next example, repeat
is used as an efficient way to implement
a loop. The next example reads all terms in a file:
a :- repeat, read(X), write(X), nl, X=end_of_file, !.
the loop is effectively terminated by the cut-goal, when the test-goal
X=end
succeeds. While the test fails, the goals read(X)
,
write(X)
, and nl
are executed repeatedly, because
backtracking is caught by the repeat
goal.
The built-in repeat/1
could be defined in Prolog by:
repeat. repeat :- repeat.
call(+
P) [ISO]
call(
P)
is executed as if the value of P
was found
instead of the call to call/1
, except that any "cut" occurring in
P only cuts alternatives in the execution of P.
incore(+
P)
call/1
.
call(+
Closure,...,?
Ai,...)
call_with_args(+
Name,...,?
Ai,...)
call/N
for better portability.
If Name is a complex term, then call_with_args/n
behaves as
call/n
:
call(p(X1,...,Xm), Y1,...,Yn) :- p(X1,...,Xm,Y1,...,Yn).
+
Pcall(
P)
. This feature has been kept to provide
compatibility with C-Prolog. When compiling a goal, YAP
generates a call(
X)
whenever a variable X is found as
a goal.
a(X) :- X.
is converted to:
a(X) :- call(X).
if(?
G,?
H,?
I)
The built-in if/3
is similar to ->/3
, with the difference
that it will backtrack over the test goal. Consider the following
small data-base:
a(1). b(a). c(x). a(2). b(b). c(y).
Execution of an if/3
query will proceed as follows:
?- if(a(X),b(Y),c(Z)). X = 1, Y = a ? ; X = 1, Y = b ? ; X = 2, Y = a ? ; X = 2, Y = b ? ; no
The system will backtrack over the two solutions for a/1
and the
two solutions for b/1
, generating four solutions.
Cuts are allowed inside the first goal G, but they will only prune over G.
If you want G to be deterministic you should use if-then-else, as
it is both more efficient and more portable.
once(:
G) [ISO]
once(G) :- call(G), !.
Note that cuts inside once/1
can only cut the other goals inside
once/1
.
forall(:
Cond,:
Action)
?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), Result =:= Formula).
ignore(:
Goal)
once/1
, but succeeds, regardless of whether
Goal
succeeded or not. Defined as:
ignore(Goal) :- Goal, !. ignore(_).
abort
break/0
below) are terminated. It is mainly
used during debugging or after a serious execution error, to return to
the top-level.
break
[ Break (level <number>) ]
telling the depth of the break level just entered. To return to the
previous level just type the end-of-file character or call the
end_of_file predicate. This predicate is especially useful during
debugging.
halt [ISO]
halt/0
returns the exit code 0
.
halt(+
I) [ISO]
catch(+
Goal,+
Exception,+
Action) [ISO]
catch(
Goal,
Exception,
Action)
tries to
execute goal Goal. If during its execution, Goal throws an
exception E' and this exception unifies with Exception, the
exception is considered to be caught and Action is executed. If
the exception E' does not unify with Exception, control
again throws the exception.
The top-level of YAP maintains a default exception handler that
is responsible to capture uncaught exceptions.
throw(+
Ball) [ISO]
throw(
Ball)
throws an exception. Execution is
stopped, and the exception is sent to the ancestor goals until reaching
a matching catch/3
, or until reaching top-level.
garbage_collect
garbage_collect
forces a garbage collection.
garbage_collect_atoms
garbage_collect
forces a garbage collection of the atoms
in the data-base. Currently, only atoms are recovered.
gc
gc
enables garbage collection. The same as
yap_flag(gc,on)
.
nogc
nogc
disables garbage collection. The same as
yap_flag(gc,off)
.
grow_heap(+
Size)
grow_stack(+
Size)
A predicate in a module is said to be undefined if there are no clauses defining the predicate, and if the predicate has not been declared to be dynamic. What YAP does when trying to execute undefined predicates can be specified in three different ways:
yap_flag/2
or
set_prolog_flag/2
built-ins. This solution generalizes the
ISO standard.
unknown/2
built-in (this solution is
compatible with previous releases of YAP).
user:unknown_predicate_handler/3
. This solution is compatible
with SICStus Prolog.
In more detail:
unknown(-
O,+
N)
The arity of N may be zero or one. If the arity is 0
, the
new action must be one of fail
, warning
, or
error
. If the arity is 1
, P is an user-defined
handler and at run-time, the argument to the handler P will be
unified with the undefined goal. Note that N must be defined prior
to calling unknown/2
, and that the single argument to N must
be unbound.
In YAP, the default action is to fail
(note that in the ISO
Prolog standard the default action is error
).
After defining undefined/1
by:
undefined(A) :- format('Undefined predicate: ~w~n',[A]), fail.
and executing the goal:
unknown(U,undefined(X)).
a call to a predicate for which no clauses were defined will result in the output of a message of the form:
Undefined predicate: user:xyz(A1,A2)
followed by the failure of that call.
yap_flag(unknown,+
SPEC)
yap_flag/2
,
current_prolog_flag/2
, or set_prolog_flag/2
, to set this
functionality. In this case, the first argument for the built-ins should
be unknown
, and the second argument should be either
error
, warning
, fail
, or a goal.
user:unknown_predicate_handler(+G,+M,?NG)
user:unknown_predicate_handler/3
hook predicate. This
user-defined procedure is called before any system processing for the
undefined procedure, with the first argument G set to the current
goal, and the second M set to the current module. The predicate
G will be called from within the user module.
If user:unknown_predicate_handler/3
succeeds, the system will
execute NG. If user:unknown_predicate_handler/3
fails, the
system will execute default action as specified by unknown/2
.
exception(+
Exception, +
Context, -
Action)
catch/3
and throw/1
.
If this hook predicate succeeds it must instantiate the Action argument to the atom fail
to make the operation fail silently, retry
to tell Prolog to retry the operation or error
to make the system generate an exception. The action retry
only makes sense if this hook modified the environment such that the operation can now succeed without error.
undefined_predicate
unknown
.
undefined_global_variable
nb_setval/2
or b_setval/2
before returning with the action retry.
The interaction between YAP and the user relies on YAP's ability to
portray messages. These messages range from prompts to error
information. All message processing is performed through the builtin
print_message/2
, in two steps:
format/3
builtin
in sequence.
The first argument to print_message/2
specifies the importance of
the message. The options are:
error
warning
informational
help
query
silent
The next table shows the main predicates and hooks associated to message handling in YAP:
print_message(+
Kind,
Term)
informational
, banner
, warning
, error
,
help
or silent
. A human-readable message is printed to
the stream user_error
.
If the Prolog flag verbose
is silent
, messages with
Kind informational
, or banner
are treated as
silent.
This predicate first translates the Term into a list of `message
lines' (see print_message_lines/3
for details). Next it will
call the hook message_hook/3
to allow the user intercepting the
message. If message_hook/3
fails it will print the message unless
Kind is silent.
If you need to report errors from your own predicates, we advise you to
stick to the existing error terms if you can; but should you need to
invent new ones, you can define corresponding error messages by
asserting clauses for prolog:message/2
. You will need to declare
the predicate as multifile.
print_message_lines(+
Stream, +
Prefix, +
Lines)
print_message/2
) that has been translated to
a list of message elements. The elements of this list are:
<Format>-<Args>
format/3
.
flush
flush_output/1
) and no final newline is generated.
at_same_line
format/1
, ~N
).
<Format>
format/3
as format(Stream, Format, [])
.
nl
user:message_hook(+
Term, +
Kind, +
Lines)
user
to intercept
messages from print_message/2
. Term and Kind are the
same as passed to print_message/2
. Lines is a list of
format statements as described with print_message_lines/3
.
This predicate should be defined dynamic and multifile to allow other
modules defining clauses for it too.
message_to_string(+
Term, -
String)
var(
T) [ISO]
atom(
T) [ISO]
atomic(T) [ISO]
compound(
T) [ISO]
db_reference(
T)
float(
T) [ISO]
rational(
T)
T
is a rational number.
integer(
T) [ISO]
nonvar(
T) [ISO]
var(
T)
.
number(
T) [ISO]
T
is an integer, rational or a float.
primitive(
T)
simple(
T)
callable(
T)
numbervars(
T,+
N1,-
Nn)
'$VAR'(
I)
, with I increasing from N1 to Nn.
ground(
T)
arg(+
N,+
T,
A) [ISO]
The current version will generate an error if T or N are
unbound, if T is not a compound term, of if N is not a positive
integer. Note that previous versions of YAP would fail silently
under these errors.
functor(
T,
F,
N) [ISO]
When T is not instantiated, F and N must be. If N is 0, F must be an atomic symbol, which will be unified with T. If N is not 0, then F must be an atom and T becomes instantiated to the most general term having functor F and arity N. If T is instantiated to a term then F and N are respectively unified with its top functor name and arity.
In the current version of YAP the arity N must be an
integer. Previous versions allowed evaluable expressions, as long as the
expression would evaluate to an integer. This feature is not available
in the ISO Prolog standard.
=..
L [ISO]
=
Y [ISO]
\=
Y [ISO]
unify_with_occurs_check(?T1,?T2) [ISO]
This predicate implements the full unification algorithm. An example:n
unify_with_occurs_check(a(X,b,Z),a(X,A,f(B)).
will succeed with the bindings A = b
and Z = f(B)
. On the
other hand:
unify_with_occurs_check(a(X,b,Z),a(X,A,f(Z)).
would fail, because Z
is not unifiable with f(Z)
. Note that
(=)/2
would succeed for the previous examples, giving the following
bindings A = b
and Z = f(Z)
.
copy_term(?
TI,-
TF) [ISO]
If you do not want any sharing to occur please use
duplicate_term/2
.
duplicate_term(?
TI,-
TF)
Also refer to copy_term/2
.
is_list(+
List)
?
Term1 =@= ?
Term2variant/2
, succeeds if Term1 and Term2 are variant terms.
subsumes_term(?
Subsumer, ?
Subsumed)
acyclic_term(?
Term)
The following predicates are used to manipulate atoms:
name(
A,
L)
name(yap,L).
will return:
L = [121,97,112].
and
name(3,L).
will return:
L = [51].
atom_chars(?
A,?
L) [ISO]
atom_codes(?
A,?
L) [ISO]
atom_concat(+
As,?
A)
atomic_concat(+
As,?
A)
atomic_list_concat(+
As,?
A)
atomic_list_concat(?
As,+
Separator,?
A)
atomic_list_concat/2
, but inserts
Separator between each pair of atoms. For example:
?- atomic_list_concat([gnu, gnat], ', ', A). A = 'gnu, gnat'
YAP emulates the SWI-Prolog version of this predicate that can also be used to split atoms by instantiating Separator and Atom as shown below.
?- atomic_list_concat(L, -, 'gnu-gnat'). L = [gnu, gnat]
atom_length(+
A,?
I) [ISO]
atom_concat(?
A1,?
A2,?
A12) [ISO]
If A1 and A2 are unbound, the built-in will find all the atoms
that concatenated give A12.
number_chars(?
I,?
L) [ISO]
number_codes(?
A,?
L) [ISO]
atom_number(?
Atom,?
Number)
number_atom(?
I,?
L)
sub_atom(+
A,?
Bef, ?
Size, ?
After, ?
At_out) [ISO]
Note that A must always be known, but At_out can be unbound when
calling this built-in. If all the arguments for sub_atom/5
but A
are unbound, the built-in will backtrack through all possible
sub-strings of A.
The following predicates are used to manipulate characters:
char_code(?
A,?
I) [ISO]
char_type(?
Char, ?
Type)
C
<ctype.h>
primitives.
alnum
alpha
csym
csymf
ascii
white
cntrl
digit
digit(
Weight)
char_type(X, digit(6))
yields X =
'6'
. Useful for parsing numbers.
xdigit(
Weight)
graph
lower
lower(Upper)
to_lower(Upper)
upper
upper(Lower)
to_upper(Lower)
punct
space
end_of_file
end_of_line
newline
period
quote
paren(Close)
code_type(?
Code, ?
Type)
char_type/2
, but uses character-codes rather than
one-character atoms. Please note that both predicates are as
flexible as possible. They handle either representation if the
argument is instantiated and only will instantiate with an integer
code or one-character atom depending of the version used. See also
the prolog-flag double_quotes
and the built-in predicates
atom_chars/2
and atom_codes/2
.
The following predicates are used to compare and order terms, using the standard ordering:
compare(
C,
X,
Y)
=
if X and Y are identical;
<
if X precedes Y in the defined order;
>
if Y precedes X in the defined order;
==
Y [ISO]
=/2
is that, if one of the
arguments is a free variable, it only succeeds when they have already
been unified.
?- X == Y.
fails, but,
?- X = Y, X == Y.
succeeds.
?- X == 2.
fails, but,
?- X = 2, X == 2.
succeeds.
\==
Y [ISO]
@<
Y [ISO]
@=<
Y [ISO]
@>
Y [ISO]
@>=
Y [ISO]
sort(+
L,-
S)
==
) elements.
keysort(+
L,
S)
-
Value,
keysort(+
L,
S)
unifies S with the list obtained
from L, by sorting its elements according to the value of
Key.
?- keysort([3-a,1-b,2-c,1-a,1-b],S).
would return:
S = [1-b,1-a,1-b,2-c,3-a]
predsort(+
Pred, +
List, -
Sorted)
<
, >
or =
. If
built-in predicate compare/3 is used, the result is the same as
sort/2.
length(?
L,?
S)
YAP now supports several different numeric types:
integers
Internally, SWI-Prolog has three integer representations. Small
integers (defined by the Prolog flag max_tagged_integer) are
encoded directly. Larger integers are represented as cell values
on the global stack. Integers that do not fit in 64-bit are
represented as serialised GNU MPZ structures on the global stack.
number
float
Arithmetic functions that require integer arguments accept, in addition to integers, rational numbers with denominator `1' and floating point numbers that can be accurately converted to integers. If the required argument is a float the argument is converted to float. Note that conversion of integers to floating point numbers may raise an overflow exception. In all other cases, arguments are converted to the same type using the order integer to rational number to floating point number.
Arithmetic expressions in YAP may use the following operators or evaluable predicates:
+
X-
X [ISO]
+
Y [ISO]
-
Y [ISO]
*
Y [ISO]
/
Y [ISO]
//
Y [ISO]
mod
Y [ISO]
rem
Y [ISO]
mod
but always has the same sign
X
.
div
Y [ISO]
(
X -
X mod
Y)
//
Y.
exp(
X) [ISO]
log(
X) [ISO]
log10(
X)
sqrt(
X) [ISO]
sin(
X) [ISO]
cos(
X) [ISO]
tan(
X)
asin(
X)
acos(
X)
atan(
X) [ISO]
atan(
X,
Y)
atan2/2
.
sinh(
X)
cosh(
X)
tanh(
X)
asinh(
X)
acosh(
X)
atanh(
X)
lgamma(
X)
erf(
X)
erfc(
X)
random(
X) [ISO]
In iso
language mode the argument must be a floating
point-number, the result is an integer and it the float is equidistant
it is rounded up, that is, to the least integer greater than X.
integer(
X)
float(
X) [ISO]
float_fractional_part(
X) [ISO]
0.0
if X is an integer. In the iso
language mode,
X must be an integer.
float_integer_part(
X) [ISO]
iso
language mode,
X must be an integer.
abs(
X) [ISO]
ceiling(
X) [ISO]
In iso
language mode the argument must be a floating
point-number and the result is an integer.
floor(
X) [ISO]
In iso
language mode the argument must be a floating
point-number and the result is an integer.
round(
X) [ISO]
In iso
language mode the argument must be a floating
point-number, the result is an integer and it the float is equidistant
it is rounded up, that is, to the least integer greater than X.
sign(
X) [ISO]
truncate(
X) [ISO]
rational(
X)
0.25
and the result is as expected, in contrast to the result of
rational(0.1)
. The function rationalize/1
gives a more
intuitive result.
?- A is rational(0.25). A is 1 rdiv 4 ?- A is rational(0.1). A = 3602879701896397 rdiv 36028797018963968
rationalize(
X)
rational/1
, but the result is only accurate within the
rounding error of floating point numbers, generally producing a much
smaller denominator.
?- A is rationalize(0.25). A = 1 rdiv 4 ?- A is rationalize(0.1). A = 1 rdiv 10
max(
X,
Y)
min(
X,
Y)
^
Yexp(
X,
Y)
**
Y [ISO]
/\
Y [ISO]
\/
Y [ISO]
#
Y ><
Yxor(
X ,
Y)
<<
Y >>
Y [ISO]
\
X [ISO]
gcd(
X,
Y)
msb(
X)
lsb(
X)
popcount(
X)
1
in the binary representation of the
non-negative integer X.
[
X]
X is Y*10+C-"0"
is the same as
X is Y*10+C-[48].
which would be evaluated as:
X is Y*10+C-48.
Besides numbers and the arithmetic operators described above, certain atoms have a special meaning when present in arithmetic expressions:
pi
e
epsilon
1.0
and the first larger floating point
number.
inf
iso
language mode.
nan
iso
language mode.
cputime
heapused
local
global
random
The primitive YAP predicates involving arithmetic expressions are:
is +
Y [2]
X is 2+3*4
succeeds with X = 14
.
+
X < +
Y [ISO]
+
X =< +
Y [ISO]
+
X > +
Y [ISO]
+
X >= +
Y [ISO]
+
X =:= +
Y [ISO]
+
X =\= +
Y [ISO]
srandom(+
X)
Notes:
The following predicates provide counting:
between(+
Low, +
High, ?
Value)
between/3
is true iff
Value >= Low, a feature that is particularly interesting
for generating integers from a certain value.
succ(?
Int1, ?
Int2)
succ(X, 0)
fails silently and succ(X, -1)
raises a domain-error. The behaviour to deal with natural numbers
only was defined by Richard O'Keefe to support the common
count-down-to-zero in a natural way.
plus(?
Int1, ?
Int2, ?
Int3)
Some of the I/O predicates described below will in certain conditions provide error messages and abort only if the file_errors flag is set. If this flag is cleared the same predicates will just fail. Details on setting and clearing this flag are given under 7.7.
Subnodes of Input/Output
open(+
F,+
M,-
S) [ISO]
At most, there are 17 streams opened at the same time. Each stream is
either an input or an output stream but not both. There are always 3
open streams: user_input
for reading, user_output
for writing
and user_error
for writing. If there is no ambiguity, the atoms
user_input
and user_output
may be referred to as user
.
The file_errors
flag controls whether errors are reported when in
mode 'read' or 'append' the file F does not exist or is not
readable, and whether in mode 'write' or 'append' the file is not
writable.
open(+
F,+
M,-
S,+
Opts) [ISO]
type(+
T) [ISO]
text
stream (default), or a
binary
stream.
reposition(+
Bool) [ISO]
true
), or
not (false
). By default, YAP enables repositioning for all
files, except terminal files and sockets.
eof_action(+
Action) [ISO]
end_of_file
. The possible
actions are error
, that raises an error, reset
, that tries to
reset the stream and is used for tty
type files, and eof_code
,
which generates a new end_of_file
(default for non-tty files).
alias(+
Name) [ISO]
The operation will fail and give an error if the alias name is already
in use. YAP allows several aliases for the same file, but only
one is returned by stream_property/2
bom(+
Bool)
true
, a BOM (Byte Order Mark) was
detected while opening the file for reading or a BOM was written while
opening the stream. See BOM for details.
encoding(+
Encoding)
representation_errors(+
Mode)
error
(throw and I/O error exception), prolog
(write \u...\
escape code or xml
(write &#...;
XML character entity).
The initial mode is prolog
for the user streams and
error
for all other streams. See also Encoding.
expand_filename(+
Mode)
true
then do filename expansion, then ask Prolog
to do file name expansion before actually trying to opening the file:
this includes processing ~
characters and processing $
environment variables at the beginning of the file. Otherwise, just try
to open the file using the given name.
The default behavior is given by the Prolog flag
open_expands_filename
.
close(+
S) [ISO]
user_input
,
user_output
, and user_error
can never be closed.
close(+
S,+
O) [ISO]
The only valid options are force(true)
and force(false)
.
YAP currently ignores these options.
time_file(+
File,-
Time)
absolute_file_name(+
Name,+
Options, -
FullPath)
absolute_file_name(+
Name, -
FullPath,+
Options)
extensions(+
ListOfExtensions)
absolute_file_name/3
will first add the extension and then
verify the conditions imposed by the other options. If the condition
fails, the next extension of the list is tried. Extensions may be
specified both as .ext
or plain ext
.
relative_to(+
FileOrDir)
working_directory/2
) or,
if Spec is atomic and absolute_file_name/[2,3]
is executed
in a directive, it uses the current source-file as reference.
access(+
Mode)
read
, write
, append
, exist
or
none
(default).
See also access_file/2
.
file_type(+
Type)
txt
implies ['']
,
prolog
implies ['.pl', '']
, executable
implies
['.so', '']
, qlf
implies ['.qlf', '']
and
directory
implies ['']
. The file-type source
is an alias for prolog
for compatibility to SICStus Prolog.
See also prolog_file_type/2
. Notice also that this predicate only
returns non-directories, unless the option file_type(directory)
is
specified, or unless access(none)
.
file_errors(fail/error)
error
(default), throw and existence_error
exception
if the file cannot be found. If fail
, stay silent.
solutions(first/all)
first
(default), the predicates leaves no choice-point.
Otherwise a choice-point will be left and backtracking may yield
more solutions.
Compatibility considerations to common argument-order in ISO as well
as SICStus absolute_file_name/3
forced us to be flexible here.
If the last argument is a list and the 2nd not, the arguments are
swapped, making the call absolute_file_name
(+Spec, -Path,
+Options) valid as well.
absolute_file_name(+
Name,-
FullPath)
user
if the file
name is user
.
file_base_name(+
Name,-
FileName)
file_name_extension(?
Base,?
Extension, ?
Name)
current_stream(
F,
M,
S)
is_stream(
S)
flush_output [ISO]
flush_output(+
S) [ISO]
set_input(+
S) [ISO]
read/1
and get/1
will start using stream S.
set_output(+
S) [ISO]
write/1
and put/1
will start using stream S.
stream_select(+
STREAMS,+
TIMEOUT,-
READSTREAMS)
If the TIMEOUT is instantiated to off
,
stream_select/3
will wait indefinitely for a stream to become
open. Otherwise the timeout must be of the form SECS:USECS
where
SECS
is an integer gives the number of seconds to wait for a timeout
and USECS
adds the number of micro-seconds.
This built-in is only defined if the system call select
is
available in the system.
current_input(-
S) [ISO]
current_output(-
S) [ISO]
at_end_of_stream [ISO]
at_end_of_stream(+
S) [ISO]
set_stream_position(+
S, +
POS) [ISO]
stream_property(?
Stream,?
Prop) [ISO]
current_stream
to obtain a current stream given a file name).
The following properties are recognized:
file_name(
P)
user_input
, user_output
, and user_error
for the
standard streams.
mode(
P)
append
,
read
, or write
.
input
output
alias(
A)
position(
P)
end_of_stream(
E)
at
the end of stream, or it has found the
end of stream and is past
, or whether it has not
yet
reached the end of stream.
eof_action(
A)
error
, generate an error,
eof_code
, return character code -1
, or reset
the
stream.
reposition(
B)
type(
T)
text
stream or a binary
stream.
bom(+
Bool)
true
, a BOM (Byte Order Mark) was
detected while opening the file for reading or a BOM was written while
opening the stream. See BOM for details.
encoding(+
Encoding)
representation_errors(+
Mode)
error
(throw and I/O error exception), prolog
(write \u...\
escape code or xml
(write &#...;
XML character entity).
The initial mode is prolog
for the user streams and
error
for all other streams. See also Encoding and
open/4
.
current_line_number(-
LineNumber)
current_line_number(+
Stream,-
LineNumber)
line_count(+
Stream,-
LineNumber)
character_count(+
Stream,-
CharacterCount)
line_position(+
Stream,-
LinePosition)
stream_position(+
Stream,-
StreamPosition)
stream_position_data/3
to
retrieve information on character or line count.
stream_position_data(+
Field,+
StreamPosition,-
Info)
line_count
, byte_count
, or
char_count
.
tell(+
S)
Whenever S is a stream not currently opened for output, an error
may be reported, depending on the state of the file_errors flag. The
predicate just fails, if S is neither a stream nor an atom.
telling(-
S)
told
see(+
S)
When S is a stream not currently opened for input, an error may be
reported, depending on the state of the file_errors
flag. If
S is neither a stream nor an atom the predicates just fails.
seeing(-
S)
seen
read(-
T) [ISO]
end_of_file
. Further reads from of
the same stream may cause an error failure (see open/3
).
read_term(-
T,+
Options) [ISO]
term_position(-
Position)
stream_position_data/3
to obtain extra
information.
singletons(-
Names)
Var
is the variable's representation in
YAP.
syntax_errors(+
Val)
yap_flag/2
for detailed information.
variable_names(-
Names)
variables(-
Names)
char_conversion(+
IN,+
OUT) [ISO]
Character conversion only works if the flag char_conversion
is
on. This is default in the iso
and sicstus
language
modes. As an example, character conversion can be used for instance to
convert characters from the ISO-LATIN-1 character set to ASCII.
If IN is the same character as OUT, char_conversion/2
will remove this conversion from the table.
current_char_conversion(?
IN,?
OUT) [ISO]
write(
T) [ISO]
writeln(
T) [ISO]
write/1
followed by nl/0
.
display(+
T)
write_canonical(+
T) [ISO]
write_term(+
T, +
Opts) [ISO]
quoted(+
Bool) [ISO]
true
, quote atoms if this would be necessary for the atom to
be recognized as an atom by YAP's parser. The default value is
false
.
ignore_ops(+
Bool) [ISO]
true
, ignore operator declarations when writing the term. The
default value is false
.
numbervars(+
Bool) [ISO]
true
, output terms of the form
'$VAR'(N)
, where N is an integer, as a sequence of capital
letters. The default value is false
.
portrayed(+
Bool)
true
, use portray/1 to portray bound terms. The default
value is false
.
portray(+
Bool)
true
, use portray/1 to portray bound terms. The default
value is false
.
max_depth(+
Depth)
Depth
is a positive integer, use Depth as
the maximum depth to portray a term. The default is 0
, that is,
unlimited depth.
priority(+
Piority)
Priority
is a positive integer smaller than 1200
,
give the context priority. The default is 1200
.
cycles(+
Bool)
writeq(
T) [ISO]
print(
T)
write/1
unless T is bound and a call to the user-defined predicate
portray/1
succeeds. To do pretty printing of terms the user should
define suitable clauses for portray/1
and use print/1
.
format(+
T,+
L)
A control sequence is introduced by a w
. The following control
sequences are available in YAP:
'~~'
'~a'
write
.
'~Nc'
'~Ne'
'~NE'
'~Nf'
'~Ng'
'~NG'
c
will be passed to printf
as:
printf("%s.Nc", F)
As an example:
?- format("~8e, ~8E, ~8f, ~8g, ~8G~w", [3.14,3.14,3.14,3.14,3.14,3.14]). 3.140000e+00, 3.140000E+00, 3.140000, 3.14, 3.143.14
'~Nd'
0
no decimal points will be
printed. The default is N = 0.
?- format("~2d, ~d",[15000, 15000]). 150.00, 15000
'~ND'
'~Nd'
, except that commas are used to separate groups
of three digits.
?- format("~2D, ~D",[150000, 150000]). 1,500.00, 150,000
'~i'
?- format('The ~i met the boregrove',[mimsy]). The met the boregrove
'~k'
write_canonical
:
?- format("Good night ~k",a+[1,2]). Good night +(a,[1,2])
'~Nn'
'~NN'
'~Nr'
2 <= N <= 36
(the default is 8).
?- format("~2r, 0x~16r, ~r", [150000, 150000, 150000]). 100100100111110000, 0x249f0, 444760
Note that the letters a-z
denote digits larger than 9.
'~NR'
2 <= N <= 36
(the default is 8).
?- format("~2r, 0x~16r, ~r", [150000, 150000, 150000]). 100100100111110000, 0x249F0, 444760
The only difference is that letters A-Z
denote digits larger than 9.
'~p'
print/1
:
?- format("Good night ~p",a+[1,2]). Good night a+[1,2]
'~q'
writeq/1
:
?- format("Good night ~q",'Hello'+[1,2]). Good night 'Hello'+[1,2]
'~Ns'
?- format("The ~s are ~4s",["woods","lovely"]). The woods are love
'~w'
write/1
:
?- format("Good night ~w",'Hello'+[1,2]). Good night Hello+[1,2]
N
, may be given as an integer, or it
may be given as an extra argument. The next example shows a small
procedure to write a variable number of a
characters:
write_many_as(N) :- format("~*c",[N,0'a]).
The format/2
built-in also allows for formatted output. One can
specify column boundaries and fill the intermediate space by a padding
character:
'~N|'
'~N+'
8
.
'~Nt'
The next example shows how to align columns and padding. We first show left-alignment:
?- format("~n*Hello~16+*~n",[]).
*Hello *
Note that we reserve 16 characters for the column.
The following example shows how to do right-alignment:
?- format("*~tHello~16+*~n",[]).
* Hello*
The ~t
escape sequence forces filling before Hello
.
We next show how to do centering:
?- format("*~tHello~t~16+*~n",[]).
* Hello *
The two ~t
escape sequence force filling both before and after
Hello
. Space is then evenly divided between the right and the
left sides.
format(+
T)
format(+
S,+
T,+
L)
with_output_to(+
Ouput,:
Goal)
once/1
, while characters written to the current
output are sent to Output. The predicate is SWI-Prolog
specific.
Applications should generally avoid creating atoms by breaking and
concatenating other atoms as the creation of large numbers of
intermediate atoms generally leads to poor performance, even more so in
multi-threaded applications. This predicate supports creating
difference-lists from character data efficiently. The example below
defines the DCG rule term/3
to insert a term in the output:
term(Term, In, Tail) :- with_output_to(codes(In, Tail), write(Term)). ?- phrase(term(hello), X). X = [104, 101, 108, 108, 111]
A Stream handle or alias
atom(-
Atom)
string(-
String)
codes(-
Codes)
codes(-
Codes, -
Tail)
chars(-
Chars)
chars(-
Chars, -
Tail)
put(+
N)
put_byte(+
N) [ISO]
put_char(+
N) [ISO]
A
. The current output stream must be a
text stream.
put_code(+
N) [ISO]
get(-
C)
end_of_stream
has already
been reached in the previous reading, this call will give an error message.
get0(-
C)
get_byte(-
C) [ISO]
get_char(-
C) [ISO]
get_code(-
C) [ISO]
peek_byte(-
C) [ISO]
peek_char(-
C) [ISO]
peek_code(-
C) [ISO]
skip(+
N)
put
(see 6.11).
tab(+
N)
nl [ISO]
read(+
S,-
T) [ISO]
read_term(+
S,-
T,+
Options) [ISO]
read_term/2
.
write(+
S,
T) [ISO]
write_canonical(+
S,+
T) [ISO]
write_canonical(+
T) [ISO]
write_term(+
S, +
T, +
Opts) [ISO]
write_term/3
.
writeq(+
S,
T) [ISO]
writeq/1
, but the output is sent to the stream S.
display(+
S,
T)
display/1
, but using stream S to display the term.
print(+
S,
T)
put(+
S,+
N)
put(N)
, but to stream S.
put_byte(+
S,+
N) [ISO]
put_byte(N)
, but to binary stream S.
put_char(+
S,+
A) [ISO]
put_char(A)
, but to text stream S.
put_code(+
S,+
N) [ISO]
put_code(N)
, but to text stream S.
get(+
S,-
C)
get(C)
, but from stream S.
get0(+
S,-
C)
get0(C)
, but from stream S.
get_byte(+
S,-
C) [ISO]
get_char(+
S,-
C) [ISO]
get_code(+
S,-
C) [ISO]
peek_byte(+
S,-
C) [ISO]
peek_char(+
S,-
C) [ISO]
peek_code(+
S,-
C) [ISO]
skip(+
S,-
C)
skip/1
, but using stream S instead of the current
input stream.
tab(+
S,+
N)
tab/1
, but using stream S.
nl(+
S) [ISO]
ttyput(+
N)
put(N)
but always to user_output
.
ttyget(-
C)
get(C)
, but from stream user_input
.
ttyget0(-
C)
get0(C)
, but from stream user_input
.
ttyskip(-
C)
skip/1
, but always using stream user_input
.
stream.
ttytab(+
N)
tab/1
, but using stream user_output
.
ttynl
user_output
.
exists(+
F)
nofileerrors
see/1
,
tell/1
, open/3
and close/1
just fail, instead of producing
an error message and aborting whenever the specified file cannot be
opened or closed.
fileerrors
write_depth(
T,
L,
A)
write/1
or write/2
. The default
value for all arguments is 0, meaning unlimited depth and length.
?- write_depth(3,5,5). yes ?- write(a(b(c(d(e(f(g))))))). a(b(c(....))) yes ?- write([1,2,3,4,5,6,7,8]). [1,2,3,4,5,...] yes ?- write(a(1,2,3,4,5,6,7,8)). a(1,2,3,4,5,...) yes
write_depth(
T,
L)
write_depth(
T,
L,_)
. Unifies T with the
value of the maximum depth of a term to be
written, and L with the maximum length of a list to write. The
setting will be used by write/1
or write/2
. The default
value for all arguments is 0, meaning unlimited depth and length.
?- write_depth(3,5,5). yes ?- write(a(b(c(d(e(f(g))))))). a(b(c(....))) yes ?- write([1,2,3,4,5,6,7,8]). [1,2,3,4,5,...] yes
always_prompt_user
user_input
stream
is not a terminal. This command is useful if you want to obtain
interactive control from a pipe or a socket.
YAP includes a SICStus Prolog compatible socket interface. This is a low level interface that provides direct access to the major socket system calls. These calls can be used both to open a new connection in the network or connect to a networked server. Socket connections are described as read/write streams, and standard I/O built-ins can be used to write on or read from sockets. The following calls are available:
socket(+
DOMAIN,+
TYPE,+
PROTOCOL,-
SOCKET)
socket
. Create a socket for
domain DOMAIN of type TYPE and protocol
PROTOCOL. Both DOMAIN and TYPE should be atoms,
whereas PROTOCOL must be an integer. The new socket object is
accessible through a descriptor bound to the variable SOCKET.
The current implementation of YAP only accepts two socket
domains: 'AF_INET'
and 'AF_UNIX'
. Socket types depend on the
underlying operating system, but at least the following types are
supported: 'SOCK_STREAM'
and 'SOCK_DGRAM'
.
socket(+
DOMAIN,-
SOCKET)
socket/4
with TYPE bound to 'SOCK_STREAM'
and
PROTOCOL bound to 0
.
socket_close(+
SOCKET)
socket_connect
(that is, client sockets) should not be closed with
socket_close
, as they will be automatically closed when the
corresponding stream is closed with close/1
or close/2
.
socket_bind(+
SOCKET, ?
PORT)
bind
, as used for servers: bind socket
to a port. Port information depends on the domain:
'AF_UNIX'(+
FILENAME)
'AF_FILE'(+
FILENAME)
'AF_INET'(?
HOST,?PORT)
socket_connect(+
SOCKET, +
PORT, -
STREAM)
connect
, used for clients: connect
socket SOCKET to PORT. The connection results in the
read/write stream STREAM.
Port information depends on the domain:
'AF_UNIX'(+
FILENAME)
'AF_FILE'(+
FILENAME)
'AF_INET'(+
HOST,+
PORT)
socket_listen(+
SOCKET, +
LENGTH)
listen
, used for servers to indicate
willingness to wait for connections at socket SOCKET. The
integer LENGTH gives the queue limit for incoming connections,
and should be limited to 5
for portable applications. The socket
must be of type SOCK_STREAM
or SOCK_SEQPACKET
.
socket_accept(+
SOCKET, -
STREAM)
socket_accept(+
SOCKET, -
CLIENT, -
STREAM)
accept
, used for servers to wait for
connections at socket SOCKET. The stream descriptor STREAM
represents the resulting connection. If the socket belongs to the
domain 'AF_INET'
, CLIENT unifies with an atom containing
the IP address for the client in numbers and dots notation.
socket_accept(+
SOCKET, -
STREAM)
socket_buffering(+
SOCKET, -
MODE, -
OLD, +
NEW)
read
or write
MODE. OLD is unified with the previous status, and NEW
receives the new status which may be one of unbuf
or
fullbuf
.
socket_select(+
SOCKETS, -
NEWSTREAMS, +
TIMEOUT, +
STREAMS, -
READSTREAMS)
select
, used for servers to wait for
connection requests or for data at sockets. The variable
SOCKETS is a list of form KEY-SOCKET, where KEY is
an user-defined identifier and SOCKET is a socket descriptor. The
variable TIMEOUT is either off
, indicating execution will
wait until something is available, or of the form SEC-USEC, where
SEC and USEC give the seconds and microseconds before
socket_select/5
returns. The variable SOCKETS is a list of
form KEY-STREAM, where KEY is an user-defined identifier
and STREAM is a stream descriptor
Execution of socket_select/5
unifies READSTREAMS from
STREAMS with readable data, and NEWSTREAMS with a list of
the form KEY-STREAM, where KEY was the key for a socket
with pending data, and STREAM the stream descriptor resulting
from accepting the connection.
current_host(?
HOSTNAME)
hostname_address(?
HOSTNAME,?
IP_ADDRESS)
Predicates in YAP may be dynamic or static. By default, when consulting or reconsulting, predicates are assumed to be static: execution is faster and the code will probably use less space. Static predicates impose some restrictions: in general there can be no addition or removal of clauses for a procedure if it is being used in the current execution.
Dynamic predicates allow programmers to change the Clausal Data Base with the same flexibility as in C-Prolog. With dynamic predicates it is always possible to add or remove clauses during execution and the semantics will be the same as for C-Prolog. But the programmer should be aware of the fact that asserting or retracting are still expensive operations, and therefore he should try to avoid them whenever possible.
dynamic +
P:- dynamic god/1.
a more convenient form can be used:
:- dynamic son/3, father/2, mother/2.
or, equivalently,
:- dynamic [son/3, father/2, mother/2].
Note:
a predicate is assumed to be dynamic when
asserted before being defined.
dynamic_predicate(+
P,+
Semantics)
logical
or
immediate
semantics.
Subnodes of Database
These predicates can be used either for static or for dynamic predicates:
assert(+
C)
assertz/1
. Adds clause C to the program. If the predicate is undefined,
declare it as dynamic. New code should use assertz/1
for better portability.
Most Prolog systems only allow asserting clauses for dynamic
predicates. This is also as specified in the ISO standard. YAP allows
asserting clauses for static predicates, as long as the predicate is not
in use and the language flag is cprolog. Note that this feature is
deprecated, if you want to assert clauses for static procedures you
should use assert_static/1
.
asserta(+
C) [ISO]
assertz(+
C) [ISO]
Most Prolog systems only allow asserting clauses for dynamic
predicates. This is also as specified in the ISO standard. YAP allows
asserting clauses for static predicates. The current version of YAP
supports this feature, but this feature is deprecated and support may go
away in future versions.
abolish(+
PredSpec) [ISO]
abolish(+
P,+
N)
assert_static(:
C)
asserta_static(:
C)
assertz_static(:
C)
The following predicates can be used for dynamic predicates and for static predicates, if source mode was on when they were compiled:
clause(+
H,
B) [ISO]
This predicate is applicable to static procedures compiled with
source
active, and to all dynamic procedures.
clause(+
H,
B,-
R)
clause/2
, plus R is unified with the
reference to the clause in the database. You can use instance/2
to access the reference's value. Note that you may not use
erase/1
on the reference on static procedures.
nth_clause(+
H,
I,-
R)
The following predicates can only be used for dynamic predicates:
retract(+
C) [ISO]
on
. For more information on
source/0
(see Setting the Compiler).
retractall(+
G)
listing
on
).
listing(+
P)
portray_clause(+
C)
listing/0
.
portray_clause(+
S,+
C)
listing/0
.
current_atom(
A)
current_predicate(
F) [ISO]
current_predicate(
A,
P)
system_predicate(
A,
P)
predicate_property(
P,
Prop) [ISO]
built_in
dynamic
static
meta_predicate(
M)
multifile
imported_from(
Mod)
exported
public
tabled
source
number_of_clauses(
ClauseCount)
predicate_statistics(
P,
NCls,
Sz,
IndexSz)
predicate_erased_statistics(
P,
NCls,
Sz,
IndexSz)
Data Base references are a fast way of accessing terms. The predicates
erase/1
and instance/1
also apply to these references and may
sometimes be used instead of retract/1
and clause/2
.
assert(+
C,-
R)
assert(C)
(see Modifying the Database) but
unifies R with the database reference that identifies the new
clause, in a one-to-one way. Note that asserta/2
only works for dynamic
predicates. If the predicate is undefined, it will automatically be
declared dynamic.
asserta(+
C,-
R)
asserta(C)
but unifying R with
the database reference that identifies the new clause, in a
one-to-one way. Note that asserta/2
only works for dynamic
predicates. If the predicate is undefined, it will automatically be
declared dynamic.
assertz(+
C,-
R)
assertz(C)
but unifying R with
the database reference that identifies the new clause, in a
one-to-one way. Note that asserta/2
only works for dynamic
predicates. If the predicate is undefined, it will automatically be
declared dynamic.
retract(+
C,-
R)
Some programs need global information for, e.g. counting or collecting data obtained by backtracking. As a rule, to keep this information, the internal data base should be used instead of asserting and retracting clauses (as most novice programmers do), . In YAP (as in some other Prolog systems) the internal data base (i.d.b. for short) is faster, needs less space and provides a better insulation of program and data than using asserted/retracted clauses. The i.d.b. is implemented as a set of terms, accessed by keys that unlikely what happens in (non-Prolog) data bases are not part of the term. Under each key a list of terms is kept. References are provided so that terms can be identified: each term in the i.d.b. has a unique reference (references are also available for clauses of dynamic predicates).
recorda(+
K,
T,-
R)
recordz(+
K,
T,-
R)
recorda_at(+
R0,
T,-
R)
recordz_at(+
R0,
T,-
R)
recordaifnot(+
K,
T,-
R)
recordzifnot(+
K,
T,-
R)
recorded(+
K,
T,
R)
erase(+
R)
erase
just fails.
erased(+
R)
instance(+
R,-
T)
:- true
. When
R is not a reference to an existing clause or to a recorded term,
this goal fails.
eraseall(+
K)
K
are erased from the internal
database. The predicate always succeeds.
current_key(?
A,?
K)
nth_instance(?
Key,?
Index,?
R)
nth_instance(?
Key,?
Index,
T,?
R)
key_statistics(+
K,-
Entries,-
Size,-
IndexSize)
key_statistics(+
K,-
Entries,-
TotalSize)
get_value(+
A,-
V)
[]
.
This predicate is YAP specific.
set_value(+
A,+
C)
The set_value
and get_value
built-ins give a fast alternative to
the internal data-base. This is a simple form of implementing a global
counter.
read_and_increment_counter(Value) :- get_value(counter, Value), Value1 is Value+1, set_value(counter, Value1).
This predicate is YAP specific.
recordzifnot(+
K,
T,-
R)
This predicate is YAP specific.
recordaifnot(+
K,
T,-
R)
This predicate is YAP specific.
There is a strong analogy between the i.d.b. and the way dynamic predicates are stored. In fact, the main i.d.b. predicates might be implemented using dynamic predicates:
recorda(X,T,R) :- asserta(idb(X,T),R). recordz(X,T,R) :- assertz(idb(X,T),R). recorded(X,T,R) :- clause(idb(X,T),R).
We can take advantage of this, the other way around, as it is quite easy to write a simple Prolog interpreter, using the i.d.b.:
asserta(G) :- recorda(interpreter,G,_). assertz(G) :- recordz(interpreter,G,_). retract(G) :- recorded(interpreter,G,R), !, erase(R). call(V) :- var(V), !, fail. call((H :- B)) :- !, recorded(interpreter,(H :- B),_), call(B). call(G) :- recorded(interpreter,G,_).
In YAP, much attention has been given to the implementation of the i.d.b., especially to the problem of accelerating the access to terms kept in a large list under the same key. Besides using the key, YAP uses an internal lookup function, transparent to the user, to find only the terms that might unify. For instance, in a data base containing the terms
b b(a) c(d) e(g) b(X) e(h)
stored under the key k/1, when executing the query
:- recorded(k(_),c(_),R).
recorded
would proceed directly to the third term, spending almost the
time as if a(X)
or b(X)
was being searched.
The lookup function uses the functor of the term, and its first three
arguments (when they exist). So, recorded(k(_),e(h),_)
would go
directly to the last term, while recorded(k(_),e(_),_)
would find
first the fourth term, and then, after backtracking, the last one.
This mechanism may be useful to implement a sort of hierarchy, where the functors of the terms (and eventually the first arguments) work as secondary keys.
In the YAP's i.d.b. an optimized representation is used for terms without free variables. This results in a faster retrieval of terms and better space usage. Whenever possible, avoid variables in terms in terms stored in the i.d.b.
YAP implements a blackboard in the style of the SICStus Prolog blackboard. The blackboard uses the same underlying mechanism as the internal data-base but has several important differences:
bb_put(+
Key,?
Term)
bb_get(+
Key,?
Term)
bb_delete(+
Key,?
Term)
bb_update(+
Key,?
Term,?
New)
When there are several solutions to a goal, if the user wants to collect all the solutions he may be led to use the data base, because backtracking will forget previous solutions.
YAP allows the programmer to choose from several system
predicates instead of writing his own routines. findall/3
gives you
the fastest, but crudest solution. The other built-in predicates
post-process the result of the query in several different ways:
findall(
T,+
G,-
L) [ISO]
With the following program:
a(2,1). a(1,1). a(2,2).
the answer to the query
findall(X,a(X,Y),L).
would be:
X = _32 Y = _33 L = [2,1,2]; no
findall(
T,+
G,+
L,-
L0)
findall/3
, but appends all answers to list L0.
all(
T,+
G,-
L)
findall(
T,
G,
L)
but eliminate
repeated elements. Thus, assuming the same clauses as in the above
example, the reply to the query
all(X,a(X,Y),L).
would be:
X = _32 Y = _33 L = [2,1]; no
Note that all/3
will fail if no answers are found.
bagof(
T,+
G,-
L) [ISO]
bagof(X,a(X,Y),L). would be: X = _32 Y = 1 L = [2,1]; X = _32 Y = 2 L = [2]; no
setof(
X,+
P,-
B) [ISO]
bagof(
T,
G,
L)
but sorting list
L and keeping only one copy of each element. Again, assuming the
same clauses as in the examples above, the reply to the query
setof(X,a(X,Y),L).
would be:
X = _32 Y = 1 L = [1,2]; X = _32 Y = 2 L = [2]; no
Grammar rules in Prolog are both a convenient way to express definite clause grammars and an extension of the well known context-free grammars.
A grammar rule is of the form:
head --> body
where both head and body are sequences of one or more items linked by the standard conjunction operator ','.
Items can be:
Grammar related built-in predicates:
expand_term(
T,-
X)
term_expansion/2
in the current module, and then try to use the user defined predicate
user:term_expansion/2
. If this call fails then the translating process
for DCG rules is applied, together with the arithmetic optimizer
whenever the compilation of arithmetic expressions is in progress.
:term_expansion(
T,-
X)
user:term_expansion(
T,-
X)
expand_term/3
to
preprocess all terms read when consulting a file. If it succeeds:
:- G
or ?- G
, it is processed as
a directive.
:goal_expansion(+
G,+
M,-
NG)
user:goal_expansion(+
G,+
M,-
NG)
goal_expansion/3
. This is an user-defined
procedure that is called after term expansion when compiling or
asserting goals for each sub-goal in a clause. The first argument is
bound to the goal and the second to the module under which the goal
G will execute. If goal_expansion/3
succeeds the new
sub-goal NG will replace G and will be processed in the same
way. If goal_expansion/3
fails the system will use the default
rules.
phrase(+
P,
L,
R)
-
R
is a phrase of type P.
phrase(+
P,
L)
phrase(P,L,[])
.
Both this predicate and the previous are used as a convenient way to
start execution of grammar rules.
'C'(
S1,
T,
S2)
'C'([H|T],H,T)
.
The following built-in predicates allow access to underlying Operating System functionality:
cd(+
D)
cd
environ(+
E,-
S)
getcwd(-
D)
pwd
ls
putenv(+
E,+
S)
rename(+
F,+
G)
sh
system(+
S)
unix(+
S)
argv/1
--
, as in the usual Unix convention.
cd/0
cd/1
environ/2
getcwd/1
putenv/2
shell/1
system/1
/bin/sh
. Acceptable commands are strings or
atoms.
shell/0
alarm(+
Seconds,+
Callable,+
OldAlarm)
0
, no new alarm is scheduled. In any event,
any previously set alarm is canceled.
The variable OldAlarm unifies with the number of seconds remaining
until any previously scheduled alarm was due to be delivered, or with
0
if there was no previously scheduled alarm.
Note that execution of Callable will wait if YAP is executing built-in predicates, such as Input/Output operations.
The next example shows how alarm/3 can be used to implement a simple clock:
loop :- loop. ticker :- write('.'), flush_output, get_value(tick, yes), alarm(1,ticker,_). :- set_value(tick, yes), alarm(1,ticker,_), loop.
The clock, ticker
, writes a dot and then checks the flag
tick
to see whether it can continue ticking. If so, it calls
itself again. Note that there is no guarantee that the each dot
corresponds a second: for instance, if the YAP is waiting for
user input, ticker
will wait until the user types the entry in.
The next example shows how alarm/3
can be used to guarantee that
a certain procedure does not take longer than a certain amount of time:
loop :- loop. :- catch((alarm(10, throw(ball), _),loop), ball, format('Quota exhausted.~n',[])).
In this case after 10
seconds our loop
is interrupted,
ball
is thrown, and the handler writes Quota exhausted
.
Execution then continues from the handler.
Note that in this case loop/0
always executes until the alarm is
sent. Often, the code you are executing succeeds or fails before the
alarm is actually delivered. In this case, you probably want to disable
the alarm when you leave the procedure. The next procedure does exactly so:
once_with_alarm(Time,Goal,DoOnAlarm) :- catch(execute_once_with_alarm(Time, Goal), alarm, DoOnAlarm). execute_once_with_alarm(Time, Goal) :- alarm(Time, alarm, _), ( call(Goal) -> alarm(0, alarm, _) ; alarm(0, alarm, _), fail).
The procedure once_with_alarm/3
has three arguments:
the Time to wait before the alarm is
sent; the Goal to execute; and the goal DoOnAlarm to execute
if the alarm is sent. It uses catch/3
to handle the case the
alarm
is sent. Then it starts the alarm, calls the goal
Goal, and disables the alarm on success or failure.
on_signal(+
Signal,?
OldAction,+
Callable)
Only a subset of the software interrupts (signals) can have their
handlers manipulated through on_signal/3
.
Their POSIX names, YAP names and default behavior is given below.
The "YAP name" of the signal is the atom that is associated with
each signal, and should be used as the first argument to
on_signal/3
. It is chosen so that it matches the signal's POSIX
name.
on_signal/3
succeeds, unless when called with an invalid
signal name or one that is not supported on this platform. No checks
are made on the handler provided by the user.
sig_up (Hangup)
sig_usr1 and sig_usr2 (User signals)
A special case is made, where if Callable is bound to
default
, then the default handler is restored for that signal.
A call in the form on_signal(
S,
H,
H)
can be used
to retrieve a signal's current handler without changing it.
It must be noted that although a signal can be received at all times, the handler is not executed while YAP is waiting for a query at the prompt. The signal will be, however, registered and dealt with as soon as the user makes a query.
Please also note, that neither POSIX Operating Systems nor YAP guarantee that the order of delivery and handling is going to correspond with the order of dispatch.
It is sometimes useful to change the value of instantiated variables. Although, this is against the spirit of logic programming, it is sometimes useful. As in other Prolog systems, YAP has several primitives that allow updating Prolog terms. Note that these primitives are also backtrackable.
The setarg/3
primitive allows updating any argument of a Prolog
compound terms. The mutable
family of predicates provides
mutable variables. They should be used instead of setarg/3
,
as they allow the encapsulation of accesses to updatable
variables. Their implementation can also be more efficient for long
deterministic computations.
setarg(+
I,+
S,?
T)
create_mutable(+
D,-
M)
get_mutable(?
D,+
M)
is_mutable(?
D)
get_mutable(?
D,+
M)
update_mutable(+
D,+
M)
Global variables are associations between names (atoms) and
terms. They differ in various ways from storing information using
assert/1
or recorda/3
.
nb_setval/2
and
backtrackable assignment using b_setval/2
.
Currently global variables are scoped globally. We may consider module
scoping in future versions. Both b_setval/2
and
nb_setval/2
implicitly create a variable if the referenced name
does not already refer to a variable.
Global variables may be initialised from directives to make them
available during the program lifetime, but some considerations are
necessary for saved-states and threads. Saved-states to not store
global variables, which implies they have to be declared with
initialization/1
to recreate them after loading the saved
state. Each thread has its own set of global variables, starting with
an empty set. Using thread_initialization/1
to define a global
variable it will be defined, restored after reloading a saved state
and created in all threads that are created after the
registration. Finally, global variables can be initialised using the
exception hook called exception/3
. The latter technique is used
by CHR.
b_setval(+
Name, +
Value)
b_getval(+
Name, -
Value)
copy_term/2
) must be
taken. The b_getval/2
predicate generates errors if Name is not
an atom or the requested variable does not exist.
Notice that for compatibility with other systems Name must be already associated with a term: otherwise the system will generate an error.
nb_setval(+
Name, +
Value)
duplicate_term/2
with
the atom Name. Note that this can be used to set an initial
value other than []
prior to backtrackable assignment.
nb_getval(+
Name, -
Value)
nb_getval/2
predicate is a synonym for b_getval/2
,
introduced for compatibility and symmetry. As most scenarios will use
a particular global variable either using non-backtrackable or
backtrackable assignment, using nb_getval/2
can be used to
document that the variable is used non-backtrackable.
nb_linkval(+
Name, +
Value)
nb_setval/2
intended for expert users only because the semantics on backtracking
to a point before creating the link are poorly defined for compound
terms. The principal term is always left untouched, but backtracking
behaviour on arguments is undone if the original assignment was
trailed and left alone otherwise, which implies that the history that
created the term affects the behaviour on backtracking. Please
consider the following example:
demo_nb_linkval :- T = nice(N), ( N = world, nb_linkval(myvar, T), fail ; nb_getval(myvar, V), writeln(V) ).
nb_set_shared_val(+
Name, +
Value)
The next example shows the differences between the three built-ins:
?- nb_setval(a,a(_)),nb_getval(a,A),nb_setval(b,t(C,A)),nb_getval(b,B). A = a(_A), B = t(_B,a(_C)) ? ?- nb_setval(a,a(_)),nb_getval(a,A),nb_set_shared_val(b,t(C,A)),nb_getval(b,B). ?- nb_setval(a,a(_)),nb_getval(a,A),nb_linkval(b,t(C,A)),nb_getval(b,B). A = a(_A), B = t(C,a(_A)) ?
nb_setarg(+{Arg], +
Term, +
Value)
nb_setval/2
. We therefore refer to the description of
nb_setval/2
for details on non-backtrackable assignment of
terms. This predicate is compatible to GNU-Prolog
setarg(A,T,V,false)
, removing the type-restriction on
Value. See also nb_linkarg/3
. Below is an example for
counting the number of solutions of a goal. Note that this
implementation is thread-safe, reentrant and capable of handling
exceptions. Realising these features with a traditional implementation
based on assert/retract or flag/3 is much more complicated.
succeeds_n_times(Goal, Times) :- Counter = counter(0), ( Goal, arg(1, Counter, N0), N is N0 + 1, nb_setarg(1, Counter, N), fail ; arg(1, Counter, Times) ).
nb_set_shared_arg(+
Arg, +
Term, +
Value)
nb_setarg/3
, but like nb_linkval/2
it does not
duplicate the global sub-terms in Value. Use with extreme care
and consult the documentation of nb_linkval/2
before use.
nb_linkarg(+
Arg, +
Term, +
Value)
nb_setarg/3
, but like nb_linkval/2
it does not
duplicate Value. Use with extreme care and consult the
documentation of nb_linkval/2
before use.
nb_current(?
Name, ?
Value)
nb_delete(+
Name)
Global variables have been introduced by various Prolog implementations recently. We follow the implementation of them in SWI-Prolog, itself based on hProlog by Bart Demoen.
GNU-Prolog provides a rich set of global variables, including
arrays. Arrays can be implemented easily in YAP and SWI-Prolog using
functor/3
and setarg/3
due to the unrestricted arity of
compound terms.
YAP includes two profilers. The count profiler keeps information on the
number of times a predicate was called. This information can be used to
detect what are the most commonly called predicates in the program. The
count profiler can be compiled by setting YAP's flag profiling
to on
. The time-profiler is a gprof
profiler, and counts
how many ticks are being spent on specific predicates, or on other
system functions such as internal data-base accesses or garbage collects.
The YAP profiling sub-system is currently under development. Functionality for this sub-system will increase with newer implementation.
Notes:
The count profiler works by incrementing counters at procedure entry or backtracking. It provides exact information:
list_profile
shows all procedures, irrespective of module, and
the procedure list_profile/1
shows the procedures being used in
a specific module.
list_profile :- % get number of calls for each profiled procedure setof(D-[M:P|D1],(current_module(M),profile_data(M:P,calls,D),profile_data(M:P,retries,D1)),LP), % output so that the most often called % predicates will come last: write_profile_data(LP). list_profile(Module) :- % get number of calls for each profiled procedure setof(D-[Module:P|D1],(profile_data(Module:P,calls,D),profile_data(Module:P,retries,D1)),LP), % output so that the most often called % predicates will come last: write_profile_data(LP). write_profile_data([]). write_profile_data([D-[M:P|R]|SLP]) :- % swap the two calls if you want the most often % called predicates first. format('~a:~w: ~32+~t~d~12+~t~d~12+~n', [M,P,D,R]), write_profile_data(SLP).
These are the current predicates to access and clear profiling data:
profile_data(?
Na/Ar, ?
Parameter, -
Data)
calls
retries
profile_reset
The tick profiler works by interrupting the Prolog code every so often and checking at each point the code was. The profiler must be able to retrace the state of the abstract machine at every moment. The major advantage of this approach is that it gives the actual amount of time being spent per procedure, or whether garbage collection dominates execution time. The major drawback is that tracking down the state of the abstract machine may take significant time, and in the worst case may slow down the whole execution.
The following procedures are available:
profinit
profon
profoff
showprofres
showprofres(
N)
The showprofres/0
and showprofres/1
predicates call a user-defined multifile hook predicate, user:prolog_predicate_name/2
, that can be used for converting a possibly explicitly-qualified callable term into an atom that will used when printing the profiling information.
Predicates compiled with YAP's flag call_counting
set to
on
update counters on the numbers of calls and of
retries. Counters are actually decreasing counters, so that they can be
used as timers. Three counters are available:
calls
: number of predicate calls since execution started or since
system was reset;
retries
: number of retries for predicates called since
execution started or since counters were reset;
calls_and_retries
: count both on predicate calls and
retries.
The code for the call counters piggybacks on the profiling code. Therefore, activating the call counters also activates the profiling counters.
These are the predicates that access and manipulate the call counters:
call_count_data(-
Calls, -
Retries, -
CallsAndRetries)
call_count_reset
call_count(?
CallsMax, ?
RetriesMax, ?
CallsAndRetriesMax)
call_counter
when the
counter calls
reaches 0;
retry_counter
when the
counter retries
reaches 0;
call_and_retry_counter
when the counter calls_and_retries
reaches 0.
Next, we show a simple example of how to use call counters:
?- yap_flag(call_counting,on), [-user]. l :- l. end_of_file. yap_flag(call_counting,off). yes yes ?- catch((call_count(10000,_,_),l),call_counter,format("limit_exceeded.~n",[])). limit_exceeded. yes
Notice that we first compile the looping predicate l/0
with
call_counting
on
. Next, we catch/3
to handle an
exception when l/0
performs more than 10000 reductions.
The YAP system includes experimental support for arrays. The
support is enabled with the option YAP_ARRAYS
.
There are two very distinct forms of arrays in YAP. The
dynamic arrays are a different way to access compound terms
created during the execution. Like any other terms, any bindings to
these terms and eventually the terms themselves will be destroyed during
backtracking. Our goal in supporting dynamic arrays is twofold. First,
they provide an alternative to the standard arg/3
built-in. Second, because dynamic arrays may have name that are globally
visible, a dynamic array can be visible from any point in the
program. In more detail, the clause
g(X) :- array_element(a,2,X).
will succeed as long as the programmer has used the built-in array/2
to create an array term with at least 3 elements in the current
environment, and the array was associated with the name a
. The
element X
is a Prolog term, so one can bind it and any such
bindings will be undone when backtracking. Note that dynamic arrays do
not have a type: each element may be any Prolog term.
The static arrays are an extension of the database. They provide a compact way for manipulating data-structures formed by characters, integers, or floats imperatively. They can also be used to provide two-way communication between YAP and external programs through shared memory.
In order to efficiently manage space elements in a static array must have a type. Currently, elements of static arrays in YAP should have one of the following predefined types:
byte
: an 8-bit signed character.
unsigned_byte
: an 8-bit unsigned character.
int
: Prolog integers. Size would be the natural size for
the machine's architecture.
float
: Prolog floating point number. Size would be equivalent
to a double in C
.
atom
: a Prolog atom.
dbref
: an internal database reference.
term
: a generic Prolog term. Note that this will term will
not be stored in the array itself, but instead will be stored in the
Prolog internal database.
Arrays may be named or anonymous. Most arrays will be
named, that is associated with an atom that will be used to find
the array. Anonymous arrays do not have a name, and they are only of
interest if the TERM_EXTENSIONS
compilation flag is enabled. In
this case, the unification and parser are extended to replace
occurrences of Prolog terms of the form X[I]
by run-time calls to
array_element/3
, so that one can use array references instead of
extra calls to arg/3
. As an example:
g(X,Y,Z,I,J) :- X[I] is Y[J]+Z[I].
should give the same results as:
G(X,Y,Z,I,J) :- array_element(X,I,E1), array_element(Y,J,E2), array_element(Z,I,E3), E1 is E2+E3.
Note that the only limitation on array size are the stack size for dynamic arrays; and, the heap size for static (not memory mapped) arrays. Memory mapped arrays are limited by available space in the file system and in the virtual memory space.
The following predicates manipulate arrays:
array(+
Name, +
Size)
Dynamic arrays work as standard compound terms, hence space for the
array is recovered automatically on backtracking.
static_array(+
Name, +
Size, +
Type)
reset_static_array(+
Name)
static_array_location(+
Name, -
Ptr)
static_array_properties(?
Name, ?
Size, ?
Type)
This built-in will silently fail if the there is no static array with
that name.
static_array_to_term(?
Name, ?
Term)
This built-in will silently fail if the there is no static array with
that name.
mmapped_array(+
Name, +
Size, +
Type, +
File)
static_array/3
, but the array is memory mapped to file
File. This means that the array is initialized from the file, and
that any changes to the array will also be stored in the file.
This built-in is only available in operating systems that support the
system call mmap
. Moreover, mmapped arrays do not store generic
terms (type term
).
close_static_array(+
Name)
resize_static_array(+
Name, -
OldSize, +
NewSize)
int
, dbref
, float
or
atom
.
Note that if the array is a mmapped array the size of the mmapped file
will be actually adjusted to correspond to the size of the array.
array_element(+
Name, +
Index, ?
Element)
update_array(+
Name, +
Index, ?
Value)
MULTI_ASSIGNMENT_VARIABLES
is
enabled (true by default). Backtracking undoes update_array/3 for
dynamic arrays, but not for static arrays.
Note that update_array/3
actually uses setarg/3
to update
elements of dynamic arrays, and setarg/3
spends an extra cell for
every update. For intensive operations we suggest it may be less
expensive to unify each element of the array with a mutable terms and
to use the operations on mutable terms.
add_to_array_element(+
Name, +
Index, , +
Number, ?
NewValue)
int
or float
. If the type of the array is int
you
only may add integers, if it is float
you may add integers or
floats. If Name corresponds to a dynamic array the array element
must have been previously bound to a number and Number
can be
any kind of number.
The add_to_array_element/3
built-in actually uses
setarg/3
to update elements of dynamic arrays. For intensive
operations we suggest it may be less expensive to unify each element
of the array with a mutable terms and to use the operations on mutable
terms.
Built-ins that return information on the current predicates and modules:
current_module(
M)
current_module(
M,
F)
statistics/0
?- statistics. memory (total) 4784124 bytes program space 3055616 bytes: 1392224 in use, 1663392 free 2228132 max stack space 1531904 bytes: 464 in use, 1531440 free global stack: 96 in use, 616684 max local stack: 368 in use, 546208 max trail stack 196604 bytes: 8 in use, 196596 free 0.010 sec. for 5 code, 2 stack, and 1 trail space overflows 0.130 sec. for 3 garbage collections which collected 421000 bytes 0.000 sec. for 0 atom garbage collections which collected 0 bytes 0.880 sec. runtime 1.020 sec. cputime 25.055 sec. elapsed time
The example shows how much memory the system spends. Memory is divided into Program Space, Stack Space and Trail. In the example we have 3MB allocated for program spaces, with less than half being actually used. YAP also shows the maximum amount of heap space having been used which was over 2MB.
The stack space is divided into two stacks which grow against each other. We are in the top level so very little stack is being used. On the other hand, the system did use a lot of global and local stack during the previous execution (we refer the reader to a WAM tutorial in order to understand what are the global and local stacks).
YAP also shows information on how many memory overflows and garbage
collections the system executed, and statistics on total execution
time. Cputime includes all running time, runtime excludes garbage
collection and stack overflow time.
statistics(?
Param,-
Info)
atoms
[
NumberOfAtoms,
SpaceUsedBy Atoms]
NumberOfAtoms
and how much
space they require in bytes, SpaceUsedBy Atoms.
cputime
[
Time since Boot,
Time From Last Call to Cputime]
dynamic_code
[
Clause Size,
Index Size,
Tree Index
Size,
Choice Point Instructions
Size,
Expansion Nodes Size,
Index Switch Size]
garbage_collection
[
Number of GCs,
Total Global Recovered,
Total Time
Spent]
yap_flag(gc_trace,verbose)
.
global_stack
[
Global Stack Used,
Execution Stack Free]
local_stack
[
Local Stack Used,
Execution Stack Free]
heap
[
Heap Used,
Heap Free]
program
[
Program Space Used,
Program Space Free]
heap
.
runtime
[
Time since Boot,
Time From Last Call to Runtime]
runtime
statistics would return time spent on
garbage collection and stack shifting.
stack_shifts
[
Number of Heap Shifts,
Number of Stack
Shifts,
Number of Trail Shifts]
yap_flag(gc_trace,verbose)
.
static_code
[
Clause Size,
Index Size,
Tree Index
Size,
Expansion Nodes Size,
Index Switch Size]
trail
[
Trail Used,
Trail Free]
walltime
[
Time since Boot,
Time From Last Call to Walltime]
time(:
Goal)
yap_flag(?
Param,?
Value)
argv
--
.
agc_margin
bounded [ISO]
profiling
off
(default) do not compile call counting information for
procedures. If on
compile predicates so that they calls and
retries to the predicate may be counted. Profiling data can be read through the
call_count_data/3
built-in.
char_conversion [ISO]
off
except in
sicstus
and iso
language modes, where it is on
.
character_escapes [ISO]
on
, or disabled, off
. The default value for this flag is
on
.
debug [ISO]
on
or
off
. If Value is bound to on
enable debugging, and if
it is bound to off
disable debugging.
+
debugger_print_options
write_term/3
options the
debugger uses to write terms. If unbound, show the current options.
dialect
yap
.
discontiguous_warnings
on
or
off
. If Value is bound to on
enable these warnings,
and if it is bound to off
disable them. The default for YAP is
off
, unless we are in sicstus
or iso
mode.
dollar_as_lower_case
off
(default) consider the character '$' a control character, if
on
consider '$' a lower case character.
double_quotes [ISO]
chars
, to a list of integers,
codes
, or to a single atom, atom
. If Value is bound, set to
the corresponding behavior. The default value is codes
.
executable
fast
on
allow fast machine code, if off
(default) disable it. Only
available in experimental implementations.
fileerrors
on
fileerrors
is on
, if off
(default)
fileerrors
is disabled.
float_format
printf()
format specification used by write/1
and
friends to determine how floating point numbers are printed. The
default is %.15g
. The specified value is passed to printf()
without further checking. For example, if you want less digits
printed, %g
will print all floats using 6 digits instead of the
default 15.
gc
on
allow garbage collection (default), if off
disable it.
gc_margin
gc_trace
off
(default) do not show information on garbage collection
and stack shifts, if on
inform when a garbage collection or stack
shift happened, if verbose
give detailed information on garbage
collection and stack shifts. Last, if very_verbose
give detailed
information on data-structures found during the garbage collection
process, namely, on choice-points.
generate_debugging_info
true
(default) generate debugging information for
procedures, including source mode. If false
predicates no
information is generated, although debugging is still possible, and
source mode is disabled.
host_type
configure
system information, including the machine-id
for which YAP was compiled and Operating System information.
index
on
allow indexing (default), if off
disable it.
informational_messages
on
allow printing of informational messages, such as the ones
that are printed when consulting. If off
disable printing
these messages. It is on
by default except if YAP is booted with
the -L
flag.
integer_rounding_function [ISO]
down
for the current version of YAP.
language
cprolog
, iso-prolog,
iso
or SICStus Prolog, sicstus
. The current default is
cprolog
. This flag affects update semantics, leashing mode,
style checking, handling calls to undefined procedures, how directives
are interpreted, when to use dynamic, character escapes, and how files
are consulted.
max_arity [ISO]
unbounded
for the current version of YAP.
max_integer [ISO]
GMP
multi-precision
library. If bounded
is false, requests for max_integer
will fail.
max_tagged_integer
min_integer [ISO]
GMP
multi-precision library. If
bounded
is false, requests for min_integer
will fail.
min_tagged_integer
n_of_integer_keys_in_bb
n_of_integer_keys_in_db
open_expands_filename
true
the open/3
builtin performs filename-expansion
before opening a file (SICStus Prolog like). If false
it does not
(SWI-Prolog like).
open_shared_object
open_shared_object/2
and friends are implemented,
providing access to shared libraries (.so
files) or to dynamic link
libraries (.DLL
files).
profiling
off
(default) do not compile profiling information for
procedures. If on
compile predicates so that they will output
profiling information. Profiling data can be read through the
profile_data/3
built-in.
prompt_alternatives_on(atom, changeable)
redefine_warnings
on
or
off
. If Value is bound to on
enable these warnings,
and if it is bound to off
disable them. The default for YAP is
off
, unless we are in sicstus
or iso
mode.
shared_object_search_path
single_var_warnings
on
or off
. If Value is bound to on
enable
these warnings, and if it is bound to off
disable them. The
default for YAP is off
, unless we are in sicstus
or
iso
mode.
strict_iso
on
or off
. If Value is bound to on
set
language mode to iso
and enable strict mode. If Value is
bound to off
disable strict mode, and keep the current language
mode. The default for YAP is off
.
Under strict ISO Prolog mode all calls to non-ISO built-ins generate an error. Compilation of clauses that would call non-ISO built-ins will also generate errors. Pre-processing for grammar rules is also disabled. Module expansion is still performed.
Arguably, ISO Prolog does not provide all the functionality required
from a modern Prolog system. Moreover, because most Prolog
implementations do not fully implement the standard and because the
standard itself gives the implementor latitude in a few important
questions, such as the unification algorithm and maximum size for
numbers there is no guarantee that programs compliant with this mode
will work the same way in every Prolog and in every platform. We thus
believe this mode is mostly useful when investigating how a program
depends on a Prolog's platform specific features.
stack_dump_on_error
on
show a stack dump when YAP finds an error. The default is
off
.
syntax_errors
read/1
,
read/2
, or read_term/3
:
dec10
fail
error
quiet
system_options
big_numbers
,
coroutining
, depth_limit
, low_level_tracer
,
or-parallelism
, rational_trees
, readline
, tabling
,
threads
, or the wam_profiler
.
tabling_mode
to_chars_mode
quintus
-like
semantics for the atom_chars/1
or number_chars/1
built-in,
or whether it should follow the ISO standard (iso
option).
+
toplevel_hook
true
if none is
presented. Only the first solution is considered and the goal is not
backtracked into.
+
toplevel_print_options
write_term/3
options used to write
terms from the top-level. If unbound, show the current options.
typein_module
unix
true
if YAP is
running on an Unix system. Defined if the C-compiler used to compile
this version of YAP either defines __unix__
or unix
.
unknown [ISO]
unknown/2
built-in. Possible values
are error
, fail
, and warning
.
update_semantics
immediate
update
semantics, as in C-Prolog (default), logical
update semantics,
as in Quintus Prolog, SICStus Prolog, or in the ISO standard. There is
also an intermediate mode, logical_assert
, where dynamic
procedures follow logical semantics but the internal data base still
follows immediate semantics.
user_error
user_error
to
this stream. If the second argument is unbound, unify the argument with
the current user_error
stream.
By default, the user_error
stream is set to a stream
corresponding to the Unix stderr
stream.
The next example shows how to use this flag:
?- open( '/dev/null', append, Error, [alias(mauri_tripa)] ). Error = '$stream'(3) ? ; no ?- set_prolog_flag(user_error, mauri_tripa). close(mauri_tripa). yes ?-
We execute three commands. First, we open a stream in write mode and
give it an alias, in this case mauri_tripa
. Next, we set
user_error
to the stream via the alias. Note that after we did so
prompts from the system were redirected to the stream
mauri_tripa
. Last, we close the stream. At this point, YAP
automatically redirects the user_error
alias to the original
stderr
.
user_flags
set_prolog_flag/2
if the flag is not known. Values are silent
, warning
and error
. The first two create the flag on-the-fly, with warning
printing a message. The value error
is consistent with ISO: it raises an existence error and does not create the flag. See also create_prolog_flag/3
. The default iserror
, and developers are encouraged to use create_prolog_flag/3
to create flags for their library.
user_input
user_input
to
this stream. If the second argument is unbound, unify the argument with
the current user_input
stream.
By default, the user_input
stream is set to a stream
corresponding to the Unix stdin
stream.
user_output
user_output
to
this stream. If the second argument is unbound, unify the argument with
the current user_output
stream.
By default, the user_output
stream is set to a stream
corresponding to the Unix stdout
stream.
verbose
normal
allow printing of informational and banner messages,
such as the ones that are printed when consulting. If silent
disable printing these messages. It is normal
by default except if
YAP is booted with the -q
or -L
flag.
verbose_load
true
allow printing of informational messages when
consulting files. If false
disable printing these messages. It
is normal
by default except if YAP is booted with the -L
flag.
version
version_data
yap
(Major,Minor,Patch,Undefined), where
Major is the major version, Minor is the minor version,
and Patch is the patch number.
windows
true
if YAP is
running on an Windows machine.
write_strings
on
if enables or off
if disabled. The default value for
this flag is off
.
max_workers
max_threads
current_prolog_flag(?
Flag,-
Value) [ISO]
yap_flag/2
with the second argument unbound, and unifying the
returned second argument with Value.
prolog_flag(?
Flag,-
OldValue,+
NewValue)
current_prolog_flag/2
with the
second argument OldValue unbound and then calling
set_prolog_flag/2
with the third argument NewValue.
set_prolog_flag(+
Flag,+
Value) [ISO]
Flag
. Equivalent to
calling yap_flag/2
with both arguments bound.
create_prolog_flag(+
Flag,+
Value,+
Options)
type(+Type)
and access(+Access)
with Access
one of read_only
or read_write
and Type one of boolean
, integer
, float
, atom
and term
(that is, no type).
op(+
P,+
T,+
A) [ISO]
xfx
, xfy
,yfx
,
xf
, yf
, fx
or fy
) and precedence P
(see appendix iv for a list of predefined operators).
Note that if there is a preexisting operator with the same name and
type, this operator will be discarded. Also, ','
may not be defined
as an operator, and it is not allowed to have the same for an infix and
a postfix operator.
current_op(
P,
T,
F) [ISO]
prompt(-
A,+
B)
initialization
prolog_initialization(
G)
initialization/1
.
version
version(-
Message)
prolog_load_context(?
Key, ?
Value)
directory
file
module
source
stream
term_position
source_location(?
FileName, ?
Line)
prolog_load_context/2
.
source_file(?
File)
source_file(?
ModuleAndPred,?
File)
absolute_file_name/2
).
Library files reside in the library_directory path (set by the
LIBDIR
variable in the Makefile for YAP). Currently,
most files in the library are from the Edinburgh Prolog library.
Library, Extensions, Built-ins, Top
This is the SWI-Prolog library based on the Quintus and SICStus 4
library. Notice that forall/2
is a SWI-Prolog built-in and term_variables/3
is a SWI-Prolog with a
different definition.
This library provides aggregating operators over the solutions of a
predicate. The operations are a generalisation of the bagof/3
,
setof/3
and findall/3
built-in predicates. The defined
aggregation operations are counting, computing the sum, minimum,
maximum, a bag of solutions and a set of solutions. We first give a
simple example, computing the country with the smallest area:
smallest_country(Name, Area) :- aggregate(min(A, N), country(N, A), min(Area, Name)).
There are four aggregation predicates, distinguished on two properties.
aggregate vs. aggregate_all
The
Distinguish argument
aggregate(sum(P), Name, country(Name, P), Total)
All aggregation predicates support the following operator below in
Template. In addition, they allow for an arbitrary named compound
term where each of the arguments is a term from the list below. I.e. the
term r(min(X), max(X))
computes both the minimum and maximum
binding for X.
count
sum(1)
.
sum(
Expr)
min(
Expr)
min(
Expr,
Witness)
max(
Expr)
max(
Expr,
Witness)
set(
X)
bag(
X)
The predicates are:
[nondet]aggregate(+
Template, :
Goal, -
Result)
[nondet]aggregate(+
Template, +
Discriminator, :
Goal, -
Result)
[semidet]aggregate_all(+
Template, :
Goal, -
Result)
[semidet]aggregate_all(+
Template, +
Discriminator, :
Goal, -
Result)
foreach(:Generator, :
Goal)
The implementation executes forall/2 if Goal does not contain any variables that are not shared with Generator.
Here is an example:
?- foreach(between(1,4,X), dif(X,Y)), Y = 5. Y = 5 ?- foreach(between(1,4,X), dif(X,Y)), Y = 3. No
Notice that Goal is copied repeatedly, which may cause
problems if attributed variables are involved.
[det]free_variables(:Generator, +
Template, +VarList0, -VarList)
free_variables(Generator, Template, OldList, NewList)
finds this set, using OldList as an accumulator.
The original author of this code was Richard O'Keefe. Jan Wielemaker made some SWI-Prolog enhancements, sponsored by SecuritEase, http://www.securitease.com. The code is public domain (from DEC10 library).
This library provides a SWI-compatible set of utilities for applying a
predicate to all elements of a list. The library just forwards
definitions from the maplist
library.
The following association list manipulation predicates are available
once included with the use_module(library(assoc))
command. The
original library used Richard O'Keefe's implementation, on top of
unbalanced binary trees. The current code utilises code from the
red-black trees library and emulates the SICStus Prolog interface.
assoc_to_list(+
Assoc,?
List)
del_assoc(+
Key, +
Assoc, ?
Val, ?
NewAssoc)
del_max_assoc(+
Assoc, ?
Key, ?
Val, ?
NewAssoc)
del_min_assoc(+
Assoc, ?
Key, ?
Val, ?
NewAssoc)
empty_assoc(+
Assoc)
gen_assoc(+
Assoc,?
Key,?
Value)
get_assoc(+
Key,+
Assoc,?
Value)
get_assoc(+
Key,+
Assoc,?
Value,+
NAssoc,?
NValue)
get_prev_assoc(+
Key,+
Assoc,?
Next,?
Value)
get_next_assoc(+
Key,+
Assoc,?
Next,?
Value)
is_assoc(+
Assoc)
list_to_assoc(+
List,?
Assoc)
map_assoc(+
Pred,+
Assoc)
map_assoc(+
Pred,+
Assoc,?
New)
max_assoc(+
Assoc,-
Key,?
Value)
min_assoc(+
Assoc,-
Key,?
Value)
ord_list_to_assoc(+
List,?
Assoc)
put_assoc(+
Key,+
Assoc,+
Val,+
New)
AVL trees are balanced search binary trees. They are named after their inventors, Adelson-Velskii and Landis, and they were the first dynamically balanced trees to be proposed. The YAP AVL tree manipulation predicates library uses code originally written by Martin van Emdem and published in the Logic Programming Newsletter, Autumn 1981. A bug in this code was fixed by Philip Vasey, in the Logic Programming Newsletter, Summer 1982. The library currently only includes routines to insert and lookup elements in the tree. Please try red-black trees if you need deletion.
avl_new(+
T)
avl_insert(+
Key,?
Value,+
T0,-
TF)
avl_lookup(+
Key,-
Value,+
T)
A heap is a labelled binary tree where the key of each node is less than or equal to the keys of its sons. The point of a heap is that we can keep on adding new elements to the heap and we can keep on taking out the minimum element. If there are N elements total, the total time is O(NlgN). If you know all the elements in advance, you are better off doing a merge-sort, but this file is for when you want to do say a best-first search, and have no idea when you start how many elements there will be, let alone what they are.
The following heap manipulation routines are available once included
with the use_module(library(heaps))
command.
add_to_heap(+
Heap,+
key,+
Datum,-
NewHeap)
empty_heap(?
Heap)
get_from_heap(+
Heap,-
key,-
Datum,-
Heap)
heap_size(+
Heap, -
Size)
heap_to_list(+
Heap, -
List)
list_to_heap(+
List, -
Heap)
min_of_heap(+
Heap, -
Key, -
Datum)
min_of_heap(+
Heap, -
Key1, -
Datum1,
The following list manipulation routines are available once included
with the use_module(library(lists))
command.
append(?
Prefix,?
Suffix,?
Combined)
append(?
Lists,?
Combined)
delete(+
List, ?
Element, ?
Residue)
flatten(+
List, ?
FlattenedList)
?- flatten([[1],[2,3],[4,[5,6],7,8]],L). L = [1,2,3,4,5,6,7,8] ? ; no
last(+
List,?
Last)
list_concat(+
Lists,?
List)
member(?
Element, ?
Set)
memberchk(+
Element, +
Set)
member/2
, but may only be used to test whether a known
Element occurs in a known Set. In return for this limited use, it
is more efficient when it is applicable.
nth0(?
N, ?
List, ?
Elem)
member/2
nth1(?
N, ?
List, ?
Elem)
nth0/3
, except that it counts from
1, that is nth(1, [H|_], H)
.
nth(?
N, ?
List, ?
Elem)
nth1/3
.
nth0(?
N, ?
List, ?
Elem, ?
Rest)
nth0(2, List, c, [a,b,d,e])
unifies List with
[a,b,c,d,e]
. nth/4
is the same except that it counts from 1. nth0/4
can be used to insert Elem after the Nth element of Rest.
nth1(?
N, ?
List, ?
Elem, ?
Rest)
nth(3, List, c,
[a,b,d,e])
unifies List with [a,b,c,d,e]
. nth/4
can be used to insert Elem after the Nth element of Rest.
nth(?
N, ?
List, ?
Elem, ?
Rest)
nth1/4
.
permutation(+
List,?
Perm)
remove_duplicates(+
List, ?
Pruned)
reverse(+
List, ?
Reversed)
same_length(?
List1, ?
List2)
same_length(-,+)
and same_length(+,-)
generate either list given
the other; mode same_length(-,-)
generates two lists of the same length,
in which case the arguments will be bound to lists of length 0, 1, 2, ...
select(?
Element, ?
List, ?
Residue)
selectchk(?
Element, ?
List, ?
Residue)
selectchk(Elem, List, Residue) :- select(Elem, List, Rest0), !, Rest = Rest0.
sublist(?
Sublist, ?
List)
append(_,Sublist,S)
and append(S,_,List)
hold.
suffix(?
Suffix, ?
List)
append(_,Suffix,List)
holds.
sum_list(?
Numbers, ?
Total)
sum_list(?
Numbers, +
SoFar, ?
Total)
sumlist(?
Numbers, ?
Total)
sum_list/2
, please do use sum_list/2
instead.
max_list(?
Numbers, ?
Max)
min_list(?
Numbers, ?
Min)
numlist(+
Low, +
High, +
List)
[Low, Low+1, ...High]
. See
also between/3
.
intersection(+
Set1, +
Set2, +
Set3)
subtract(+
Set, +
Delete, ?
Result)
memberchk/2
. The complexity is
|Delete|*|Set|
.
See ord_subtract/3
.
This package provides a set of useful predicates to manipulate
sequences of characters codes, usually first read in as a line. It is
available by loading the library library(lineutils)
.
search_for(+
Char,+
Line)
search_for(+
Char,+
Line)
search_for(+
Char,+
Line,-
RestOfine)
scan_natural(?
Nat,+
Line,+
RestOfLine)
scan_integer(?
Int,+
Line,+
RestOfLine)
split(+
Line,+
Separators,-
Split)
?- split("Hello * I am free"," *",S). S = ["Hello","I","am","free"] ? no
split(+
Line,-
Split)
fields(+
Line,+
Separators,-
Split)
?- fields("Hello I am free"," *",S). S = ["Hello","","I","am","","free"] ?
fields(+
Line,-
Split)
glue(+
Words,+
Separator,-
Line)
copy_line(+
StreamInput,+
StreamOutput)
copy_line(+
StreamInput,+
StreamOutput)
process(+
StreamInp, +
Goal)
call(Goal,LineIn)
.
filter(+
StreamInp, +
StreamOut, +
Goal)
call(Goal,LineIn,LineOut)
, and output LineOut to
stream StreamOut.
file_filter(+
FileIn, +
FileOut, +
Goal)
call(Goal,LineIn,LineOut)
, and output LineOut to file
FileOut.
file_filter(+
FileIn, +
FileOut, +
Goal,
file_filter/3
, but before starting the filter execute
format/3
on the output stream, using FormatCommand and
Arguments.
This library provides a set of utilities for applying a predicate to
all elements of a list or to all sub-terms of a term. They allow to
easily perform the most common do-loop constructs in Prolog. To avoid
performance degradation due to apply/2
, each call creates an
equivalent Prolog program, without meta-calls, which is executed by
the Prolog engine instead. Note that if the equivalent Prolog program
already exists, it will be simply used. The library is based on code
by Joachim Schimpf and on code from SWI-Prolog.
The following routines are available once included with the
use_module(library(apply_macros))
command.
maplist(+
Pred, ?
ListIn, ?
ListOut)
maplist(+
Pred, ?
ListIn)
maplist(+
Pred, ?
L1, ?
L2, ?
L3)
call(
Pred,
A1,
A2,
A3)
holds for every
corresponding element in lists L1, L2, and L3.
maplist(+
Pred, ?
L1, ?
L2, ?
L3, ?
L4)
call(
Pred,
A1,
A2,
A3,
A4)
holds
for every corresponding element in lists L1, L2, L3, and
L4.
checklist(+
Pred, +
List)
selectlist(+
Pred, +
ListIn, ?
ListOut)
convlist(+
Pred, +
ListIn, ?
ListOut)
maplist
and selectlist
: creates ListOut by
applying the predicate Pred to all list elements on which
Pred succeeds
sumlist(+
Pred, +
List, ?
AccIn, ?
AccOut)
mapargs(+
Pred, ?
TermIn, ?
TermOut)
sumargs(+
Pred, +
Term, ?
AccIn, ?
AccOut)
mapnodes(+
Pred, +
TermIn, ?
TermOut)
checknodes(+
Pred, +
Term)
sumnodes(+
Pred, +
Term, ?
AccIn, ?
AccOut)
include(+
Pred, +
ListIn, ?
ListOut)
selectlist/3
.
exclude(+
Goal, +
List1, ?
List2)
call(Goal, Xi)
fails.
partition(+
Pred, +
List1, ?
Included, ?
Excluded)
call(Pred, X)
succeeds and Excluded contains the remaining elements.
partition(+
Pred, +
List1, ?
Lesser, ?
Equal, ?
Greater)
call(Pred, Xi, Place)
, where Place must be unified to one
of <
, =
or >
. Pred
must be deterministic.
Examples:
%given plus(X,Y,Z) :- Z is X + Y. plus_if_pos(X,Y,Z) :- Y > 0, Z is X + Y. vars(X, Y, [X|Y]) :- var(X), !. vars(_, Y, Y). trans(TermIn, TermOut) :- nonvar(TermIn), TermIn =.. [p|Args], TermOut =..[q|Args], !. trans(X,X). %success maplist(plus(1), [1,2,3,4], [2,3,4,5]). checklist(var, [X,Y,Z]). selectlist(<(0), [-1,0,1], [1]). convlist(plus_if_pos(1), [-1,0,1], [2]). sumlist(plus, [1,2,3,4], 1, 11). mapargs(number_atom,s(1,2,3), s('1','2','3')). sumargs(vars, s(1,X,2,Y), [], [Y,X]).m apnodes(trans, p(a,p(b,a),c), q(a,q(b,a),c)). checknodes(\==(T), p(X,p(Y,X),Z)). sumnodes(vars, [c(X), p(X,Y), q(Y)], [], [Y,Y,X,X]). % another one maplist(mapargs(number_atom),[c(1),s(1,2,3)],[c('1'),s('1','2','3')]).
This package provides a fast implementation of multi-dimensional
matrices of integers and floats. In contrast to dynamic arrays, these
matrices are multi-dimensional and compact. In contrast to static
arrays. these arrays are allocated in the stack. Matrices are available
by loading the library library(matrix)
.
Notice that the functionality in this library is only partial. Please contact the YAP maintainers if you require extra functionality.
matrix_new(+
Type,+
Dims,-
Matrix)
ints
or floats
, and with a list of dimensions Dims.
The matrix will be initialised to zeros.
?- matrix_new(ints,[2,3],Matrix). Matrix = 0
Notice that currently YAP will always write a matrix as 0
.
matrix_new(+
Type,+
Dims,+
List,-
Matrix)
ints
or floats
, with dimensions Dims, and
initialised from list List.
matrix_new_set(?
Dims,+
OldMatrix,+
Value,-
NewMatrix)
matrix_dims(+
Matrix,-
Dims)
matrix_ndims(+
Matrix,-
Dims)
matrix_size(+
Matrix,-
NElems)
matrix_type(+
Matrix,-
Type)
matrix_to_list(+
Matrix,-
Elems)
matrix_get(+
Matrix,+
Position,-
Elem)
matrix_set(+
Matrix,+
Position,+
Elem)
matrix_set_all(+
Matrix,+
Elem)
matrix_add(+
Matrix,+
Position,+
Operand)
matrix_inc(+
Matrix,+
Position)
matrix_inc(+
Matrix,+
Position,-
Element)
matrix_dec(+
Matrix,+
Position)
matrix_dec(+
Matrix,+
Position,-
Element)
matrix_arg_to_offset(+
Matrix,+
Position,-
Offset)
matrix_offset_to_arg(+
Matrix,-
Offset,+
Position)
matrix_max(+
Matrix,+
Max)
matrix_maxarg(+
Matrix,+
Maxarg)
matrix_min(+
Matrix,+
Min)
matrix_minarg(+
Matrix,+
Minarg)
matrix_sum(+
Matrix,+
Sum)
matrix_agg_lines(+
Matrix,+
Aggregate)
matrix_agg_cols(+
Matrix,+
Aggregate)
matrix_op(+
Matrix1,+
Matrix2,+
Op,-
Result)
+
) is supported.
matrix_op_to_all(+
Matrix1,+
Op,+
Operand,-
Result)
+
), multiplication (+
), and division
(/
) are supported.
matrix_op_to_lines(+
Matrix1,+
Lines,+
Op,-
Result)
/
) is supported.
matrix_op_to_cols(+
Matrix1,+
Cols,+
Op,-
Result)
+
) is
supported. Notice that Cols will have n-1 dimensions.
matrix_shuffle(+
Matrix,+
NewOrder,-
Shuffle)
matrix_transpose(+
Matrix,-
Transpose)
matrix_transpose(Matrix,Transpose) :- matrix_shuffle(Matrix,[1,0],Transpose).
matrix_expand(+
Matrix,+
NewDimensions,-
New)
matrix_select(+
Matrix,+
Dimension,+
Index,-
New)
matrix_column(+
Matrix,+
Column,-
NewMatrix)
The MathWorks MATLAB is a widely used package for array
processing. YAP now includes a straightforward interface to MATLAB. To
actually use it, you need to install YAP calling configure
with
the --with-matlab=DIR
option, and you need to call
use_module(library(lists))
command.
Accessing the matlab dynamic libraries can be complicated. In Linux machines, to use this interface, you may have to set the environment variable LD_LIBRARY_PATH. Next, follows an example using bash in a 64-bit Linux PC:
export LD_LIBRARY_PATH=''$MATLAB_HOME"/sys/os/glnxa64:''$MATLAB_HOME"/bin/glnxa64:''$LD_LIBRARY_PATH"
where MATLAB_HOME
is the directory where matlab is installed
at. Please replace ax64
for x86
on a 32-bit PC.
start_matlab(+
Options)
close_matlab
matlab_on
matlab_eval_string(+
Command)
matlab_eval_string(+
Command, -
Answer)
matlab_cells(+
Size, ?
Array)
cells
.
matlab_cells(+
SizeX, +
SizeY, ?
Array)
cells
.
matlab_initialized_cells(+
SizeX, +
SizeY, +
List, ?
Array)
matlab_matrix(+
SizeX, +
SizeY, +
List, ?
Array)
matlab_set(+
MatVar, +
X, +
Y, +
Value)
matlab_get_variable(+
MatVar, -
List)
matlab_item(+
MatVar, +
X, ?
Val)
C
notation for matrix access (ie, starting from 0).
matlab_item(+
MatVar, +
X, +
Y, ?
Val)
C
notation for matrix access (ie, starting from 0).
matlab_item1(+
MatVar, +
X, ?
Val)
matlab_item1(+
MatVar, +
X, +
Y, ?
Val)
matlab_sequence(+
Min, +
Max, ?
Array)
matlab_vector(+
Size, +
List, ?
Array)
matlab_zeros(+
Size, ?
Array)
zeros
.
matlab_zeros(+
SizeX, +
SizeY, ?
Array)
zeros
.
matlab_zeros(+
SizeX, +
SizeY, +
SizeZ, ?
Array)
zeros
.
matlab_zeros(+
SizeX, +
SizeY, +
SizeZ, ?
Array)
zeros
.
The following routines implement well-known data-structures using global
non-backtrackable variables (implemented on the Prolog stack). The
data-structures currently supported are Queues, Heaps, and Beam for Beam
search. They are allowed through library(nb)
.
nb_queue(-
Queue)
nb_queue_close(+
Queue, -
Head, ?
Tail)
nb_queue_enqueue(+
Queue, +
Element)
nb_queue_dequeue(+
Queue, -
Element)
nb_queue_peek(+
Queue, -
Element)
nb_queue_size(+
Queue, -
Size)
nb_queue_empty(+
Queue)
nb_heap(+
DefaultSize,-
Heap)
nb_heap_close(+
Heap)
nb_heap_add(+
Heap, +
Key, +
Value)
nb_heap_del(+
Heap, -
Key, -
Value)
nb_heap_peek(+
Heap, -
Key, -
Value))
nb_heap_size(+
Heap, -
Size)
nb_heap_empty(+
Heap)
nb_beam(+
DefaultSize,-
Beam)
nb_beam_close(+
Beam)
nb_beam_add(+
Beam, +
Key, +
Value)
nb_beam_del(+
Beam, -
Key, -
Value)
nb_beam_peek(+
Beam, -
Key, -
Value))
nb_beam_size(+
Beam, -
Size)
nb_beam_empty(+
Beam)
The following ordered set manipulation routines are available once
included with the use_module(library(ordsets))
command. An
ordered set is represented by a list having unique and ordered
elements. Output arguments are guaranteed to be ordered sets, if the
relevant inputs are. This is a slightly patched version of Richard
O'Keefe's original library.
list_to_ord_set(+
List, ?
Set)
merge(+
List1, +
List2, -
Merged)
Notice that merge/3
will not remove duplicates, so merging
ordered sets will not necessarily result in an ordered set. Use
ord_union/3
instead.
ord_add_element(+
Set1, +
Element, ?
Set2)
merge(Set1, [Element], Set2)
, but a
bit faster, and certainly more clearly. The same as ord_insert/3
.
ord_del_element(+
Set1, +
Element, ?
Set2)
ord_disjoint(+
Set1, +
Set2)
ord_member(+
Element, +
Set)
ord_insert(+
Set1, +
Element, ?
Set2)
merge(Set1, [Element], Set2)
, but a
bit faster, and certainly more clearly. The same as ord_add_element/3
.
ord_intersect(+
Set1, +
Set2)
ord_intersection(+
Set1, +
Set2, ?
Intersection)
ord_intersection(+
Set1, +
Set2, ?
Intersection, ?
Diff)
ord_seteq(+
Set1, +
Set2)
ord_setproduct(+
Set1, +
Set2, -
Set)
ord_subset(+
Set1, +
Set2)
ord_subtract(+
Set1, +
Set2, ?
Difference)
ord_symdiff(+
Set1, +
Set2, ?
Difference)
ord_union(+
Sets, ?
Union)
ord_union(+
Set1, +
Set2, ?
Union)
ord_union(+
Set1, +
Set2, ?
Union, ?
Diff)
The following routines produce random non-negative integers in the range 0 .. 2^(w-1) -1, where w is the word size available for integers, e.g. 32 for Intel machines and 64 for Alpha machines. Note that the numbers generated by this random number generator are repeatable. This generator was originally written by Allen Van Gelder and is based on Knuth Vol 2.
rannum(-
I)
rannum(X) :- yap_flag(max_integer,MI), rannum(R), X is R/MI.
to obtain a floating point number uniformly distributed between 0 and 1.
ranstart
ranstart/0
built-in is always called by the system when loading
the package.
ranstart(+
Seed)
ranunif(+
Range,-
I)
ranunif/2
produces a uniformly distributed non-negative random
integer I over a caller-specified range R. If range is R,
the result is in 0 .. R-1.
The following queue manipulation routines are available once
included with the use_module(library(queues))
command. Queues are
implemented with difference lists.
make_queue(+
Queue)
join_queue(+
Element, +
OldQueue, -
NewQueue)
list_join_queue(+
List, +
OldQueue, -
NewQueue)
jump_queue(+
Element, +
OldQueue, -
NewQueue)
list_jump_queue(+
List, +
OldQueue, +
NewQueue)
head_queue(+
Queue, ?
Head)
serve_queue(+
OldQueue, +
Head, -
NewQueue)
empty_queue(+
Queue)
length_queue(+
Queue, -
Length)
list_to_queue(+
List, -
Queue)
queue_to_list(+
Queue, -
List)
The following random number operations are included with the
use_module(library(random))
command. Since YAP-4.3.19 YAP uses
the O'Keefe public-domain algorithm, based on the "Applied Statistics"
algorithm AS183.
getrand(-
Key)
rand(X,Y,Z)
describing the
current state of the random number generator.
random(-
Number)
[0...1)
.
random(+
LOW, +
HIGH, -
NUMBER)
[LOW...HIGH)
. If both LOW and HIGH are
integers then NUMBER will also be an integer, otherwise
NUMBER will be a floating-point number.
randseq(+
LENGTH, +
MAX, -
Numbers)
[1�...
MAX)
.
randset(+
LENGTH, +
MAX, -
Numbers)
[1�...
MAX)
.
setrand(+
Key)
rand(X,Y,Z)
to set a new state for the
random number generator. The integer X
must be in the range
[1...30269)
, the integer Y
must be in the range
[1...30307)
, and the integer Z
must be in the range
[1...30323)
.
The readutil
library contains primitives to read lines, files,
multiple terms, etc.
read_line_to_codes(+
Stream, -
Codes)
read_line_to_codes/3
,
this predicate removes trailing newline character.
On end-of-file the atom end_of_file
is returned. See also
at_end_of_stream/[0,1]
.
read_line_to_codes(+
Stream, -
Codes, ?
Tail)
read_line_to_codes/2
, the newline is retained in the
output. This predicate is especially useful for reading a block of
lines upto some delimiter. The following example reads an HTTP header
ended by a blank line:
read_header_data(Stream, Header) :- read_line_to_codes(Stream, Header, Tail), read_header_data(Header, Stream, Tail). read_header_data("\r\n", _, _) :- !. read_header_data("\n", _, _) :- !. read_header_data("", _, _) :- !. read_header_data(_, Stream, Tail) :- read_line_to_codes(Stream, Tail, NewTail), read_header_data(Tail, Stream, NewTail).
read_stream_to_codes(+
Stream, -
Codes)
read_stream_to_codes(+
Stream, -
Codes, ?
Tail)
read_stream_to_codes/2
.
read_file_to_codes(+
Spec, -
Codes, +
Options)
read_file_to_terms(+
Spec, -
Terms, +
Options)
Red-Black trees are balanced search binary trees. They are named because nodes can be classified as either red or black. The code we include is based on "Introduction to Algorithms", second edition, by Cormen, Leiserson, Rivest and Stein. The library includes routines to insert, lookup and delete elements in the tree.
rb_new(?
T)
rb_empty(?
T)
is_rbtree(+
T)
rb_insert(+
T0,+
Key,?
Value,+
TF)
Add a new element with key Key and Value to the tree
T0 creating a new red-black tree TF. Fails is an element
with Key exists in the tree.
rb_lookup(+
Key,-
Value,+
T)
rb_lookupall(+
Key,-
Value,+
T)
rb_delete(+
T,+
Key,-
TN)
rb_delete(+
T,+
Key,-
Val,-
TN)
rb_del_min(+
T,-
Key,-
Val,-
TN)
rb_del_max(+
T,-
Key,-
Val,-
TN)
rb_update(+
T,+
Key,+
NewVal,-
TN)
rb_apply(+
T,+
Key,+
G,-
TN)
call(G,Val0,ValF)
holds, then TN differs from
T only in that Key is associated with value ValF in
tree TN. Fails if it cannot find Key in T, or if
call(G,Val0,ValF)
is not satisfiable.
rb_visit(+
T,-
Pairs)
rb_size(+
T,-
Size)
rb_keys(+
T,+
Keys)
rb_map(+
T,+
G,-
TN)
call(G,Val0,ValF)
holds, then the value associated with Key
in TN is ValF. Fails if or if call(G,Val0,ValF)
is not
satisfiable for all Var0.
rb_partial_map(+
T,+
Keys,+
G,-
TN)
call(G,Val0,ValF)
holds, then the value associated with Key in TN is
ValF. Fails if or if call(G,Val0,ValF)
is not satisfiable
for all Var0. Assumes keys are not repeated.
rb_clone(+
T,+
NT,+
Nodes)
rb_min(+
T,-
Key,-
Value)
rb_max(+
T,-
Key,-
Value)
rb_next(+
T, +
Key,-
Next,-
Value)
rb_previous(+
T, +
Key,-
Previous,-
Value)
list_to_rbtree(+
L, -
T)
ord_list_to_rbtree(+
L, -
T)
This library includes routines to determine whether a regular expression
matches part or all of a string. The routines can also return which
parts parts of the string matched the expression or subexpressions of
it. This library relies on Henry Spencer's C
-package and is only
available in operating systems that support dynamic loading. The
C
-code has been obtained from the sources of FreeBSD-4.0 and is
protected by copyright from Henry Spencer and from the Regents of the
University of California (see the file library/regex/COPYRIGHT for
further details).
Much of the description of regular expressions below is copied verbatim from Henry Spencer's manual page.
A regular expression is zero or more branches, separated by “|”. It matches anything that matches one of the branches.
A branch is zero or more pieces, concatenated. It matches a match for the first, followed by a match for the second, etc.
A piece is an atom possibly followed by “*”, “+”, or “?”. An atom followed by “*” matches a sequence of 0 or more matches of the atom. An atom followed by “+” matches a sequence of 1 or more matches of the atom. An atom followed by “?” matches a match of the atom, or the null string.
An atom is a regular expression in parentheses (matching a match for the regular expression), a range (see below), “.” (matching any single character), “^” (matching the null string at the beginning of the input string), “$” (matching the null string at the end of the input string), a “\” followed by a single character (matching that character), or a single character with no other significance (matching that character).
A range is a sequence of characters enclosed in “[]”. It normally matches any single character from the sequence. If the sequence begins with “^”, it matches any single character not from the rest of the sequence. If two characters in the sequence are separated by “-”, this is shorthand for the full list of ASCII characters between them (e.g. “[0-9]” matches any decimal digit). To include a literal “]” in the sequence, make it the first character (following a possible “^”). To include a literal “-”, make it the first or last character.
regexp(+
RegExp,+
String,+
Opts)
nocase
: Causes upper-case characters in String to
be treated as lower case during the matching process.
regexp(+
RegExp,+
String,+
Opts,?
SubMatchVars)
The options may be:
nocase
: Causes upper-case characters in String to
be treated as lower case during the matching process.
indices
: Changes what is stored in
SubMatchVars. Instead of storing the matching characters from
String, each variable will contain a term of the form IO-IF
giving the indices in String of the first and last characters in
the matching range of characters.
In general there may be more than one way to match a regular expression to an input string. For example, consider the command
regexp("(a*)b*","aabaaabb", [], [X,Y])
Considering only the rules given so far, X and Y could end up
with the values "aabb"
and "aa"
, "aaab"
and
"aaa"
, "ab"
and "a"
, or any of several other
combinations. To resolve this potential ambiguity regexp
chooses among
alternatives using the rule “first then longest”. In other words, it
considers the possible matches in order working from left to right
across the input string and the pattern, and it attempts to match longer
pieces of the input string before shorter ones. More specifically, the
following rules apply in decreasing order of priority:
In the example from above, "(a*)b*"
matches "aab"
: the
"(a*)"
portion of the pattern is matched first and it consumes
the leading "aa"
; then the "b*"
portion of the pattern
consumes the next "b"
. Or, consider the following example:
regexp("(ab|a)(b*)c", "abc", [], [X,Y,Z])
After this command X will be "abc"
, Y will be
"ab"
, and Z will be an empty string. Rule 4 specifies that
"(ab|a)"
gets first shot at the input string and Rule 2 specifies
that the "ab"
sub-expression is checked before the "a"
sub-expression. Thus the "b"
has already been claimed before the
"(b*)"
component is checked and (b*)
must match an empty string.
This section discusses the functionality of the (autoload)
library(shlib)
, providing an interface to manage shared
libraries.
One of the files provides a global function install_mylib()
that
initialises the module using calls to PL_register_foreign()
. Here is a
simple example file mylib.c
, which creates a Windows MessageBox:
#include <windows.h> #include <SWI-Prolog.h> static foreign_t pl_say_hello(term_t to) { char *a; if ( PL_get_atom_chars(to, &a) ) { MessageBox(NULL, a, "DLL test", MB_OK|MB_TASKMODAL); PL_succeed; } PL_fail; } install_t install_mylib() { PL_register_foreign("say_hello", 1, pl_say_hello, 0); }
Now write a file mylib.pl:
:- module(mylib, [ say_hello/1 ]). :- use_foreign_library(foreign(mylib)).
The file mylib.pl can be loaded as a normal Prolog file and provides the predicate defined in C.
[det]load_foreign_library(:
FileSpec)
[det]load_foreign_library(:
FileSpec, +
Entry:atom)
install_
, followed by the file base-name. E.g., the
load-call below calls the function install_mylib()
. If the platform
prefixes extern functions with _
, this prefix is added before
calling.
... load_foreign_library(foreign(mylib)), ...
FileSpec is a specification for
absolute_file_name/3
. If searching the file fails, the plain
name is passed to the OS to try the default method of the OS for
locating foreign objects. The default definition of
file_search_path/2
searches <prolog home>/lib/Yap.
See also
use_foreign_library/1,2
are intended for use in
directives.
[det]use_foreign_library(+
FileSpec)
[det]use_foreign_library(+
FileSpec, +
Entry:atom)
initialization/2
with the option
now. This is similar to using:
:- initialization(load_foreign_library(foreign(mylib))).
but using the initialization/1
wrapper causes the library to
be loaded after loading of the file in which it appears is
completed, while use_foreign_library/1
loads the library
immediately. I.e. the difference is only relevant if the remainder
of the file uses functionality of the C
-library.
[det]unload_foreign_library(+
FileSpec)
[det]unload_foreign_library(+
FileSpec, +
Exit:atom)
uninstall_
, followed by the file base-name.
current_foreign_library(?
File, ?
Public)
Splay trees are explained in the paper "Self-adjusting Binary Search Trees", by D.D. Sleator and R.E. Tarjan, JACM, vol. 32, No.3, July 1985, p. 668. They are designed to support fast insertions, deletions and removals in binary search trees without the complexity of traditional balanced trees. The key idea is to allow the tree to become unbalanced. To make up for this, whenever we find a node, we move it up to the top. We use code by Vijay Saraswat originally posted to the Prolog mailing-list.
splay_access(-
Return,+
Key,?
Val,+
Tree,-
NewTree)
true
. Otherwise unify Return with
null
. The variable NewTree unifies with the new tree.
splay_delete(+
Key,?
Val,+
Tree,-
NewTree)
splay_init(-
NewTree)
splay_insert(+
Key,?
Val,+
Tree,-
NewTree)
splay_join(+
LeftTree,+
RighTree,-
NewTree)
splay_split(+
Key,?
Val,+
Tree,-
LeftTree,-
RightTree)
From Version 4.3.2 onwards YAP implements SICStus Prolog compatible
String I/O. The library allows users to read from and write to a memory
buffer as if it was a file. The memory buffer is built from or converted
to a string of character codes by the routines in library. Therefore, if
one wants to read from a string the string must be fully instantiated
before the library built-in opens the string for reading. These commands
are available through the use_module(library(charsio))
command.
format_to_chars(+
Form, +
Args, -
Result)
format/2
with form Form and
arguments Args outputting the result to the string of character
codes Result.
format_to_chars(+
Form, +
Args, -
Result, -
Result0)
format/2
with form Form and
arguments Args outputting the result to the difference list of
character codes Result-Result0.
write_to_chars(+
Term, -
Result)
write/1
with argument Term
outputting the result to the string of character codes Result.
write_to_chars(+
Term, -
Result0, -
Result)
write/1
with argument Term
outputting the result to the difference list of character codes
Result-Result0.
atom_to_chars(+
Atom, -
Result)
atom_to_chars(+
Atom, -
Result0, -
Result)
number_to_chars(+
Number, -
Result)
number_to_chars(+
Number, -
Result0, -
Result)
atom_to_term(+
Atom, -
Term, -
Bindings)
read_term/2
using the option variable_names
and return the read term in Term and the variable bindings in Bindings. Bindings is a list of Name = Var
couples, thus providing access to the actual variable names. See also read_term/2
. If Atom has no valid syntax, a syntax_error exception is raised.
term_to_atom(?
Term, ?
Atom)
write_term/2
with the option quoted(true).
read_from_chars(+
Chars, -
Term)
open_chars_stream(+
Chars, -
Stream)
with_output_to_chars(?
Goal, -
Chars)
with_output_to_chars(?
Goal, ?
Chars0, -
Chars)
with_output_to_chars(?
Goal, -
Stream, ?
Chars0, -
Chars)
The implementation of the character IO operations relies on three YAP built-ins:
charsio:open_mem_read_stream(+
String, -
Stream)
charsio:open_mem_write_stream(-
Stream)
charsio:peek_mem_write_stream(-
Stream, L0, L)
charsio
in
init.yap
. Novel procedures for manipulating strings by explicitly
importing these built-ins.
YAP does not currently support opening a charsio
stream in
append
mode, or seeking in such a stream.
YAP now provides a library of system utilities compatible with the
SICStus Prolog system library. This library extends and to some point
replaces the functionality of Operating System access routines. The
library includes Unix/Linux and Win32 C
code. They
are available through the use_module(library(system))
command.
datime(datime(-
Year, -
Month, -
DayOfTheMonth,
datime/1
procedure returns the current date and time, with
information on Year, Month, DayOfTheMonth,
Hour, Minute, and Second. The Hour is returned
on local time. This function uses the WIN32
GetLocalTime
function or the Unix localtime
function.
?- datime(X). X = datime(2001,5,28,15,29,46) ?
mktime(datime(+
Year, +
Month, +
DayOfTheMonth,
mktime/1
procedure returns the number of Seconds
elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time
(UTC). The user provides information on Year, Month,
DayOfTheMonth, Hour, Minute, and Second. The
Hour is given on local time. This function uses the WIN32
GetLocalTime
function or the Unix mktime
function.
?- mktime(datime(2001,5,28,15,29,46),X). X = 991081786 ? ;
delete_file(+
File)
delete_file/1
procedure removes file File. If
File is a directory, remove the directory and all its
subdirectories.
?- delete_file(x).
delete_file(+
File,+
Opts)
delete_file/2
procedure removes file File according to
options Opts. These options are directory
if one should
remove directories, recursive
if one should remove directories
recursively, and ignore
if errors are not to be reported.
This example is equivalent to using the delete_file/1
predicate:
?- delete_file(x, [recursive]).
directory_files(+
Dir,+
List)
directory_files/2
procedures a
listing of all files and directories in the directory:
?- directory_files('.',L), writeq(L). ['Makefile.~1~','sys.so','Makefile','sys.o',x,..,'.']
The predicates uses the dirent
family of routines in Unix
environments, and findfirst
in WIN32.
file_exists(+
File)
file_exists(+
File,+
Permissions)
file_property(+
File,?
Property)
type(
Type)
, which gives whether the file is a regular
file, a directory, a fifo file, or of unknown type;
size(
Size)
, with gives the size for a file, and
mod_time(
Time)
, which gives the last time a file was
modified according to some Operating System dependent
timestamp; mode(
mode)
, gives the permission flags for the
file, and linkto(
FileName)
, gives the file pointed to by a
symbolic link. Properties can be obtained through backtracking:
?- file_property('Makefile',P). P = type(regular) ? ; P = size(2375) ? ; P = mod_time(990826911) ? ; no
make_directory(+
Dir)
rename_file(+
OldFile,+
NewFile)
C
built-in function rename
.
environ(?
EnvVar,+
EnvValue)
?- environ('HOME',X). X = 'C:\\cygwin\\home\\administrator' ?
host_id(-
Id)
hostid
function when available,
host_name(-
Name)
hostname
function in Unix systems when available, and the
GetComputerName
function in WIN32 systems.
kill(
Id,+
SIGNAL)
kill
so one can send signals to groups of
processes. In WIN32 the predicate is an interface to
TerminateProcess
, so it kills Id independently of SIGNAL.
mktemp(
Spec,-
File)
mktemp
: given a Spec, that is a file
name with six X to it, create a file name File. Use
tmpnam/1
instead.
pid(-
Id)
tmpnam(-
File)
tmp_file(-
File)
exec(+
Command,[+
InputStream,+
OutputStream,+
ErrorStream],-
PID)
bin/sh -c
in Unix.
The following example demonstrates the use of exec/3
to send a
command and process its output:
exec(ls,[std,pipe(S),null],P),repeat, get0(S,C), (C = -1, close(S) ! ; put(C)).
The streams may be one of standard stream, std
, null stream,
null
, or pipe(S)
, where S is a pipe stream. Note
that it is up to the user to close the pipe.
working_directory(-
CurDir,?
NextDir)
popen(+
Command, +
TYPE, -
Stream)
read
or write
, not both. The stream should be closed
using close/1
, there is no need for a special pclose
command.
The following example demonstrates the use of popen/3
to process
the output of a command, as exec/3
would do:
?- popen(ls,read,X),repeat, get0(X,C), (C = -1, ! ; put(C)). X = 'C:\\cygwin\\home\\administrator' ?
The WIN32 implementation of popen/3
relies on exec/3
.
shell
SHELL
. In WIN32 environment YAP will use COMSPEC
if
SHELL
is undefined.
shell(+
Command)
SHELL
with the option
" -c "
. In WIN32 environment YAP will use COMSPEC
if
SHELL
is undefined, in this case with the option " /c "
.
shell(+
Command,-
Status)
SHELL
with the option " -c "
. In
WIN32 environment YAP will use COMSPEC
if SHELL
is
undefined, in this case with the option " /c "
.
sleep(+
Time)
usleep
if the number of
seconds is below one, and sleep
if it is over a second. The WIN32
implementation uses Sleep
for both cases.
system
/bin/sh
in Unix systems and COMSPEC
in
WIN32.
system(+
Command,-
Res)
system
: execute command Command and unify
Res with the result.
wait(+
PID,-
Status)
The next routines provide a set of commonly used utilities to manipulate
terms. Most of these utilities have been implemented in C
for
efficiency. They are available through the
use_module(library(terms))
command.
cyclic_term(?
Term)
term_hash(+
Term, ?
Hash)
0
to, but not including, 33554432
.
term_hash(+
Term, +
Depth, +
Range, ?
Hash)
0
to, but
not including, Range. If Depth is -1
the whole term
is considered. Otherwise, the term is considered only up to depth
1
, where the constants and the principal functor have depth
1
, and an argument of a term with depth I has depth I+1.
variables_within_term(+
Variables,?
Term, -
OutputVariables)
new_variables_in_term(+
Variables,?
Term, -
OutputVariables)
variant(?
Term1, ?
Term2)
subsumes(?
Term1, ?
Term2)
subsumes_chk(?
Term1, ?
Term2)
variable_in_term(?
Term,?
Var)
unifiable(?
Term1, ?
Term2, -
Bindings)
The next routines provide a set of utilities to create and manipulate
prefix trees of Prolog terms. Tries were originally proposed to
implement tabling in Logic Programming, but can be used for other
purposes. The tries will be stored in the Prolog database and can seen
as alternative to assert
and record
family of
primitives. Most of these utilities have been implemented in C
for efficiency. They are available through the
use_module(library(tries))
command.
trie_open(-
Id)
trie_close(+
Id)
trie_close_all
trie_mode(?
Mode)
std
(default) or rev
.
trie_put_entry(+
Trie,+
Term,-
Ref)
trie_check_entry(+
Trie,+
Term,-
Ref)
trie_get_entry(+
Ref,-
Term)
trie_remove_entry(+
Ref)
trie_remove_subtree(+
Ref)
trie_save(+
Trie,+
FileName)
trie_load(+
Trie,+
FileName)
trie_stats(-
Memory,-
Tries,-
Entries,-
Nodes)
trie_max_stats(-
Memory,-
Tries,-
Entries,-
Nodes)
trie_usage(+
Trie,-
Entries,-
Nodes,-
VirtualNodes)
trie_print(+
Trie)
call_cleanup/1 and call_cleanup/2 allow predicates to register
code for execution after the call is finished. Predicates can be
declared to be fragile to ensure that call_cleanup is called
for any Goal which needs it. This library is loaded with the
use_module(library(cleanup))
command.
:- fragile
P,....,
Pn:- fragile foo/1,bar:baz/2.
call_cleanup(:
Goal)
call_cleanup(:
Goal, :
CleanUpGoal)
setup_call_cleanup(:
Setup,:
Goal, :
CleanUpGoal)
(Setup, Goal)
. For each sucessful execution of Setup, calling Goal, the
cleanup handler Cleanup is guaranteed to be called exactly once.
This will happen after Goal completes, either through failure,
deterministic success, commit, or an exception. Setup will
contain the goals that need to be protected from asynchronous interrupts
such as the ones received from call_with_time_limit/2
or thread_signal/2
. In
most uses, Setup will perform temporary side-effects required by
Goal that are finally undone by Cleanup.
Success or failure of Cleanup is ignored and choice-points it
created are destroyed (as once/1
). If Cleanup throws an exception,
this is executed as normal.
Typically, this predicate is used to cleanup permanent data storage required to execute Goal, close file-descriptors, etc. The example below provides a non-deterministic search for a term in a file, closing the stream as needed.
term_in_file(Term, File) :- setup_call_cleanup(open(File, read, In), term_in_stream(Term, In), close(In) ). term_in_stream(Term, In) :- repeat, read(In, T), ( T == end_of_file -> !, fail ; T = Term ).
Note that it is impossible to implement this predicate in Prolog other than
by reading all terms into a list, close the file and call member/2
.
Without setup_call_cleanup/3
there is no way to gain control if the
choice-point left by repeat
is removed by a cut or an exception.
setup_call_cleanup/2
can also be used to test determinism of a goal:
?- setup_call_cleanup(true,(X=1;X=2), Det=yes). X = 1 ; X = 2, Det = yes ;
This predicate is under consideration for inclusion into the ISO standard.
For compatibility with other Prolog implementations see call_cleanup/2
.
setup_call_catcher_cleanup(:
Setup,:
Goal, +
Catcher,:
CleanUpGoal)
setup_call_cleanup(
Setup,
Goal,
Cleanup)
with
additional information on the reason of calling Cleanup. Prior
to calling Cleanup, Catcher unifies with the termination
code. If this unification fails, Cleanup is
not called.
on_cleanup(+
CleanUpGoal)
cleanup_all
There are some private predicates which could be used in special cases, such as manually setting up cleanup-contexts and registering CleanUpGoals for other than the current cleanup-context. Read the Source Luke.
The time_out/3 command relies on the alarm/3 built-in to
implement a call with a maximum time of execution. The command is
available with the use_module(library(timeout))
command.
time_out(+
Goal, +
Timeout, -
Result)
This command is implemented by activating an alarm at procedure entry. If the timer expires before the goal completes, the alarm will throw an exception timeout.
One should note that time_out/3
is not reentrant, that is, a goal
called from time_out
should never itself call
time_out/3
. Moreover, time_out/3
will deactivate any previous
alarms set by alarm/3
and vice-versa, hence only one of these
calls should be used in a program.
Last, even though the timer is set in milliseconds, the current implementation relies on alarm/3, and therefore can only offer precision on the scale of seconds.
The following queue manipulation routines are available once
included with the use_module(library(trees))
command.
get_label(+
Index, +
Tree, ?
Label)
list_to_tree(+
List, -
Tree)
map_tree(+
Pred, +
OldTree, -
NewTree)
Pred(Old,New)
is true for corresponding elements of the two trees.
put_label(+
Index, +
OldTree, +
Label, -
NewTree)
tree_size(+
Tree, -
Size)
tree_to_list(+
Tree, -
List)
The following graph manipulation routines are based in code originally written by Richard O'Keefe. The code was then extended to be compatible with the SICStus Prolog ugraphs library. The routines assume directed graphs, undirected graphs may be implemented by using two edges. Graphs are represented in one of two ways:
These built-ins are available once included with the
use_module(library(ugraphs))
command.
vertices_edges_to_ugraph(+
Vertices, +
Edges, -
Graph)
?- vertices_edges_to_ugraph([],[1-3,2-4,4-5,1-5],L). L = [1-[3,5],2-[4],3-[],4-[5],5-[]] ?
In this case all edges are defined implicitly. The next example shows three unconnected edges:
?- vertices_edges_to_ugraph([6,7,8],[1-3,2-4,4-5,1-5],L). L = [1-[3,5],2-[4],3-[],4-[5],5-[],6-[],7-[],8-[]] ?
vertices(+
Graph, -
Vertices)
?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V). L = [1,2,3,4,5]
edges(+
Graph, -
Edges)
?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V). L = [1,2,3,4,5]
add_vertices(+
Graph, +
Vertices, -
NewGraph)
?- add_vertices([1-[3,5],2-[4],3-[],4-[5], 5-[],6-[],7-[],8-[]], [0,2,9,10,11], NG). NG = [0-[],1-[3,5],2-[4],3-[],4-[5],5-[], 6-[],7-[],8-[],9-[],10-[],11-[]]
del_vertices(+
Graph, +
Vertices, -
NewGraph)
?- del_vertices([2,1],[1-[3,5],2-[4],3-[], 4-[5],5-[],6-[],7-[2,6],8-[]],NL). NL = [3-[],4-[5],5-[],6-[],7-[6],8-[]]
add_edges(+
Graph, +
Edges, -
NewGraph)
?- add_edges([1-[3,5],2-[4],3-[],4-[5],5-[],6-[], 7-[],8-[]],[1-6,2-3,3-2,5-7,3-2,4-5],NL). NL = [1-[3,5,6],2-[3,4],3-[2],4-[5],5-[7],6-[],7-[],8-[]]
del_edges(+
Graph, +
Edges, -
NewGraph)
?- del_edges([1-[3,5],2-[4],3-[],4-[5],5-[], 6-[],7-[],8-[]], [1-6,2-3,3-2,5-7,3-2,4-5,1-3],NL). NL = [1-[5],2-[4],3-[],4-[],5-[],6-[],7-[],8-[]]
transpose(+
Graph, -
NewGraph)
O(|V|^2)
. In the next example:
?- transpose([1-[3,5],2-[4],3-[], 4-[5],5-[],6-[],7-[],8-[]], NL). NL = [1-[],2-[],3-[1],4-[2],5-[1,4],6-[],7-[],8-[]]
Notice that an undirected graph is its own transpose.
neighbors(+
Vertex, +
Graph, -
Vertices)
?- neighbors(4,[1-[3,5],2-[4],3-[], 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). NL = [1,2,7,5]
neighbours(+
Vertex, +
Graph, -
Vertices)
?- neighbours(4,[1-[3,5],2-[4],3-[], 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). NL = [1,2,7,5]
complement(+
Graph, -
NewGraph)
?- complement([1-[3,5],2-[4],3-[], 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). NL = [1-[2,4,6,7,8],2-[1,3,5,6,7,8],3-[1,2,4,5,6,7,8], 4-[3,5,6,8],5-[1,2,3,4,6,7,8],6-[1,2,3,4,5,7,8], 7-[1,2,3,4,5,6,8],8-[1,2,3,4,5,6,7]]
compose(+
LeftGraph, +
RightGraph, -
NewGraph)
?- compose([1-[2],2-[3]],[2-[4],3-[1,2,4]],L). L = [1-[4],2-[1,2,4],3-[]]
top_sort(+
Graph, -
Sort)
?- top_sort([_138-[_219],_219-[_139], _139-[]],L). L = [_138,_219,_139]
top_sort(+
Graph, -
Sort0, -
Sort)
transitive_closure(+
Graph, +
Closure)
?- transitive_closure([1-[2,3],2-[4,5],4-[6]],L). L = [1-[2,3,4,5,6],2-[4,5,6],4-[6]]
reachable(+
Node, +
Graph, -
Vertices)
?- reachable(1,[1-[3,5],2-[4],3-[],4-[5],5-[]],V). V = [1,3,5]
The following graph manipulation routines use the red-black tree library to try to avoid linear-time scans of the graph for all graph operations. Graphs are represented as a red-black tree, where the key is the vertex, and the associated value is a list of vertices reachable from that vertex through an edge (ie, a list of edges).
dgraph_new(+
Graph)
dgraph_vertices(+
Graph, -
Vertices)
dgraph_edge(+
N1, +
N2, +
Graph)
dgraph_edges(+
Graph, -
Edges)
dgraph_add_vertices(+
Graph, +
Vertex, -
NewGraph)
dgraph_add_vertices(+
Graph, +
Vertices, -
NewGraph)
dgraph_del_vertex(+
Graph, +
Vertex, -
NewGraph)
dgraph_del_vertices(+
Graph, +
Vertices, -
NewGraph)
dgraph_add_edge(+
Graph, +
N1, +
N2, -
NewGraph)
dgraph_add_edges(+
Graph, +
Edges, -
NewGraph)
dgraph_del_edge(+
Graph, +
N1, +
N2, -
NewGraph)
dgraph_del_edges(+
Graph, +
Edges, -
NewGraph)
dgraph_to_ugraph(+
Graph, -
UGraph)
ugraph_to_dgraph( +
UGraph, -
Graph)
dgraph_neighbors(+
Vertex, +
Graph, -
Vertices)
dgraph_neighbours(+
Vertex, +
Graph, -
Vertices)
dgraph_complement(+
Graph, -
NewGraph)
dgraph_transpose(+
Graph, -
Transpose)
dgraph_compose(+
Graph1, +
Graph2, -
ComposedGraph)
dgraph_transitive_closure(+
Graph, -
Closure)
dgraph_symmetric_closure(+
Graph, -
Closure)
dgraph_top_sort(+
Graph, -
Vertices)
dgraph_top_sort(+
Graph, -
Vertices, ?
Vertices0)
dgraph_min_path(+
V1, +
V1, +
Graph, -
Path, ?
Costt)
dgraph_max_path(+
V1, +
V1, +
Graph, -
Path, ?
Costt)
dgraph_min_paths(+
V1, +
Graph, -
Paths)
dgraph_isomorphic(+
Vs, +
NewVs, +
G0, -
GF)
dgraph_path(+
Vertex, +
Graph, ?
Path)
dgraph_reachable(+
Vertex, +
Graph, ?
Edges)
The following graph manipulation routines use the red-black tree graph library to implement undirected graphs. Mostly, this is done by having two directed edges per undirected edge.
undgraph_new(+
Graph)
undgraph_vertices(+
Graph, -
Vertices)
undgraph_edge(+
N1, +
N2, +
Graph)
undgraph_edges(+
Graph, -
Edges)
undgraph_add_vertices(+
Graph, +
Vertices, -
NewGraph)
undgraph_del_vertices(+
Graph, +
Vertices, -
NewGraph)
undgraph_add_edges(+
Graph, +
Edges, -
NewGraph)
undgraph_del_edges(+
Graph, +
Edges, -
NewGraph)
undgraph_neighbors(+
Vertex, +
Graph, -
Vertices)
undgraph_neighbours(+
Vertex, +
Graph, -
Vertices)
undgraph_complement(+
Graph, -
NewGraph)
dgraph_to_undgraph( +
DGraph, -
UndGraph)
This library, designed and implemented by Ulrich Neumerkel, provides
lambda expressions to simplify higher order programming based on call/N
.
Lambda expressions are represented by ordinary Prolog terms. There are two kinds of lambda expressions:
Free+\X1^X2^ ..^XN^Goal \X1^X2^ ..^XN^Goal
The second is a shorthand for t+\X1^X2^..^XN^Goal
, where Xi
are the parameters.
Goal is a goal or continuation (Syntax note: Operators within Goal
require parentheses due to the low precedence of the ^
operator).
Free contains variables that are valid outside the scope of the lambda expression. They are thus free variables within.
All other variables of Goal are considered local variables. They must not appear outside the lambda expression. This restriction is currently not checked. Violations may lead to unexpected bindings.
In the following example the parentheses around X>3
are necessary.
?- use_module(library(lambda)). ?- use_module(library(apply)). ?- maplist(\X^(X>3),[4,5,9]). true.
In the following X is a variable that is shared by both instances of the lambda expression. The second query illustrates the cooperation of continuations and lambdas. The lambda expression is in this case a continuation expecting a further argument.
?- Xs = [A,B], maplist(X+\Y^dif(X,Y), Xs). Xs = [A, B], dif(X, A), dif(X, B). ?- Xs = [A,B], maplist(X+\dif(X), Xs). Xs = [A, B], dif(X, A), dif(X, B).
The following queries are all equivalent. To see this, use
the fact f(x,y)
.
?- call(f,A1,A2). ?- call(\X^f(X),A1,A2). ?- call(\X^Y^f(X,Y), A1,A2). ?- call(\X^(X+\Y^f(X,Y)), A1,A2). ?- call(call(f, A1),A2). ?- call(f(A1),A2). ?- f(A1,A2). A1 = x, A2 = y.
Further discussions at http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/ISO-Hiord.
This library provides a set of utilities for interfacing with LAM MPI.
The following routines are available once included with the
use_module(library(lam_mpi))
command. The yap should be
invoked using the LAM mpiexec or mpirun commands (see LAM manual for
more details).
mpi_init
mpi_finalize
mpi_comm_size(-
Size)
mpi_comm_rank(-
Rank)
mpi_version(-
Major,-
Minor)
mpi_send(+
Data,+
Dest,+
Tag)
mpi_isend(+
Data,+
Dest,+
Tag,-
Handle)
mpi_wait
or
mpi_test
predicates. Until mpi_wait
is called, the
memory allocated for the buffer containing the message is not
released.
mpi_recv(?
Source,?
Tag,-
Data)
mpi_irecv(?
Source,?
Tag,-
Handle)
mpi_wait_recv
should be used to obtain the data associated to
the handle.
mpi_wait_recv(?
Handle,-
Status,-
Data)
mpi_test_recv(?
Handle,-
Status,-
Data)
mpi_wait(?
Handle,-
Status)
mpi_send
, the predicate blocks until the message is buffered
or sent by the runtime system. At this point the send buffer is
released. If the operation was a mpi_recv
, it waits until the
message is copied to the receive buffer. Status is unified with
the status of the message.
mpi_test(?
Handle,-
Status)
mpi_barrier
mpi_recv
to receive the messages, one
should use mpi_bcast2
.
mpi_bcast2(+
Root, +
Data)
mpi_bcast3(+
Root, +
Data, +
Tag)
mpi_ibcast(+
Root, +
Data, +
Tag)
mpi_gc
This library provides a way of visualizing a prolog program using modules with blocks.
To use it use: :-use_module(library(block_diagram))
.
make_diagram(+inputfilename, +ouputfilename)
dot -Tpdf filename > output.pdf
.
make_diagram(+inputfilename, +ouputfilename, +predicate, +depth, +extension)
make_diagram/2
but you can define how many of the imported/exporeted predicates will be shown with predicate, and how deep the crawler is allowed to go with depth. The extension is used if the file use module directives do not include a file extension.
Subnodes of SWI-Prolog
This library provides a number of SWI-Prolog builtins that are not by
default in YAP. This support is loaded with the
expects_dialect(swi)
command.
append(?
List1,?
List2,?
List3)
between(+
Low,+
High,?
Value)
inf
, between/3
is true iff
Value less or equal than Low, a feature that is particularly
interesting for generating integers from a certain value.
chdir(+
Dir)
working_directory/2
.
concat_atom(+
List,-
Atom)
atom_concat/3
,
allowing for variables in the list.
concat_atom(?
List,+
Separator,?
Atom)
?- concat_atom([gnu, gnat], ', ', A). A = 'gnu, gnat'
(Unimplemented) This predicate can also be used to split atoms by instantiating Separator and Atom:
?- concat_atom(L, -, 'gnu-gnat'). L = [gnu, gnat]
nth1(+
Index,?
List,?
Elem)
Set environment variable. Name and Value should be
instantiated to atoms or integers. The environment variable will be
passed to shell/[0-2]
and can be requested using getenv/2
.
They also influence expand_file_name/2
.
setenv(+
Name,+
Value)
shell/[0-2]
and can be requested using getenv/2
.
They also influence expand_file_name/2
.
term_to_atom(?
Term,?
Atom)
syntax_error
exception is raised. Otherwise Term is “written” on Atom
using write/1
.
working_directory(-
Old,+
New)
working_directory(CWD, CWD)
to get the current directory. See
also absolute_file_name/2
and chdir/1
.
@
Term1 =@= @
Term2All the predicates in this section call a predicate on all members of a
list or until the predicate called fails. The predicate is called via
call/[2..]
, which implies common arguments can be put in
front of the arguments obtained from the list(s). For example:
?- maplist(plus(1), [0, 1, 2], X). X = [1, 2, 3]
we will phrase this as “Predicate is applied on ...”
maplist(+
Pred,+
List)
maplist/2
fails.
maplist(+
Pred,+
List1,+
List2)
maplist(+
Pred,+
List1,+
List2,+
List4)
forall(+
Cond,+
Action)
?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), Result =:= Formula).
SWI-Prolog global variables are associations between names (atoms) and
terms. They differ in various ways from storing information using
assert/1
or recorda/3
.
nb_setval/2
and
backtrackable assignment using b_setval/2
.
Both b_setval/2
and nb_setval/2
implicitly create a variable if the
referenced name does not already refer to a variable.
Global variables may be initialised from directives to make them
available during the program lifetime, but some considerations are
necessary for saved-states and threads. Saved-states to not store global
variables, which implies they have to be declared with initialization/1
to recreate them after loading the saved state. Each thread has
its own set of global variables, starting with an empty set. Using
thread_inititialization/1
to define a global variable it will be
defined, restored after reloading a saved state and created in all
threads that are created after the registration.
b_setval(+
Name,+
Value)
[]
is created (the empty list). On backtracking the
assignment is reversed.
b_getval(+
Name,-
Value)
copy_term/2
) must be taken. The
b_getval/2
predicate generates errors if Name is not an atom or
the requested variable does not exist.
nb_setval(+
Name,+
Value)
duplicate_term/2
with the atom Name. Note that this can be used to set an
initial value other than []
prior to backtrackable assignment.
nb_getval(+
Name,-
Value)
nb_getval/2
predicate is a synonym for b_getval/2, introduced for
compatibility and symmetry. As most scenarios will use a particular
global variable either using non-backtrackable or backtrackable
assignment, using nb_getval/2
can be used to document that the
variable is used non-backtrackable.
nb_current(?
Name,?
Value)
nb_delete(?
Name)
Global variables have been introduced by various Prolog
implementations recently. YAP follows their implementation in SWI-Prolog, itself
based on hProlog by Bart Demoen. Jan and Bart
decided that the semantics if hProlog nb_setval/2
, which is
equivalent to nb_linkval/2
is not acceptable for normal Prolog
users as the behaviour is influenced by how builtin predicates
constructing terms (read/1
, =../2
, etc.) are implemented.
GNU-Prolog provides a rich set of global variables, including arrays.
Arrays can be implemented easily in SWI-Prolog using functor/3
and
setarg/3
due to the unrestricted arity of compound terms.
YAP includes several extensions that are not enabled by
default, but that can be used to extend the functionality of the
system. These options can be set at compilation time by enabling the
related compilation flag, as explained in the Makefile
Extensions to Traditional Prolog
Prolog unification is not a complete implementation. For efficiency
considerations, Prolog systems do not perform occur checks while
unifying terms. As an example, X = a(X)
will not fail but instead
will create an infinite term of the form a(a(a(a(a(...)))))
, or
rational tree.
Rational trees are now supported by default in YAP. In previous
versions, this was not the default and these terms could easily lead
to infinite computation. For example, X = a(X), X = X
would
enter an infinite loop.
The RATIONAL_TREES
flag improves support for these
terms. Internal primitives are now aware that these terms can exist, and
will not enter infinite loops. Hence, the previous unification will
succeed. Another example, X = a(X), ground(X)
will succeed
instead of looping. Other affected built-ins include the term comparison
primitives, numbervars/3
, copy_term/2
, and the internal
data base routines. The support does not extend to Input/Output routines
or to assert/1
YAP does not allow directly reading
rational trees, and you need to use write_depth/2
to avoid
entering an infinite cycle when trying to write an infinite term.
Prolog uses a simple left-to-right flow of control. It is sometimes convenient to change this control so that goals will only be executed when conditions are fulfilled. This may result in a more "data-driven" execution, or may be necessary to correctly implement extensions such as negation by default.
The COROUTINING
flag enables this option. Note that the support for
coroutining will in general slow down execution.
The following declaration is supported:
block/1
block/1
is a condition on a goal or a conjunction
of conditions, with each element separated by commas. Each condition is
of the form predname(
C1,...,
CN)
, where N is the
arity of the goal, and each CI is of the form -
, if the
argument must suspend until the first such variable is bound, or
?
, otherwise.
wait/1
wait/1
is a predicate descriptor or a conjunction
of these predicates. These predicates will suspend until their first
argument is bound.
The following primitives are supported:
dif(
X,
Y)
dif/2
will
suspend if unification may still succeed or fail, and will fail if they
always unify.
freeze(?
X,:
G)
frozen(
X,
G)
true
if no goal has suspended.
when(+
C,:
G)
,
C2;
C2?=(
V1,
C2)
nonvar(
V)
ground(
V)
Note that when/2
will fail if the conditions fail.
call_residue(:
G,
L)
dif/2
suspends twice, once outside call_residue/2
,
and the other inside:
?- dif(X,Y), call_residue((dif(X,Y),(X = f(Z) ; Y = f(Z))), L). X = f(Z), L = [[Y]-dif(f(Z),Y)], dif(f(Z),Y) ? ; Y = f(Z), L = [[X]-dif(X,f(Z))], dif(X,f(Z)) ? ; no
The system only reports one invocation of dif/2
as having
suspended.
call_residue_vars(:
G,
L)
?- dif(X,Z), call_residue_vars(dif(X,Y),L). dif(X,Z), call_residue_vars(dif(X,Y),L). L = [Y], dif(X,Z), dif(X,Y) ? ; no
YAP supports attributed variables, originally developed at OFAI by Christian Holzbaur. Attributes are a means of declaring that an arbitrary term is a property for a variable. These properties can be updated during forward execution. Moreover, the unification algorithm is aware of attributed variables and will call user defined handlers when trying to unify these variables.
Attributed variables provide an elegant abstraction over which one can extend Prolog systems. Their main application so far has been in implementing constraint handlers, such as Holzbaur's CLPQR, Fruewirth and Holzbaur's CHR, and CLP(BN).
Different Prolog systems implement attributed variables in different ways. Traditionally, YAP has used the interface designed by SICStus Prolog. This interface is still available in the atts library, but from YAP-6.0.3 we recommend using the hProlog, SWI style interface. The main reason to do so is that most packages included in YAP that use attributed variables, such as CHR, CLP(FD), and CLP(QR), rely on the SWI-Prolog interface.
The following documentation is taken from the SWI-Prolog manual.
Binding an attributed variable schedules a goal to be executed at the
first possible opportunity. In the current implementation the hooks are
executed immediately after a successful unification of the clause-head
or successful completion of a foreign language (built-in) predicate. Each
attribute is associated to a module and the hook attr_unify_hook/2
is
executed in this module. The example below realises a very simple and
incomplete finite domain reasoner.
:- module(domain, [ domain/2 % Var, ?Domain ]). :- use_module(library(ordsets)). domain(X, Dom) :- var(Dom), !, get_attr(X, domain, Dom). domain(X, List) :- list_to_ord_set(List, Domain), put_attr(Y, domain, Domain), X = Y. % An attributed variable with attribute value Domain has been % assigned the value Y attr_unify_hook(Domain, Y) :- ( get_attr(Y, domain, Dom2) -> ord_intersection(Domain, Dom2, NewDomain), ( NewDomain == [] -> fail ; NewDomain = [Value] -> Y = Value ; put_attr(Y, domain, NewDomain) ) ; var(Y) -> put_attr( Y, domain, Domain ) ; ord_memberchk(Y, Domain) ). % Translate attributes from this module to residual goals attribute_goals(X) --> { get_attr(X, domain, List) }, [domain(X, List)].
Before explaining the code we give some example queries:
?- domain(X, [a,b]), X = c
| fail
|
domain(X, [a,b]), domain(X, [a,c]).
| X=a
|
domain(X, [a,b,c]), domain(X, [a,c]).
| domain(X, [a,c]).
|
The predicate domain/2
fetches (first clause) or assigns
(second clause) the variable a domain, a set of values it can
be unified with. In the second clause first associates the domain
with a fresh variable and then unifies X to this variable to deal
with the possibility that X already has a domain. The
predicate attr_unify_hook/2
is a hook called after a variable with
a domain is assigned a value. In the simple case where the variable
is bound to a concrete value we simply check whether this value is in
the domain. Otherwise we take the intersection of the domains and either
fail if the intersection is empty (first example), simply assign the
value if there is only one value in the intersection (second example) or
assign the intersection as the new domain of the variable (third
example). The nonterminal attribute_goals/3
is used to translate
remaining attributes to user-readable goals that, when executed, reinstate
these attributes.
attvar(?
Term)
Term
is an attributed variable. Note that var/1
also
succeeds on attributed variables. Attributed variables are created with
put_attr/3
.
put_attr(+
Var,+
Module,+
Value)
setarg/3
). This predicate raises a representation error if
Var is not a variable and a type error if Module is not an atom.
get_attr(+
Var,+
Module,-
Value)
del_attr(+
Var,+
Module)
attr_unify_hook(+
AttValue,+
VarValue)
put_attr/3
.
attr_portray_hook(+
AttValue,+
Var)
write_term/2
and friends for each attribute if the option
attributes(portray)
is in effect. If the hook succeeds the
attribute is considered printed. Otherwise Module = ...
is
printed to indicate the existence of a variable.
attribute_goals(+
Var,-
Gs,+
GsRest)
Normal user code should deal with put_attr/3
, get_attr/3
and del_attr/2
.
The routines in this section fetch or set the entire attribute list of a
variables. Use of these predicates is anticipated to be restricted to
printing and other special purpose operations.
get_attrs(+
Var,-
Attributes)
att(
Module,
Value,
MoreAttributes)
, where MoreAttributes is
[]
for the last attribute.
put_attrs(+
Var,+
Attributes)
get_attrs/2
for a description of
Attributes.
del_attrs(+
Var)
term_attvars(+
Term,-
AttVars)
term_attvars/2
works recursively through
attributes. This predicate is Cycle-safe.
copy_term(?
TI,-
TF,-
Goals)
maplist(call,
Goals)
can be called to recreate the
attributes.
Before the actual copying, copy_term/3
calls
attribute_goals/1
in the module where the attribute is
defined.
copy_term_nat(?
TI,-
TF)
copy_term/2
. Attributes however, are not copied but replaced
by fresh variables.
term_variables(?
Term, -
Variables)
Old style attribute declarations are activated through loading the library atts . The command
| ?- use_module(library(atts)).
enables this form of use of attributed variables. The package provides the following functionality:
put_atts/2
adds or deletes attributes to a
variable. The variable may be unbound or may be an attributed
variable. In the latter case, YAP discards previous values for the
attributes.
get_atts/2
can be used to check the values of
an attribute associated with a variable.
Attributes are compound terms associated with a variable. Each attribute has a name which is private to the module in which the attribute was defined. Variables may have at most one attribute with a name. Attribute names are defined with the following declaration:
:- attribute AttributeSpec, ..., AttributeSpec.
where each AttributeSpec has the form (Name/Arity). One single such declaration is allowed per module Module.
Although the YAP module system is predicate based, attributes are local
to modules. This is implemented by rewriting all calls to the
built-ins that manipulate attributes so that attribute names are
preprocessed depending on the module. The user:goal_expansion/3
mechanism is used for this purpose.
The attribute manipulation predicates always work as follows:
The following three procedures are available to the user. Notice that these built-ins are rewritten by the system into internal built-ins, and that the rewriting process depends on the module on which the built-ins have been invoked.
:get_atts(
-Var,
?ListOfAttributes)
+(
Attribute)
, -(
Attribute)
(the kbd
prefix may be dropped). The meaning of + and - is:
+(
Attribute)
-(
Attribute)
:put_atts(
-Var,
?ListOfAttributes)
+(
Attribute)
set_mutable/2
).
-(
Attribute)
The user-predicate predicate verify_attributes/3
is called when
attempting to unify an attributed variable which might have attributes
in some Module.
:verify_attributes(
-Var,
+Value,
-Goals)
It is up to the user to define which actions may be performed by verify_attributes/3 but the procedure is expected to return in Goals a list of goals to be called after Var is unified with Value. If verify_attributes/3 fails, the unification will fail.
Notice that the verify_attributes/3 may be called even if Var
has no attributes in module Module. In this case the routine should
simply succeed with Goals unified with the empty list.
attvar(
-Var)
Attributes are usually presented as goals. The following routines are
used by built-in predicates such as call_residue/2
and by the
Prolog top-level to display attributes:
:attribute_goal(
-Var,
-Goal)
:project_attributes(
-QueryVars,
+AttrVars)
Constraint solvers must be able to project a set of constraints to a set
of variables. This is useful when displaying the solution to a goal, but
may also be used to manipulate computations. The user-defined
project_attributes/2
is responsible for implementing this
projection.
:project_attributes(
+QueryVars,
+AttrVars)
Projection interacts with attribute_goal/2
at the Prolog top
level. When the query succeeds, the system first calls
project_attributes/2
. The system then calls
attribute_goal/2
to get a user-level representation of the
constraints. Typically, attribute_goal/2
will convert from the
original constraints into a set of new constraints on the projection,
and these constraints are the ones that will have an
attribute_goal/2
handler.
The following two examples example is taken from the SICStus Prolog manual. It
sketches the implementation of a simple finite domain “solver”. Note
that an industrial strength solver would have to provide a wider range
of functionality and that it quite likely would utilize a more efficient
representation for the domains proper. The module exports a single
predicate domain(
-Var,
?Domain)
which associates
Domain (a list of terms) with Var. A variable can be
queried for its domain by leaving Domain unbound.
We do not present here a definition for project_attributes/2
.
Projecting finite domain constraints happens to be difficult.
:- module(domain, [domain/2]). :- use_module(library(atts)). :- use_module(library(ordsets), [ ord_intersection/3, ord_intersect/2, list_to_ord_set/2 ]). :- attribute dom/1. verify_attributes(Var, Other, Goals) :- get_atts(Var, dom(Da)), !, % are we involved? ( var(Other) -> % must be attributed then ( get_atts(Other, dom(Db)) -> % has a domain? ord_intersection(Da, Db, Dc), Dc = [El|Els], % at least one element ( Els = [] -> % exactly one element Goals = [Other=El] % implied binding ; Goals = [], put_atts(Other, dom(Dc))% rescue intersection ) ; Goals = [], put_atts(Other, dom(Da)) % rescue the domain ) ; Goals = [], ord_intersect([Other], Da) % value in domain? ). verify_attributes(_, _, []). % unification triggered % because of attributes % in other modules attribute_goal(Var, domain(Var,Dom)) :- % interpretation as goal get_atts(Var, dom(Dom)). domain(X, Dom) :- var(Dom), !, get_atts(X, dom(Dom)). domain(X, List) :- list_to_ord_set(List, Set), Set = [El|Els], % at least one element ( Els = [] -> % exactly one element X = El % implied binding ; put_atts(Fresh, dom(Set)), X = Fresh % may call % verify_attributes/3 ).
Note that the “implied binding” Other=El
was deferred until after
the completion of verify_attribute/3
. Otherwise, there might be a
danger of recursively invoking verify_attribute/3
, which might bind
Var
, which is not allowed inside the scope of verify_attribute/3
.
Deferring unifications into the third argument of verify_attribute/3
effectively serializes the calls to verify_attribute/3
.
Assuming that the code resides in the file domain.yap, we can use it via:
| ?- use_module(domain).
Let's test it:
| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]). domain(X,[1,5,6,7]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]) ? yes | ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]), X=Y. Y = X, domain(X,[5,6]), domain(Z,[1,6,7,8]) ? yes | ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]), X=Y, Y=Z. X = 6, Y = 6, Z = 6
To demonstrate the use of the Goals argument of
verify_attributes/3
, we give an implementation of
freeze/2
. We have to name it myfreeze/2
in order to
avoid a name clash with the built-in predicate of the same name.
:- module(myfreeze, [myfreeze/2]). :- use_module(library(atts)). :- attribute frozen/1. verify_attributes(Var, Other, Goals) :- get_atts(Var, frozen(Fa)), !, % are we involved? ( var(Other) -> % must be attributed then ( get_atts(Other, frozen(Fb)) % has a pending goal? -> put_atts(Other, frozen((Fa,Fb))) % rescue conjunction ; put_atts(Other, frozen(Fa)) % rescue the pending goal ), Goals = [] ; Goals = [Fa] ). verify_attributes(_, _, []). attribute_goal(Var, Goal) :- % interpretation as goal get_atts(Var, frozen(Goal)). myfreeze(X, Goal) :- put_atts(Fresh, frozen(Goal)), Fresh = X.
Assuming that this code lives in file myfreeze.yap, we would use it via:
| ?- use_module(myfreeze). | ?- myfreeze(X,print(bound(x,X))), X=2. bound(x,2) % side effect X = 2 % bindings
The two solvers even work together:
| ?- myfreeze(X,print(bound(x,X))), domain(X,[1,2,3]), domain(Y,[2,10]), X=Y. bound(x,2) % side effect X = 2, % bindings Y = 2
The two example solvers interact via bindings to shared attributed
variables only. More complicated interactions are likely to be found
in more sophisticated solvers. The corresponding
verify_attributes/3
predicates would typically refer to the
attributes from other known solvers/modules via the module prefix in
Module:get_atts/2
.
YAP now uses the CLP(R) package developed by Leslie De Koninck, K.U. Leuven as part of a thesis with supervisor Bart Demoen and daily advisor Tom Schrijvers, and distributed with SWI-Prolog.
This CLP(R) system is a port of the CLP(Q,R) system of Sicstus Prolog and YAP by Christian Holzbaur: Holzbaur C.: OFAI clp(q,r) Manual, Edition 1.3.3, Austrian Research Institute for Artificial Intelligence, Vienna, TR-95-09, 1995, http://www.ofai.at/cgi-bin/tr-online/cgi-bin/tr-online?number+95-09 This port only contains the part concerning real arithmetics. This manual is roughly based on the manual of the above mentioned CLP(QR) implementation.
Please note that the clpr library is not an
autoload
library and therefore this library must be loaded
explicitely before using it:
:- use_module(library(clpr)).
The following predicates are provided to work with constraints:
{+
Constraints}
entailed(+
Constraint)
inf(+
Expression,-
Inf)
inf(+
Expression,-
Sup)
min(+
Expression)
max(+
Expression)
bb_inf(+
Ints,+
Expression,-
Inf,-
Vertext,+
Eps)
bb_inf(+
Ints,+
Expression,-
Inf)
dump(+
Target,+
Newvars,-
CodedAnswer)
dump([X,Y,Z],[x,y,z],Cons)
Cons will contain the constraints on X, Y and
Z where these variables have been replaced by atoms x
, y
and z
.
The arguments of the predicates defined in the subsection above are defined in the following table. Failing to meet the syntax rules will result in an exception.
<Constraints> ---> <Constraint> \\ single constraint \\ | <Constraint> , <Constraints> \\ conjunction \\ | <Constraint> ; <Constraints> \\ disjunction \\ <Constraint> ---> <Expression> {<} <Expression> \\ less than \\ | <Expression> {>} <Expression> \\ greater than \\ | <Expression> {=<} <Expression> \\ less or equal \\ | {<=}(<Expression>, <Expression>) \\ less or equal \\ | <Expression> {>=} <Expression> \\ greater or equal \\ | <Expression> {=\=} <Expression> \\ not equal \\ | <Expression> =:= <Expression> \\ equal \\ | <Expression> = <Expression> \\ equal \\ <Expression> ---> <Variable> \\ Prolog variable \\ | <Number> \\ Prolog number (float, integer) \\ | +<Expression> \\ unary plus \\ | -<Expression> \\ unary minus \\ | <Expression> + <Expression> \\ addition \\ | <Expression> - <Expression> \\ substraction \\ | <Expression> * <Expression> \\ multiplication \\ | <Expression> / <Expression> \\ division \\ | abs(<Expression>) \\ absolute value \\ | sin(<Expression>) \\ sine \\ | cos(<Expression>) \\ cosine \\ | tan(<Expression>) \\ tangent \\ | exp(<Expression>) \\ exponent \\ | pow(<Expression>) \\ exponent \\ | <Expression> {^} <Expression> \\ exponent \\ | min(<Expression>, <Expression>) \\ minimum \\ | max(<Expression>, <Expression>) \\ maximum \\
Instead of using the {}/1
predicate, you can also use the standard
unification mechanism to store constraints. The following code samples
are equivalent:
{X =:= Y} {X = Y} X = Y
{X =:= 5.0} {X = 5.0} X = 5.0
In this version, non-linear constraints do not get solved until certain conditions are satisfied. We call these conditions the isolation axioms. They are given in the following table.
A = B * C when B or C is ground or // A = 5 * C or A = B * 4 \\ A and (B or C) are ground // 20 = 5 * C or 20 = B * 4 \\ A = B / C when C is ground or // A = B / 3 A and B are ground // 4 = 12 / C X = min(Y,Z) when Y and Z are ground or // X = min(4,3) X = max(Y,Z) Y and Z are ground // X = max(4,3) X = abs(Y) Y is ground // X = abs(-7) X = pow(Y,Z) when X and Y are ground or // 8 = 2 ^ Z X = exp(Y,Z) X and Z are ground // 8 = Y ^ 3 X = Y ^ Z Y and Z are ground // X = 2 ^ 3 X = sin(Y) when X is ground or // 1 = sin(Y) X = cos(Y) Y is ground // X = sin(1.5707) X = tan(Y)
This chapter is written by Tom Schrijvers, K.U. Leuven for the hProlog system. Adjusted by Jan Wielemaker to fit the SWI-Prolog documentation infrastructure and remove hProlog specific references.
The CHR system of SWI-Prolog is the K.U.Leuven CHR system. The runtime environment is written by Christian Holzbaur and Tom Schrijvers while the compiler is written by Tom Schrijvers. Both are integrated with SWI-Prolog and licenced under compatible conditions with permission from the authors.
The main reference for SWI-Prolog's CHR system is:
Constraint Handling Rules (CHR) is a committed-choice bottom-up language embedded in Prolog. It is designed for writing constraint solvers and is particularily useful for providing application-specific constraints. It has been used in many kinds of applications, like scheduling, model checking, abduction, type checking among many others.
CHR has previously been implemented in other Prolog systems (SICStus, Eclipse, Yap), Haskell and Java. This CHR system is based on the compilation scheme and runtime environment of CHR in SICStus.
In this documentation we restrict ourselves to giving a short overview of CHR in general and mainly focus on elements specific to this implementation. For a more thorough review of CHR we refer the reader to [Freuhwirth:98]. More background on CHR can be found at the CHR web site.
The syntax of CHR rules in hProlog is the following:
rules --> rule, rules. rules --> []. rule --> name, actual_rule, pragma, [atom('.')]. name --> atom, [atom('´)]. name --> []. actual_rule --> simplification_rule. actual_rule --> propagation_rule. actual_rule --> simpagation_rule. simplification_rule --> constraints, [atom('<=>')], guard, body. propagation_rule --> constraints, [atom('==>')], guard, body. simpagation_rule --> constraints, [atom('\')], constraints, [atom('<=>')], guard, body. constraints --> constraint, constraint_id. constraints --> constraint, [atom(',')], constraints. constraint --> compound_term. constraint_id --> []. constraint_id --> [atom('#')], variable. guard --> []. guard --> goal, [atom('|')]. body --> goal. pragma --> []. pragma --> [atom('pragma')], actual_pragmas. actual_pragmas --> actual_pragma. actual_pragmas --> actual_pragma, [atom(',')], actual_pragmas. actual_pragma --> [atom('passive(')], variable, [atom(')')].
Additional syntax-related terminology:
actual_rule
before
the arrow (either <=>
or ==>
)
In this subsection the operational semantics of CHR in Prolog are presented informally. They do not differ essentially from other CHR systems.
When a constraint is called, it is considered an active constraint and the system will try to apply the rules to it. Rules are tried and executed sequentially in the order they are written.
A rule is conceptually tried for an active constraint in the following way. The active constraint is matched with a constraint in the head of the rule. If more constraints appear in the head they are looked for among the suspended constraints, which are called passive constraints in this context. If the necessary passive constraints can be found and all match with the head of the rule and the guard of the rule succeeds, then the rule is committed and the body of the rule executed. If not all the necessary passive constraint can be found, the matching fails or the guard fails, then the body is not executed and the process of trying and executing simply continues with the following rules. If for a rule, there are multiple constraints in the head, the active constraint will try the rule sequentially multiple times, each time trying to match with another constraint.
This process ends either when the active constraint disappears, i.e. it is removed by some rule, or after the last rule has been processed. In the latter case the active constraint becomes suspended.
A suspended constraint is eligible as a passive constraint for an active constraint. The other way it may interact again with the rules, is when a variable appearing in the constraint becomes bound to either a nonvariable or another variable involved in one or more constraints. In that case the constraint is triggered, i.e. it becomes an active constraint and all the rules are tried.
There are three different kinds of rules, each with their specific semantics:
simplification
propagation
simpagation
\
and then calls its body. It is an optimization of
simplification rules of the form: \[constraints_1, constraints_2 <=>
constraints_1, body \] Namely, in the simpagation form:
constraints1 \ constraints2 <=> body
constraints1 constraints are not called in the body.
Naming a rule is optional and has no semantical meaning. It only functions as documentation for the programmer.
The semantics of the pragmas are:
Additional pragmas may be released in the future.
It is possible to specify options that apply to all the CHR rules in the module.
Options are specified with the option/2
declaration:
option(Option,Value).
Available options are:
check_guard_bindings
on
, to enable the checks, and off
, to disable the
checks.
optimize
full
, to enable all available
optimizations, and off
(default), to disable all optimizations.
The default is derived from the SWI-Prolog flag optimise
, where
true
is mapped to full
. Therefore the commandline
option -O provides full CHR optimization.
If optimization is enabled, debugging should be disabled.
debug
on
(default) and off
. See
debugging for more details on debugging. The default is
derived from the prolog flag generate_debug_info
, which
is true
by default. See -nodebug.
If debugging is enabled, optimization should be disabled.
mode
-
, +
or ?
.
The latter is the default. The meaning is the following:
-
+
?
type_declaration
int
float
number
natural
any
Currently, type declarations are only used to improve certain optimizations (guard simplification, occurrence subsumption, ...).
type_definition
type(
name,
list)
, where
name is a term and list is a list of alternatives.
Variables can be used to define generic types. Recursive definitions
are allowed. Examples are
type(bool,[true,false]). type(complex_number,[float + float * i]). type(binary_tree(T),[ leaf(T) | node(binary_tree(T),binary_tree(T)) ]). type(list(T),[ [] | [T | list(T)]).
The mode, type_declaration and type_definition options are provided for backward compatibility. The new syntax is described below.
The CHR constraints defined in a particulary chr file are
associated with a module. The default module is user
. One should
never load different chr files with the same CHR module name.
Every constraint used in CHR rules has to be declared. There are two ways to do this. The old style is as follows:
option(type_definition,type(list(T),[ [] , [T|list(T)] ]). option(mode,foo(+,?)). option(type_declaration,foo(list(int),float)). :- constraints foo/2, bar/0.
The new style is as follows:
:- chr_type list(T) ---> [] ; [T|list(T)]. :- constraints foo(+list(int),?float), bar.
The SWI-Prolog CHR compiler exploits term_expansion/2 rules to translate the constraint handling rules to plain Prolog. These rules are loaded from the library chr. They are activated if the compiled file has the chr extension or after finding a declaration of the format below.
:- constraints ...
It is adviced to define CHR rules in a module file, where the module declaration is immediately followed by including the chr library as examplified below:
:- module(zebra, [ zebra/0 ]). :- use_module(library(chr)). :- constraints ...
Using this style CHR rules can be defined in ordinary Prolog pl files and the operator definitions required by CHR do not leak into modules where they might cause conflicts.
The CHR debugging facilities are currently rather limited. Only tracing
is currently available. To use the CHR debugging facilities for a CHR
file it must be compiled for debugging. Generating debug info is
controlled by the CHR option debug
, whose default is derived
from the SWI-Prolog flag generate_debug_info
. Therefore debug
info is provided unless the -nodebug is used.
For CHR constraints the four standard ports are defined:
call
exit
fail
redo
In addition to the above ports, CHR constraints have five additional ports:
wake
insert
remove
try
apply
Tracing is enabled with the chr_trace/0 predicate and disabled with the chr_notrace/0 predicate.
When enabled the tracer will step through the call
,
exit
, fail
, wake
and apply
ports,
accepting debug commands, and simply write out the other ports.
The following debug commans are currently supported:
CHR debug options: <cr> creep c creep s skip g ancestors n nodebug b break a abort f fail ? help h help
Their meaning is:
creep
skip
ancestors
nodebug
break
abort
fail
help
The chr module contains several predicates that allow inspecting and printing the content of the constraint store.
chr_trace/0
chr_notrace/0
chr_leash/0
full
to stop at all ports, none
or off
to never
stop, and default
to stop at the call
, exit
,
fail
, wake
and apply
ports. See also leash/1.
chr_show_store(+
Mod)
chr_toplevel_show_store
controls whether the toplevel shows the
constraint stores. The value true
enables it. Any other value
disables it.
Here are two example constraint solvers written in CHR.
leq/2
, which is a less-than-or-equal constraint.
:- module(leq,[cycle/3, leq/2]). :- use_module(library(chr)). :- constraints leq/2. reflexivity leq(X,X) <=> true. antisymmetry leq(X,Y), leq(Y,X) <=> X = Y. idempotence leq(X,Y) \ leq(X,Y) <=> true. transitivity leq(X,Y), leq(Y,Z) ==> leq(X,Z). cycle(X,Y,Z):- leq(X,Y), leq(Y,Z), leq(Z,X).
:- module(dom,[dom/2]). :- use_module(library(chr)). :- constraints dom/2. dom(X,[]) <=> fail. dom(X,[Y]) <=> X = Y. dom(X,L1), dom(X,L2) <=> intersection(L1,L2,L3), dom(X,L3). intersection([],_,[]). intersection([H|T],L2,[H|L3]) :- member(H,L2), !, intersection(T,L2,L3). intersection([_|T],L2,L3) :- intersection(T,L2,L3).
There are small differences between CHR in SWI-Prolog and newer YAPs and SICStus and older versions of YAP. Besides differences in available options and pragmas, the following differences should be noted:
[The handler/1 declaration]
handler/1
declaration declaring a unique handler name. This declaration is valid
syntax in SWI-Prolog, but will have no effect. A warning will be given
during compilation.
[The rules/1 declaration]
rules/1
declaration. The
declaration is valid syntax in SWI-Prolog, but has no effect. A
warning is given during compilation.
[Sourcefile naming]
In this section we cover several guidelines on how to use CHR to write constraint solvers and how to do so efficiently.
[Set semantics]
{constraint \ constraint <=> true}.
[Multi-headed rules]
[Mode and type declarations]
The Logtalk object-oriented extension is available after running its
standalone installer by using the yaplgt
command in POSIX
systems or by using the Logtalk - YAP
shortcut in the Logtalk
program group in the Start Menu on Windows systems. For more information
please see the URL http://logtalk.org/.
The MYDDAS database project was developed within a FCT project aiming at the development of a highly efficient deductive database system, based on the coupling of the MySQL relational database system with the Yap Prolog system. MYDDAS was later expanded to support the ODBC interface.
Subnodes of MYDDAS
Next, we describe how to usen of the YAP with the MYDDAS System. The use of this system is entirely depend of the MySQL development libraries or the ODBC development libraries. At least one of the this development libraries must be installed on the computer system, otherwise MYDDAS will not compile. The MySQL development libraries from MySQL 3.23 an above are know to work. We recommend the usage of MySQL versusODBC, but it is possible to have both options installed
At the same time, without any problem. The MYDDAS system automatically controls the two options. Currently, MYDDAS is know to compile without problems in Linux. The usage of this system on Windows has not been tested yet. MYDDAS must be enabled at configure time. This can be done with the following options:
--enable-myddas
--enable-myddas-stats
--enable-top-level
The system includes four main blocks that are put together through the MYDDAS interface: the Yap Prolog compiler, the MySQL database system, an ODBC layer and a Prolog to SQL compiler. Current effort is put on the MySQL interface rather than on the ODBC interface. If you want to use the full power of the MYDDAS interface we recommend you to use a MySQL database. Other databases, such as Oracle, PostGres or Microsoft SQL Server, can be interfaced through the ODBC layer, but with limited performance and features support.
The main structure of the MYDDAS interface is simple. Prolog queries involving database goals are translated to SQL using the Prolog to SQL compiler; then the SQL expression is sent to the database system, which returns the set of tuples satisfying the query; and finally those tuples are made available to the Prolog engine as terms. For recursive queries involving database goals, the YapTab tabling engine provides the necessary support for an efficient evaluation of such queries.
An important aspect of the MYDDAS interface is that for the programmer the use of predicates which are defined in database relations is completely transparent. An example of this transparent support is the Prolog cut operator, which has exactly the same behaviour from predicates defined in the Prolog program source code, or from predicates defined in database as relations.
Begin by starting YAP and loading the library
use_module(library(myddas))
. This library already includes the
Prolog to SQL Compiler described in [2] and [1]. In MYDDAS this compiler
has been extended to support further constructs which allow a more
efficient SQL translation.
db open(+,+,+,+,+).
db open(+,+,+,+).
db close(+).
db_close.
Assuming the MySQL server is running and we have an account, we can
login to MySQL by invoking db_open/5
as one of the following:
?- db_open(mysql,Connection,Host/Database,User,Password). ?- db_open(mysql,Connection,Host/Database/Port,User,Password). ?- db_open(mysql,Connection,Host/Database/UnixSocket,User,Password). ?- db_open(mysql,Connection,Host/Database/Port/UnixSocket,User,Password).
If the login is successful, there will be a response of yes
. For
instance:
?- db_open(mysql,con1,localhost/guest_db,guest,'').
uses the MySQL native interface, selected by the first argument, to open
a connection identified by the con1
atom, to an instance of a
MySQL server running on host localhost
, using database guest db
and user guest
with empty password
. To disconnect from the con1
connection we use:
?- db_close(con1).
Alternatively, we can use db_open/4
and db_close/0,
without an argument
to identify the connection. In this case the default connection is used,
with atom myddas
. Thus using
?- db_open(mysql,localhost/guest_db,guest,''). ?- db_close.
or
?- db_open(mysql,myddas,localhost/guest_db,guest,''). ?- db_close(myddas).
is exactly the same.
MYDDAS also supports ODBC. To connect to a database using an ODBC driver
you must have configured on your system a ODBC DSN. If so, the db_open/4
and db_open/5
have the following mode:
?- db_open(odbc,Connection,ODBC_DSN,User,Password). ?- db_open(odbc,ODBC_DSN,User,Password).
For instance, if you do db_open(odbc,odbc_dsn,guest,'')
. it will connect
to a database, through ODBC, using the definitions on the odbc_dsn
DSN
configured on the system. The user will be the user guest
with no
password.
db_import(+Conn,+RelationName,+PredName).
db_import(+RelationName,+PredName).
Assuming you have access permission for the relation you wish to import,
you can use db_import/3
or db_import/2
as:
?- db_import(Conn,RelationName,PredName). ?- db_import(RelationName,PredName).
where RelationName, is the name of
relation we wish to access, PredName is the name of the predicate we
wish to use to access the relation from YAP. Conn, is the connection
identifier, which again can be dropped so that the default myddas connection
is used. For instance, if we want to access the relation phonebook,
using the predicate phonebook/3
we write:
?- db_import(con1,phonebook,phonebook). yes ?- phonebook(Letter,Name,Number). Letter = 'D', Name = 'John Doe', Number = 123456789 ? yes
Backtracking can then be used to retrieve the next row of the relation phonebook. Records with particular field values may be selected in the same way as in Prolog. (In particular, no mode specification for database predicates is required). For instance:
?- phonebook(Letter,'John Doe',Letter). Letter = 'D', Number = 123456789 ? yes
generates the query
SELECT A.Letter , 'John Doe' , A.Number FROM 'phonebook' A WHERE A.Name = 'John Doe';
db view(+,+,+).
db view(+,+).
?- db_import('Edge',edge). yes
and we then write a query to retrieve all the direct cycles in the graph, such as
?- edge(A,B), edge(B,A). A = 10, B = 20 ?
this is clearly inefficient [3], because of relation-level
access. Relation-level access means that a separate SQL query will be
generated for every goal in the body of the clause. For the second
edge/2
goal, a SQL query is generated using the variable bindings that
result from the first edge/2
goal execution. If the second
edge/2
goal
fails, or if alternative solutions are demanded, backtracking access the
next tuple for the first edge/2
goal and another SQL query will be
generated for the second edge/2
goal. The generation of this large
number of queries and the communication overhead with the database
system for each of them, makes the relation-level approach inefficient.
To solve this problem the view level interface can be used for the
definition of rules whose bodies includes only imported database
predicates. One can use the view level interface through the predicates
db_view/3
and db_view/2
:
?- db_view(Conn,PredName(Arg_1,...,Arg_n),DbGoal). ?- db_view(PredName(Arg_1,...,Arg_n),DbGoal).
All arguments are standard Prolog terms. Arg1 through Argn
define the attributes to be retrieved from the database, while
DbGoal defines the selection restrictions and join
conditions. Conn is the connection identifier, which again can be
dropped. Calling predicate PredName/n
will retrieve database
tuples using a single SQL query generated for the DbGoal. We next show
an example of a view definition for the direct cycles discussed
above. Assuming the declaration:
?- db_import('Edge',edge). yes
we write:
?- db_view(direct_cycle(A,B),(edge(A,B), edge(B,A))). yes ?- direct_cycle(A,B)). A = 10, B = 20 ?
This call generates the SQL statement:
SELECT A.attr1 , A.attr2 FROM Edge A , Edge B WHERE B.attr1 = A.attr2 AND B.attr2 = A.attr1;
Backtracking, as in relational level interface, can be used to retrieve the next row of the view.
The view interface also supports aggregate function predicates such as
sum
, avg
, count
, min
and max
. For
instance:
?- db_view(count(X),(X is count(B, B^edge(10,B)))).
generates the query :
SELECT COUNT(A.attr2) FROM Edge A WHERE A.attr1 = 10;
To know how to use db view/3
, please refer to Draxler's Prolog to
SQL Compiler Manual.
db_sql(+,+,?).
db_sql(+,?).
It is also possible to explicitly send a SQL query to the database server using
?- db_sql(Conn,SQL,List). ?- db_sql(SQL,List).
where SQL is an arbitrary SQL expression, and List is a list holding the first tuple of result set returned by the server. The result set can also be navigated through backtracking.
Example:
?- db_sql('SELECT * FROM phonebook',LA). LA = ['D','John Doe',123456789] ?
db_assert(+,+).
db_assert(+).
Assuming you have imported the related base table using
db_import/2
or db_import/3
, you can insert to that table
by using db_assert/2
predicate any given fact.
?- db_assert(Conn,Fact). ?- db_assert(Fact).
The second argument must be declared with all of its arguments bound to
constants. For example assuming helloWorld
is imported through
db_import/2
:
?- db_import('Hello World',helloWorld). yes ?- db_assert(helloWorld('A' ,'Ana',31)). yes
This, would generate the following query
INSERT INTO helloWorld VALUES ('A','Ana',3)
which would insert into the helloWorld, the following row:
A,Ana,31
. If we want to insert NULL
values into the
relation, we call db_assert/2
with a uninstantiated variable in
the data base imported predicate. For example, the following query on
the YAP-prolog system:
?- db_assert(helloWorld('A',NULL,31)). yes
Would insert the row: A,null value,31
into the relation
Hello World
, assuming that the second row allows null values.
db insert(+,+,+).
db insert(+,+).
This predicate would create a new database predicate, which will insert any given tuple into the database.
?- db_insert(Conn,RelationName,PredName). ?- db_insert(RelationName,PredName).
This would create a new predicate with name PredName, that will
insert tuples into the relation RelationName. is the connection
identifier. For example, if we wanted to insert the new tuple
('A',null,31)
into the relation Hello World
, we do:
?- db_insert('Hello World',helloWorldInsert). yes ?- helloWorldInsert('A',NULL,31). yes
db_get_attributes_types(+,+,?).
db_get_attributes_types(+,?).
The prototype for this predicate is the following:
?- db_get_attributes_types(Conn,RelationName,ListOfFields). ?- db_get_attributes_types(RelationName,ListOfFields).
You can use the
predicate db_get_attributes types/2
or db_get_attributes_types/3
, to
know what are the names and attributes types of the fields of a given
relation. For example:
?- db_get_attributes_types(myddas,'Hello World',LA). LA = ['Number',integer,'Name',string,'Letter',string] ? yes
where Hello World is the name of the relation and myddas is the connection identifier.
db_number_of_fields(+,?).
db_number_of_fields(+,+,?).
The prototype for this predicate is the following:
?- db_number_of_fields(Conn,RelationName,Arity). ?- db_number_of_fields(RelationName,Arity).
You can use the predicate db_number_of_fields/2
or
db_number_of_fields/3
to know what is the arity of a given
relation. Example:
?- db_number_of_fields(myddas,'Hello World',Arity). Arity = 3 ? yes
where Hello World
is the name of the
relation and myddas
is the connection identifier.
db_datalog_describe(+,+).
db_datalog_describe(+).
The db datalog_describe/2
predicate does not really returns any
value. It simply prints to the screen the result of the MySQL describe
command, the same way as DESCRIBE
in the MySQL prompt would.
?- db_datalog_describe(myddas,'Hello World'). +----------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+----------+------+-----+---------+-------+ + Number | int(11) | YES | | NULL | | + Name | char(10) | YES | | NULL | | + Letter | char(1) | YES | | NULL | | +----------+----------+------+-----+---------+-------+ yes
db_describe(+,+).
db_describe(+).
The db_describe/3
predicate does the same action as
db_datalog_describe/2
predicate but with one major
difference. The results are returned by backtracking. For example, the
last query:
?- db_describe(myddas,'Hello World',Term). Term = tableInfo('Number',int(11),'YES','',null(0),'') ? ; Term = tableInfo('Name',char(10),'YES','',null(1),'' ? ; Term = tableInfo('Letter',char(1),'YES','',null(2),'') ? ; no
db_datalog_show_tables(+).
db_datalog_show_tables
If we need to know what relations exists in a given MySQL Schema, we can use
the db_datalog_show_tables/1
predicate. As db_datalog_describe/2,
it does not returns any value, but instead prints to the screen the result of the
SHOW TABLES
command, the same way as it would be in the MySQL prompt.
?- db_datalog_show_tables(myddas). +-----------------+ | Tables_in_guest | +-----------------+ | Hello World | +-----------------+ yes
db_show_tables(+, ?).
db_show_tables(?)
The db_show_tables/2
predicate does the same action as
db_show_tables/1
predicate but with one major difference. The
results are returned by backtracking. For example, given the last query:
?- db_show_tables(myddas,Table). Table = table('Hello World') ? ; no
db_top_level(+,+,+,+,+).
db_top_level(+,+,+,+).
Through MYDDAS is also possible to access the MySQL Database Server, in the same wthe mysql client. In this mode, is possible to query the SQL server by just using the standard SQL language. This mode is exactly the same as different from the standard mysql client. We can use this mode, by invoking the db top level/5. as one of the following:
?- db_top_level(mysql,Connection,Host/Database,User,Password). ?- db_top_level(mysql,Connection,Host/Database/Port,User,Password). ?- db_top_level(mysql,Connection,Host/Database/UnixSocket,User,Password). ?- db_top_level(mysql,Connection,Host/Database/Port/UnixSocket,User,Password).
Usage is similar as the one described for the db_open/5
predicate
discussed above. If the login is successful, automatically the prompt of
the mysql client will be used. For example:
?- db_top_level(mysql,con1,localhost/guest_db,guest,'').
opens a
connection identified by the con1
atom, to an instance of a MySQL server
running on host localhost
, using database guest db
and user guest
with
empty password. After this is possible to use MYDDAS as the mysql
client.
?- db_top_level(mysql,con1,localhost/guest_db,guest,''). Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 4468 to server version: 4.0.20 Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> exit Bye yes ?-
db_verbose(+).
db_top_level(+,+,+,+).
When we ask a question to YAP, using a predicate asserted by
db_import/3
, or by db_view/3
, this will generate a SQL
QUERY
. If we want to see that query, we must to this at a given
point in our session on YAP.
?- db_verbose(1). yes ?-
If we want to
disable this feature, we must call the db_verbose/1
predicate with the value 0.
db_module(?).
When we create a new database predicate, by using db_import/3
,
db_view/3
or db_insert/3
, that predicate will be asserted
by default on the user
module. If we want to change this value, we can
use the db_module/1
predicate to do so.
?- db_module(lists). yes ?-
By executing this predicate, all of the predicates asserted by the predicates enumerated earlier will created in the lists module. If we want to put back the value on default, we can manually put the value user. Example:
?- db_module(user). yes ?-
We can also see in what module the predicates are being asserted by doing:
?- db_module(X). X=user yes ?-
db_my_result_set(?).
The MySQL C API permits two modes for transferring the data generated by a query to the client, in our case YAP. The first mode, and the default mode used by the MYDDAS-MySQL, is to store the result. This mode copies all the information generated to the client side.
?- db_my_result_set(X). X=store_result yes
The other mode that we can use is use result. This one uses the result set created directly from the server. If we want to use this mode, he simply do
?- db_my_result_set(use_result). yes
After this command, all
of the database predicates will use use result by default. We can change
this by doing again db_my_result_set(store_result)
.
db_my_sql_mode(+Conn,?SQL_Mode).
db_my_sql_mode(?SQL_Mode).
The MySQL server allows the user to change the SQL mode. This can be very useful for debugging proposes. For example, if we want MySQL server not to ignore the INSERT statement warnings and instead of taking action, report an error, we could use the following SQL mode.
?-db_my_sql_mode(traditional). yes
You can see the available SQL Modes at the MySQL homepage at http://www.mysql.org.
YAP implements a SWI-Prolog compatible multithreading library. Like in SWI-Prolog, Prolog threads have their own stacks and only share the Prolog heap: predicates, records, flags and other global non-backtrackable data. The package is based on the POSIX thread standard (Butenhof:1997:PPT) used on most popular systems except for MS-Windows.
Subnodes of Threads
Subnodes of Thread Communication
thread_create(:
Goal, -
Id, +
Options)
stack
-S
option.
trail
-T
.
alias
thread_join/2
).
at_exit
detached
false
(default), the thread can be waited for using
thread_join/2
. thread_join/2
must be called on this thread
to reclaim the all resources associated to the thread. If true
,
the system will reclaim all associated resources automatically after the
thread finishes. Please note that thread identifiers are freed for reuse
after a detached thread finishes or a normal thread has been joined.
See also thread_join/2
and thread_detach/1
.
The Goal argument is copied to the new Prolog engine.
This implies further instantiation of this term in either thread does
not have consequences for the other thread: Prolog threads do not share
data from their stacks.
thread_create(:
Goal, -
Id)
thread_create/3
.
thread_create(:
Goal)
thread_create/3
.
thread_self(-
Id)
thread_join(+
Id, -
Status)
detached
true
cannot be joined. See also current_thread/2
.
A thread that has been completed without thread_join/2
being
called on it is partly reclaimed: the Prolog stacks are released and the
C-thread is destroyed. A small data-structure representing the
exit-status of the thread is retained until thread_join/2
is called on
the thread. Defined values for Status are:
true
false
exception(
Term)
print_message/2
to turn system exceptions into
readable messages.
exited(
Term)
thread_exit/1
using the argument Term.
thread_detach(+
Id)
detached
option at
thread_create/3
at runtime. Id is the identifier of the thread
placed in detached state.
One of the possible applications is to simplify debugging. Threads that
are created as detached
leave no traces if they crash. For
not-detached threads the status can be inspected using
current_thread/2
. Threads nobody is waiting for may be created
normally and detach themselves just before completion. This way they
leave no traces on normal completion and their reason for failure can be
inspected.
thread_yield
thread_exit(+
Term)
exited(
Term)
as
result-state for thread_join/2
. If the thread has the attribute
detached
true
it terminates, but its exit status cannot be
retrieved using thread_join/2
making the value of Term
irrelevant. The Prolog stacks and C-thread are reclaimed.
thread_at_exit(:
Term)
at_halt/1
, but only for the current
thread. These hooks are ran regardless of why the execution of the
thread has been completed. As these hooks are run, the return-code is
already available through thread_property/2
using the result of
thread_self/1
as thread-identifier. If you want to guarantee the
execution of an exit hook no matter how the thread terminates (the thread
can be aborted before reaching the thread_at_exit/1
call), consider
using instead the at_exit/1
option of thread_create/3
.
thread_setconcurrency(+
Old, -
New)
pthread_setconcurrency()
. Solaris is a typical example of this
family. On other systems this predicate unifies Old to 0 (zero)
and succeeds silently.
thread_sleep(+
Time)
Normal multi-threaded applications should not need these the predicates
from this section because almost any usage of these predicates is
unsafe. For example checking the existence of a thread before signalling
it is of no use as it may vanish between the two calls. Catching
exceptions using catch/3
is the only safe way to deal with
thread-existence errors.
These predicates are provided for diagnosis and monitoring tasks.
thread_property(?
Id, ?
Property)
thread_property/2
does not influence any thread. See also
thread_join/2
. For threads that have an alias-name, this name can
be used in Id instead of the numerical thread identifier.
Property is one of:
status(
Status)
alias(
Alias)
at_exit(
AtExit)
detached(
Boolean)
stack(
Size)
trail(
Size)
system(
Size)
current_thread(+
Id, -
Status)
current_thread/2
does not influence any thread. See also
thread_join/2
. For threads that have an alias-name, this name is
returned in Id instead of the numerical thread identifier.
Status is one of:
running
false
true
exited(
Term)
thread_exit/1
with Term as argument. If the underlying native thread has
exited (using pthread_exit()) Term is unbound.
exception(
Term)
throw/1
and catch/3
).
thread_statistics(+
Id, +
Key, -
Value)
statistics/2
does in single-threaded applications. This call returns all keys
of statistics/2
, although only information statistics about the
stacks and CPU time yield different values for each thread.
mutex_statistics
threads
Subnodes of Thread Communication
Prolog threads can exchange data using dynamic predicates, database records, and other globally shared data. These provide no suitable means to wait for data or a condition as they can only be checked in an expensive polling loop. Message queues provide a means for threads to wait for data or conditions without using the CPU.
Each thread has a message-queue attached to it that is identified
by the thread. Additional queues are created using
message_queue_create/2
.
thread_send_message(+
Term)
thread_send_message(+
QueueOrThreadId, +
Term)
thread_self/1
). Any term can be placed in a message queue, but note that
the term is copied to the receiving thread and variable-bindings are
thus lost. This call returns immediately.
If more than one thread is waiting for messages on the given queue and
at least one of these is waiting with a partially instantiated
Term, the waiting threads are all sent a wakeup signal,
starting a rush for the available messages in the queue. This behaviour
can seriously harm performance with many threads waiting on the same
queue as all-but-the-winner perform a useless scan of the queue. If
there is only one waiting thread or all waiting threads wait with an
unbound variable an arbitrary thread is restarted to scan the queue.
thread_get_message(?
Term)
Please note that not-unifying messages remain in the queue. After
the following has been executed, thread 1 has the term gnu
in its queue and continues execution using A is gnat
.
<thread 1> thread_get_message(a(A)), <thread 2> thread_send_message(b(gnu)), thread_send_message(a(gnat)),
See also thread_peek_message/1
.
message_queue_create(?
Queue)
thread_send_message/2
, the name of a queue may not be in use
as a thread-name. If Queue is unbound an anonymous queue is
created and Queue is unified to its identifier.
message_queue_destroy(+
Queue)
message_queue_create/1
. It is
not allows to destroy the queue of a thread. Neither is it
allowed to destroy a queue other threads are waiting for or, for
anonymous message queues, may try to wait for later.
thread_get_message(+
Queue, ?
Term)
thread_get_message/1
, operating on a given queue. It is allowed to
peek into another thread's message queue, an operation that can be used
to check whether a thread has swallowed a message sent to it.
thread_peek_message(?
Term)
thread_peek_message(+
Queue, ?
Term)
thread_peek_message/1
, operating on a given queue. It is allowed to
peek into another thread's message queue, an operation that can be used
to check whether a thread has swallowed a message sent to it.
Explicit message queues are designed with the worker-pool model in mind, where multiple threads wait on a single queue and pick up the first goal to execute. Below is a simple implementation where the workers execute arbitrary Prolog goals. Note that this example provides no means to tell when all work is done. This must be realised using additional synchronisation.
% create_workers(+Id, +N) % % Create a pool with given Id and number of workers. create_workers(Id, N) :- message_queue_create(Id), forall(between(1, N, _), thread_create(do_work(Id), _, [])). do_work(Id) :- repeat, thread_get_message(Id, Goal), ( catch(Goal, E, print_message(error, E)) -> true ; print_message(error, goal_failed(Goal, worker(Id))) ), fail. % work(+Id, +Goal) % % Post work to be done by the pool work(Id, Goal) :- thread_send_message(Id, Goal).
These predicates provide a mechanism to make another thread execute some
goal as an interrupt. Signalling threads is safe as these
interrupts are only checked at safe points in the virtual machine.
Nevertheless, signalling in multi-threaded environments should be
handled with care as the receiving thread may hold a mutex
(see with_mutex/2
). Signalling probably only makes sense to start
debugging threads and to cancel no-longer-needed threads with throw/1
,
where the receiving thread should be designed carefully do handle
exceptions at any point.
thread_signal(+
ThreadId, :
Goal)
thread_signal/2
itself places Goal into the signalled-thread's signal queue
and returns immediately.
Signals (interrupts) do not cooperate well with the world of multi-threading, mainly because the status of mutexes cannot be guaranteed easily. At the call-port, the Prolog virtual machine holds no locks and therefore the asynchronous execution is safe.
Goal can be any valid Prolog goal, including throw/1
to make
the receiving thread generate an exception and trace/0
to start
tracing the receiving thread.
Besides queues threads can share and exchange data using dynamic
predicates. The multi-threaded version knows about two types of
dynamic predicates. By default, a predicate declared dynamic
(see dynamic/1
) is shared by all threads. Each thread may
assert, retract and run the dynamic predicate. Synchronisation inside
Prolog guarantees the consistency of the predicate. Updates are
logical: visible clauses are not affected by assert/retract
after a query started on the predicate. In many cases primitive from
thread synchronisation should be used to ensure application invariants on
the predicate are maintained.
Besides shared predicates, dynamic predicates can be declared with the
thread_local/1
directive. Such predicates share their
attributes, but the clause-list is different in each thread.
thread_local(
+Functor/Arity)
assert/1
, retract/1
,
etc, during execution of the program. Unlike normal shared dynamic
data however each thread has its own clause-list for the predicate.
As a thread starts, this clause list is empty. If there are still
clauses as the thread terminates these are automatically reclaimed by
the system. The thread_local
property implies
the property dynamic
.
Thread-local dynamic predicates are intended for maintaining thread-specific state or intermediate results of a computation.
It is not recommended to put clauses for a thread-local predicate into a file as in the example below as the clause is only visible from the thread that loaded the source-file. All other threads start with an empty clause-list.
:- thread_local foo/1. foo(gnat).
All internal Prolog operations are thread-safe. This implies two Prolog threads can operate on the same dynamic predicate without corrupting the consistency of the predicate. This section deals with user-level mutexes (called monitors in ADA or critical-sections by Microsoft). A mutex is a MUTual EXclusive device, which implies at most one thread can hold a mutex.
Mutexes are used to realise related updates to the Prolog database.
With `related', we refer to the situation where a `transaction' implies
two or more changes to the Prolog database. For example, we have a
predicate address/2
, representing the address of a person and we want
to change the address by retracting the old and asserting the new
address. Between these two operations the database is invalid: this
person has either no address or two addresses, depending on the
assert/retract order.
Here is how to realise a correct update:
:- initialization mutex_create(addressbook). change_address(Id, Address) :- mutex_lock(addressbook), retractall(address(Id, _)), asserta(address(Id, Address)), mutex_unlock(addressbook).
mutex_create(?
MutexId)
mutex_destroy(+
MutexId)
existence_error
exception.
with_mutex(+
MutexId, :
Goal)
once/1
). The mutex is unlocked
regardless of whether Goal succeeds, fails or raises an exception.
An exception thrown by Goal is re-thrown after the mutex has been
successfully unlocked. See also mutex_create/2
.
Although described in the thread-section, this predicate is also
available in the single-threaded version, where it behaves simply as
once/1
.
mutex_lock(+
MutexId)
If MutexId is an atom, and there is no current mutex with that
name, the mutex is created automatically using mutex_create/1
. This
implies named mutexes need not be declared explicitly.
Please note that locking and unlocking mutexes should be paired
carefully. Especially make sure to unlock mutexes even if the protected
code fails or raises an exception. For most common cases use
with_mutex/2
, which provides a safer way for handling Prolog-level
mutexes.
mutex_trylock(+
MutexId)
mutex_unlock(+
MutexId)
permission_error
exception is raised.
mutex_unlock_all
abort/0
or exceptions. See
also thread_signal/2
.
current_mutex(?
MutexId, ?
ThreadId, ?
Count)
[]
and Count is 0.
There has been a sizeable amount of work on an or-parallel
implementation for YAP, called YAPOr. Most of this work has
been performed by Ricardo Rocha. In this system parallelism is exploited
implicitly by running several alternatives in or-parallel. This option
can be enabled from the configure
script or by checking the
system's Makefile
.
YAPOr is still a very experimental system, going through rapid development. The following restrictions are of note:
We expect that some of these restrictions will be removed in future releases.
YAPTab is the tabling engine that extends YAP's execution model to support tabled evaluation for definite programs. YAPTab was implemented by Ricardo Rocha and its implementation is largely based on the ground-breaking design of the XSB Prolog system, which implements the SLG-WAM. Tables are implemented using tries and YAPTab supports the dynamic intermixing of batched scheduling and local scheduling at the subgoal level. Currently, the following restrictions are of note:
To experiment with YAPTab use --enable-tabling
in the configure
script or add -DTABLING
to YAP_EXTRAS
in the system's
Makefile
. We next describe the set of built-ins predicates
designed to interact with YAPTab and control tabled execution:
table +
P:- table son/3. :- table father/2. :- table mother/2.
or
:- table son/3, father/2, mother/2.
or
:- table [son/3, father/2, mother/2].
is_tabled(+
P)
tabling_mode(+
P,?
Mode)
batched
local
exec_answers
load_answers
batched
and exec_answers
. To set the tabling mode for all predicates at
once you can use the yap_flag/2
predicate as described next.
yap_flag(tabling_mode,?
Mode)
default
batched
local
exec_answers
load_answers
abolish_table(+
P)
abolish_all_tables/0
show_table(+
P)
table_statistics(+
P)
tabling_statistics/0
It is possible to follow the flow at abstract machine level if
YAP is compiled with the flag LOW_LEVEL_TRACER
. Note
that this option is of most interest to implementers, as it quickly generates
an huge amount of information.
Low level tracing can be toggled from an interrupt handler by using the
option T
. There are also two built-ins that activate and
deactivate low level tracing:
start_low_level_trace
stop_low_level_trace
Note that this compile-time option will slow down execution.
Implementors may be interested in detecting on which abstract machine
instructions are executed by a program. The ANALYST
flag can give
WAM level information. Note that this option slows down execution very
substantially, and is only of interest to developers of the system
internals, or to system debuggers.
reset_op_counters
show_op_counters(+
A)
show_ops_by_group(+
A)
The following predicates are available to control the debugging of programs:
debug
debugging
nodebug
spy +
Pnospy +
Pspy P
.
nospyall
notrace
leash(+
M)
full
tight
half
loose
off
none
off
full
.
The user may also specify directly the debugger ports where he wants to be prompted. If the argument for leash is a number N, each of lower four bits of the number is used to control prompting at one the ports of the box model. The debugger will prompt according to the following conditions:
N/\ 1 =\= 0
prompt on fail
N/\ 2 =\= 0
prompt on redo
N/\ 4 =\= 0
prompt on exit
N/\ 8 =\= 0
prompt on call
leash(15)
is equivalent to leash(full)
and
leash(0)
is equivalent to leash(off)
.
Another way of using leash
is to give it a list with the names of
the ports where the debugger should stop. For example,
leash([call,exit,redo,fail])
is the same as leash(full)
or
leash(15)
and leash([fail])
might be used instead of
leash(1)
.
spy_write(+
Stream,Term)
write/2
.
trace
notrace
nodebug/0
.
Debugging with YAP is similar to debugging with C-Prolog. Both systems include a procedural debugger, based on Byrd's four port model. In this model, execution is seen at the procedure level: each activation of a procedure is seen as a box with control flowing into and out of that box.
In the four port model control is caught at four key points: before entering the procedure, after exiting the procedure (meaning successful evaluation of all queries activated by the procedure), after backtracking but before trying new alternative to the procedure and after failing the procedure. Each one of these points is named a port:
*--------------------------------------* Call | | Exit ---------> + descendant(X,Y) :- offspring(X,Y). + ---------> | | | descendant(X,Z) :- | <--------- + offspring(X,Y), descendant(Y,Z). + <--------- Fail | | Redo *--------------------------------------*
Call
Exit
Redo
Fail
To start debugging, the user will either call trace
or spy the
relevant procedures, entering debug mode, and start execution of the
program. When finding the first spy-point, YAP's debugger will take
control and show a message of the form:
* (1) call: quicksort([1,2,3],_38) ?
The debugger message will be shown while creeping, or at spy-points, and it includes four or five fields:
*
, execution is at a
spy-point. If the third character is a >
, execution has returned
either from a skip, a fail or a redo command.
write_term/3
on the standard error stream, using the options
given by debugger_print_options
.
If the active port is leashed, the debugger will prompt the user with a
?
, and wait for a command. A debugger command is just a
character, followed by a return. By default, only the call and redo
entries are leashed, but the leash/1
predicate can be used in
order to make the debugger stop where needed.
There are several commands available, but the user only needs to
remember the help command, which is h
. This command shows all the
available options, which are:
c - creep
return - creep
l - leap
k - quasi-leap
z - zip
s - skip
t - fast-skip
f [
GoalId] - fail
r [
GoalId] - retry
a - abort
n - nodebug
e - exit
h - help
! Query
b - break
!
break
.
+ - spy this goal
! spy G
where G
is the active goal.
- - nospy this goal
! nospy G
where G is
the active goal.
p - print
d - display
<Depth - debugger write depth
write_depth/2
(see I/O Control).
< - full term
write_depth/2
(see I/O Control).
A - alternatives
g [
N]
The debugging information, when fast-skip quasi-leap
is used, will
be lost.
We next discuss several issues on trying to make Prolog programs run fast in YAP. We assume two different programming styles:
loop(Env) :- do_something(Env,NewEnv), loop(NewEnv).
The indexation mechanism restricts the set of clauses to be tried in a procedure by using information about the status of the instantiated arguments of the goal. These arguments are then used as a key, selecting a restricted set of a clauses from all the clauses forming the procedure.
As an example, the two clauses for concatenate:
concatenate([],L,L). concatenate([H|T],A,[H|NT]) :- concatenate(T,A,NT).
If the first argument for the goal is a list, then only the second clause is of interest. If the first argument is the nil atom, the system needs to look only for the first clause. The indexation generates instructions that test the value of the first argument, and then proceed to a selected clause, or group of clauses.
Note that if the first argument was a free variable, then both clauses should be tried. In general, indexation will not be useful if the first argument is a free variable.
When activating a predicate, a Prolog system needs to store state information. This information, stored in a structure known as choice point or fail point, is necessary when backtracking to other clauses for the predicate. The operations of creating and using a choice point are very expensive, both in the terms of space used and time spent. Creating a choice point is not necessary if there is only a clause for the predicate as there are no clauses to backtrack to. With indexation, this situation is extended: in the example, if the first argument was the atom nil, then only one clause would really be of interest, and it is pointless to create a choice point. This feature is even more useful if the first argument is a list: without indexation, execution would try the first clause, creating a choice point. The clause would fail, the choice point would then be used to restore the previous state of the computation and the second clause would be tried. The code generated by the indexation mechanism would behave much more efficiently: it would test the first argument and see whether it is a list, and then proceed directly to the second clause.
An important side effect concerns the use of "cut". In the above example, some programmers would use a "cut" in the first clause just to inform the system that the predicate is not backtrackable and force the removal the choice point just created. As a result, less space is needed but with a great loss in expressive power: the "cut" would prevent some uses of the procedure, like generating lists through backtracking. Of course, with indexation the "cut" becomes useless: the choice point is not even created.
Indexation is also very important for predicates with a large number of clauses that are used like tables:
logician(aristoteles,greek). logician(frege,german). logician(russel,english). logician(godel,german). logician(whitehead,english).
An interpreter like C-Prolog, trying to answer the query:
?- logician(godel,X).
would blindly follow the standard Prolog strategy, trying first the first clause, then the second, the third and finally finding the relevant clause. Also, as there are some more clauses after the important one, a choice point has to be created, even if we know the next clauses will certainly fail. A "cut" would be needed to prevent some possible uses for the procedure, like generating all logicians. In this situation, the indexing mechanism generates instructions that implement a search table. In this table, the value of the first argument would be used as a key for fast search of possibly matching clauses. For the query of the last example, the result of the search would be just the fourth clause, and again there would be no need for a choice point.
If the first argument is a complex term, indexation will select clauses just by testing its main functor. However, there is an important exception: if the first argument of a clause is a list, the algorithm also uses the list's head if not a variable. For instance, with the following clauses,
rules([],B,B). rules([n(N)|T],I,O) :- rules_for_noun(N,I,N), rules(T,N,O). rules([v(V)|T],I,O) :- rules_for_verb(V,I,N), rules(T,N,O). rules([q(Q)|T],I,O) :- rules_for_qualifier(Q,I,N), rules(T,N,O).
if the first argument of the goal is a list, its head will be tested, and only the clauses matching it will be tried during execution.
Some advice on how to take a good advantage of this mechanism:
type(n(mary),person). type(n(john), person). type(n(chair),object). type(v(eat),active). type(v(rest),passive).
becomes more efficient with:
type(n(N),T) :- type_of_noun(N,T). type(v(V),T) :- type_of_verb(V,T). type_of_noun(mary,person). type_of_noun(john,person). type_of_noun(chair,object). type_of_verb(eat,active). type_of_verb(rest,passive).
YAP provides the user with the necessary facilities for writing predicates in a language other than Prolog. Since, under Unix systems, most language implementations are link-able to C, we will describe here only the YAP interface to the C language.
Before describing in full detail how to interface to C code, we will examine a brief example.
Assume the user requires a predicate my_process_id(Id)
which succeeds
when Id unifies with the number of the process under which YAP is running.
In this case we will create a my_process.c
file containing the
C-code described below.
#include "YAP/YAPInterface.h" static int my_process_id(void) { YAP_Term pid = YAP_MkIntTerm(getpid()); YAP_Term out = YAP_ARG1; return(YAP_Unify(out,pid)); } void init_my_predicates() { YAP_UserCPredicate("my_process_id",my_process_id,1); } |
The commands to compile the above file depend on the operating system. Under Linux (i386 and Alpha) you should use:
gcc -c -shared -fPIC my_process.c ld -shared -o my_process.so my_process.o
Under WIN32 in a MINGW/CYGWIN environment, using the standard installation path you should use:
gcc -mno-cygwin -I "c:/Yap/include" -c my_process.c gcc -mno-cygwin "c:/Yap/bin/yap.dll" --shared -o my_process.dll my_process.o
Under WIN32 in a pure CYGWIN environment, using the standard installation path, you should use:
gcc -I/usr/local -c my_process.c gcc -shared -o my_process.dll my_process.o /usr/local/bin/yap.dll
Under Solaris2 it is sufficient to use:
gcc -fPIC -c my_process.c
Under SunOS it is sufficient to use:
gcc -c my_process.c
Under Digital Unix you need to create a so
file. Use:
gcc tst.c -c -fpic ld my_process.o -o my_process.so -shared -expect_unresolved '*'
and replace my process.so
for my process.o
in the
remainder of the example.
And could be loaded, under YAP, by executing the following Prolog goal
load_foreign_files(['my_process'],[],init_my_predicates).
Note that since YAP4.3.3 you should not give the suffix for object files. YAP will deduce the correct suffix from the operating system it is running under.
After loading that file the following Prolog goal
my_process_id(N)
would unify N with the number of the process under which YAP is running.
Having presented a full example, we will now examine in more detail the contents of the C source code file presented above.
The include statement is used to make available to the C source code the macros for the handling of Prolog terms and also some YAP public definitions.
The function my_process_id
is the implementation, in C, of the
desired predicate. Note that it returns an integer denoting the success
of failure of the goal and also that it has no arguments even though the
predicate being defined has one.
In fact the arguments of a Prolog predicate written in C are accessed
through macros, defined in the include file, with names YAP_ARG1,
YAP_ARG2, ..., YAP_ARG16 or with YAP_A(N)
where N is the argument number (starting with 1). In the present
case the function uses just one local variable of type YAP_Term
, the
type used for holding YAP terms, where the integer returned by the
standard unix function getpid()
is stored as an integer term (the
conversion is done by YAP_MkIntTerm(Int))
. Then it calls the
pre-defined routine YAP_Unify(YAP_Term, YAP_Term)
which in turn returns an
integer denoting success or failure of the unification.
The role of the procedure init_my_predicates
is to make known to
YAP, by calling YAP_UserCPredicate
, the predicates being
defined in the file. This is in fact why, in the example above,
init_my_predicates
was passed as the third argument to
load_foreign_files
.
The rest of this appendix describes exhaustively how to interface C to YAP.
This section provides information about the primitives available to the C programmer for manipulating Prolog terms.
Several C typedefs are included in the header file yap/YAPInterface.h
to
describe, in a portable way, the C representation of Prolog terms.
The user should write is programs using this macros to ensure portability of
code across different versions of YAP.
The more important typedef is YAP_Term which is used to denote the type of a Prolog term.
Terms, from a point of view of the C-programmer, can be classified as follows
YAP_Bool YAP_IsVarTerm(YAP_Term t)
returns true iff its argument is an uninstantiated variable. Conversely the primitive
YAP_Bool YAP_NonVarTerm(YAP_Term t)
returns true iff its argument is not a variable.
The user can create a new uninstantiated variable using the primitive
YAP_Term YAP_MkVarTerm()
The following primitives can be used to discriminate among the different types of non-variable terms:
YAP_Bool YAP_IsIntTerm(YAP_Term t) YAP_Bool YAP_IsFloatTerm(YAP_Term t) YAP_Bool YAP_IsDbRefTerm(YAP_Term t) YAP_Bool YAP_IsAtomTerm(YAP_Term t) YAP_Bool YAP_IsPairTerm(YAP_Term t) YAP_Bool YAP_IsApplTerm(YAP_Term t)
Next, we mention the primitives that allow one to destruct and construct terms. All the above primitives ensure that their result is dereferenced, i.e. that it is not a pointer to another term.
The following primitives are provided for creating an integer term from an integer and to access the value of an integer term.
YAP_Term YAP_MkIntTerm(YAP_Int i) YAP_Int YAP_IntOfTerm(YAP_Term t)
where YAP_Int
is a typedef for the C integer type appropriate for
the machine or compiler in question (normally a long integer). The size
of the allowed integers is implementation dependent but is always
greater or equal to 24 bits: usually 32 bits on 32 bit machines, and 64
on 64 bit machines.
The two following primitives play a similar role for floating-point terms
YAP_Term YAP_MkFloatTerm(YAP_flt double) YAP_flt YAP_FloatOfTerm(YAP_Term t)
where flt
is a typedef for the appropriate C floating point type,
nowadays a double
The following primitives are provided for verifying whether a term is a big int, creating a term from a big integer and to access the value of a big int from a term.
YAP_Bool YAP_IsBigNumTerm(YAP_Term t) YAP_Term YAP_MkBigNumTerm(void *b) void *YAP_BigNumOfTerm(YAP_Term t, void *b)
YAP must support bignum for the configuration you are using (check the
YAP configuration and setup). For now, YAP only supports the GNU GMP
library, and void *
will be a cast for mpz_t
. Notice
that YAP_BigNumOfTerm
requires the number to be already
initialised. As an example, we show how to print a bignum:
static int p_print_bignum(void) { mpz_t mz; if (!YAP_IsBigNumTerm(YAP_ARG1)) return FALSE; mpz_init(mz); YAP_BigNumOfTerm(YAP_ARG1, mz); gmp_printf("Shows up as %Zd\n", mz); mpz_clear(mz); return TRUE; }
Currently, no primitives are supplied to users for manipulating data base references.
A special typedef YAP_Atom
is provided to describe Prolog
atoms (symbolic constants). The two following primitives can be used
to manipulate atom terms
YAP_Term YAP_MkAtomTerm(YAP_Atom at) YAP_Atom YAP_AtomOfTerm(YAP_Term t)
The following primitives are available for associating atoms with their names
YAP_Atom YAP_LookupAtom(char * s) YAP_Atom YAP_FullLookupAtom(char * s) char *YAP_AtomName(YAP_Atom t)
The function YAP_LookupAtom
looks up an atom in the standard hash
table. The function YAP_FullLookupAtom
will also search if the
atom had been "hidden": this is useful for system maintenance from C
code. The functor YAP_AtomName
returns a pointer to the string
for the atom.
The following primitives handle constructing atoms from strings with wide characters, and vice-versa:
YAP_Atom YAP_LookupWideAtom(wchar_t * s) wchar_t *YAP_WideAtomName(YAP_Atom t)
The following primitive tells whether an atom needs wide atoms in its representation:
int YAP_IsWideAtom(YAP_Atom t)
The following primitive can be used to obtain the size of an atom in a representation-independent way:
int YAP_AtomNameLength(YAP_Atom t)
The next routines give users some control over the atom garbage collector. They allow the user to guarantee that an atom is not to be garbage collected (this is important if the atom is hold externally to the Prolog engine, allow it to be collected, and call a hook on garbage collection:
int YAP_AtomGetHold(YAP_Atom at) int YAP_AtomReleaseHold(YAP_Atom at) int YAP_AGCRegisterHook(YAP_AGC_hook f) YAP_Term YAP_TailOfTerm(YAP_Term t)
A pair is a Prolog term which consists of a tuple of two Prolog terms designated as the head and the tail of the term. Pairs are most often used to build lists. The following primitives can be used to manipulate pairs:
YAP_Term YAP_MkPairTerm(YAP_Term Head, YAP_Term Tail) YAP_Term YAP_MkNewPairTerm(void) YAP_Term YAP_HeadOfTerm(YAP_Term t) YAP_Term YAP_TailOfTerm(YAP_Term t)
One can construct a new pair from two terms, or one can just build a pair whose head and tail are new unbound variables. Finally, one can fetch the head or the tail.
A compound term consists of a functor and a sequence of terms with
length equal to the arity of the functor. A functor, described in C by
the typedef Functor
, consists of an atom and of an integer.
The following primitives were designed to manipulate compound terms and
functors
YAP_Term YAP_MkApplTerm(YAP_Functor f, unsigned long int n, YAP_Term[] args) YAP_Term YAP_MkNewApplTerm(YAP_Functor f, int n) YAP_Term YAP_ArgOfTerm(int argno,YAP_Term ts) YAP_Term *YAP_ArgsOfTerm(YAP_Term ts) YAP_Functor YAP_FunctorOfTerm(YAP_Term ts)
The YAP_MkApplTerm
function constructs a new term, with functor
f (of arity n), and using an array args of n
terms with n equal to the arity of the
functor. YAP_MkNewApplTerm
builds up a compound term whose
arguments are unbound variables. YAP_ArgOfTerm
gives an argument
to a compound term. argno
should be greater or equal to 1 and
less or equal to the arity of the functor. YAP_ArgsOfTerm
returns a pointer to an array of arguments.
YAP allows one to manipulate the functors of compound term. The function
YAP_FunctorOfTerm
allows one to obtain a variable of type
YAP_Functor
with the functor to a term. The following functions
then allow one to construct functors, and to obtain their name and arity.
YAP_Functor YAP_MkFunctor(YAP_Atom a,unsigned long int arity) YAP_Atom YAP_NameOfFunctor(YAP_Functor f) YAP_Int YAP_ArityOfFunctor(YAP_Functor f)
Note that the functor is essentially a pair formed by an atom, and arity.
YAP provides a single routine to attempt the unification of two Prolog terms. The routine may succeed or fail:
Int YAP_Unify(YAP_Term a, YAP_Term b)
The routine attempts to unify the terms a and
b returning TRUE
if the unification succeeds and FALSE
otherwise.
The YAP C-interface now includes an utility routine to copy a string represented as a list of a character codes to a previously allocated buffer
int YAP_StringToBuffer(YAP_Term String, char *buf, unsigned int bufsize)
The routine copies the list of character codes String to a previously allocated buffer buf. The string including a terminating null character must fit in bufsize characters, otherwise the routine will simply fail. The StringToBuffer routine fails and generates an exception if String is not a valid string.
The C-interface also includes utility routines to do the reverse, that is, to copy a from a buffer to a list of character codes, to a difference list, or to a list of character atoms. The routines work either on strings of characters or strings of wide characters:
YAP_Term YAP_BufferToString(char *buf) YAP_Term YAP_NBufferToString(char *buf, size_t len) YAP_Term YAP_WideBufferToString(wchar_t *buf) YAP_Term YAP_NWideBufferToString(wchar_t *buf, size_t len) YAP_Term YAP_BufferToAtomList(char *buf) YAP_Term YAP_NBufferToAtomList(char *buf, size_t len) YAP_Term YAP_WideBufferToAtomList(wchar_t *buf) YAP_Term YAP_NWideBufferToAtomList(wchar_t *buf, size_t len)
Users are advised to use the N version of the routines. Otherwise, the user-provided string must include a terminating null character.
The C-interface function calls the parser on a sequence of characters stored at buf and returns the resulting term.
YAP_Term YAP_ReadBuffer(char *buf,YAP_Term *error)
The user-provided string must include a terminating null
character. Syntax errors will cause returning FALSE
and binding
error to a Prolog term.
The next routine can be used to ask space from the Prolog data-base:
void *YAP_AllocSpaceFromYAP(int size)
The routine returns a pointer to a buffer allocated from the code area,
or NULL
if sufficient space was not available.
The space allocated with YAP_AllocSpaceFromYAP
can be released
back to YAP by using:
void YAP_FreeSpaceFromYAP(void *buf)
The routine releases a buffer allocated from the code area. The system
may crash if buf
is not a valid pointer to a buffer in the code
area.
C
The C-Interface also provides the C-application with a measure of control over the YAP Input/Output system. The first routine allows one to find a file number given a current stream:
int YAP_StreamToFileNo(YAP_Term stream)
This function gives the file descriptor for a currently available stream. Note that null streams and in memory streams do not have corresponding open streams, so the routine will return a negative. Moreover, YAP will not be aware of any direct operations on this stream, so information on, say, current stream position, may become stale.
A second routine that is sometimes useful is:
void YAP_CloseAllOpenStreams(void)
This routine closes the YAP Input/Output system except for the first
three streams, that are always associated with the three standard Unix
streams. It is most useful if you are doing fork()
.
Last, one may sometimes need to flush all streams:
void YAP_CloseAllOpenStreams(void)
It is also useful before you do a fork()
, or otherwise you may
have trouble with unflushed output.
The next routine allows a currently open file to become a stream. The routine receives as arguments a file descriptor, the true file name as a string, an atom with the user name, and a set of flags:
void YAP_OpenStream(void *FD, char *name, YAP_Term t, int flags)
The available flags are YAP_INPUT_STREAM
,
YAP_OUTPUT_STREAM
, YAP_APPEND_STREAM
,
YAP_PIPE_STREAM
, YAP_TTY_STREAM
, YAP_POPEN_STREAM
,
YAP_BINARY_STREAM
, and YAP_SEEKABLE_STREAM
. By default, the
stream is supposed to be at position 0. The argument name gives
the name by which YAP should know the new stream.
C
The C-Interface provides the C-application with a a number of utility functions that are useful.
The first provides a way to insert a term into the data-base
void *YAP_Record(YAP_Term t)
This function returns a pointer to a copy of the term in the database (or to NULL if the operation fails.
The next functions provides a way to recover the term from the data-base:
YAP_Term YAP_Recorded(void *handle)
Notice that the semantics are the same as for recorded/3
: this
function creates a new copy of the term in the stack, with fresh
variables. The function returns 0L if it cannot create a new term.
Last, the next function allows one to recover space:
int YAP_Erase(void *handle)
Notice that any accesses using handle after this operation may lead to a crash.
The following functions are often required to compare terms.
The first function succeeds if two terms are actually the same term, as
==/2
:
int YAP_ExactlyEqual(YAP_Term t1, YAP_Term t2)
The second function succeeds if two terms are variant terms, and returns
0 otherwise, as
=/¯2
:
int YAP_Variant(YAP_Term t1, YAP_Term t2)
The second function computes a hash function for a term, as in
term_hash/4
.
YAP_Int YAP_TermHash(YAP_Term t, YAP_Int range, YAP_Int depth, int ignore_variables));
The first three arguments follow term_has/4
. The last argument
indicates what to do if we find a variable: if 0
fail, otherwise
ignore the variable.
C
back to PrologThere are several ways to call Prolog code from C-code. By default, the
YAP_RunGoal()
should be used for this task. It assumes the engine
has been initialised before:
YAP_RunGoal(YAP_Term Goal)
Execute query Goal and return 1 if the query succeeds, and 0 otherwise. The predicate returns 0 if failure, otherwise it will return an YAP_Term.
Quite often, one wants to run a query once. In this case you should use Goal:
YAP_RunGoalOnce(YAP_Term Goal)
The YAP_RunGoal()
function makes sure to recover stack space at
the end of execution.
Prolog terms are pointers: a problem users often find is that the term
Goal may actually be moved around during the execution of
YAP_RunGoal()
, due to garbage collection or stack shifting. If
this is possible, Goal will become invalid after executing
YAP_RunGoal()
. In this case, it is a good idea to save Goal
slots, as shown next:
long sl = YAP_InitSlot(scoreTerm); out = YAP_RunGoal(t); t = YAP_GetFromSlot(sl); YAP_RecoverSlots(1); if (out == 0) return FALSE;
Slots are safe houses in the stack, the garbage collector and the stack
shifter know about them and make sure they have correct values. In this
case, we use a slot to preserve t during the execution of
YAP_RunGoal
. When the execution of t is over we read the
(possibly changed) value of t back from the slot sl and tell
YAP that the slot sl is not needed and can be given back to the
system. The slot functions are as follows:
YAP_Int YAP_NewSlots(int
NumberOfSlots)
YAP_Int YAP_CurrentSlot(void)
YAP_Int YAP_InitSlot(YAP_Term
t)
YAP_Term *YAP_AddressFromSlot(YAP_Int
slot)
void YAP_PutInSlot(YAP_Int
slot, YAP_Term
t)
int YAP_RecoverSlots(int
HowMany)
YAP_Int YAP_ArgsToSlots(int
HowMany)
void YAP_SlotsToArgs(int
HowMany, YAP_Int
slot)
The following functions complement YAP_RunGoal:
YAP_RunGoal
will become invalid.
int YAP_Reset(void)
abort/0
built-in). This is useful when you want to start a new query before
asking all solutions to the previous query.
int YAP_ShutdownGoal(int backtrack)
backtrack
is true, stack space will be recovered and bindings
will be undone. In both cases, any slots allocated since the goal was
created will become invalid.
YAP_Bool YAP_GoalHasException(YAP_Term *tp)
void YAP_ClearExceptions(void)
The YAP_RunGoal interface is designed to be very robust, but may not be the most efficient when repeated calls to the same goal are made and when there is no interest in processing exception. The YAP_EnterGoal interface should have lower-overhead:
YAP_PredEntryPtr YAP_FunctorToPred(YAP_Functor
f,
YAP_PredEntryPtr YAP_AtomToPred(YAP_Atom
at,
YAP_Bool YAP_EnterGoal(YAP_PredEntryPtr
pe,
YAP_Term *
array, YAP_dogoalinfo *
infop)
Execute a query for predicate pe. The query is given as an
array of terms Array. infop is the address of a goal
handle that can be used to backtrack and to recover space. Succeeds if
a solution was found.
Notice that you cannot create new slots if an YAP_EnterGoal goal is open.
YAP_Bool YAP_RetryGoal(YAP_dogoalinfo *
infop)
YAP_EnterGoal
. The query is
given by the handle infop. Returns whether a new solution could
be be found.
YAP_Bool YAP_LeaveGoal(YAP_Bool
backtrack,
YAP_dogoalinfo *
infop)
Exit a query query created by YAP_EnterGoal
. If
backtrack
is TRUE
, variable bindings are undone and Heap
space is recovered. Otherwise, only stack space is recovered, ie,
LeaveGoal
executes a cut.
YAP_EnterGoal
:
void runall(YAP_Term g) { YAP_dogoalinfo goalInfo; YAP_Term *goalArgs = YAP_ArraysOfTerm(g); YAP_Functor *goalFunctor = YAP_FunctorOfTerm(g); YAP_PredEntryPtr goalPred = YAP_FunctorToPred(goalFunctor); result = YAP_EnterGoal( goalPred, goalArgs, &goalInfo ); while (result) result = YAP_RetryGoal( &goalInfo ); YAP_LeaveGoal(TRUE, &goalInfo); }
YAP allows calling a new Prolog interpreter from C
. One
way is to first construct a goal G
, and then it is sufficient to
perform:
YAP_Bool YAP_CallProlog(YAP_Term G)
the result will be FALSE
, if the goal failed, or TRUE
, if
the goal succeeded. In this case, the variables in G will store
the values they have been unified with. Execution only proceeds until
finding the first solution to the goal, but you can call
findall/3
or friends if you need all the solutions.
Notice that during execution, garbage collection or stack shifting may have moved the terms
YAP allows one to create a new module from C-code. To create the new code it is sufficient to call:
YAP_Module YAP_CreateModule(YAP_Atom ModuleName)
Notice that the new module does not have any predicates associated and that it is not the current module. To find the current module, you can call:
YAP_Module YAP_CurrentModule()
Given a module, you may want to obtain the corresponding name. This is possible by using:
YAP_Term YAP_ModuleName(YAP_Module mod)
Notice that this function returns a term, and not an atom. You can
YAP_AtomOfTerm
to extract the corresponding Prolog atom.
void YAP_Throw(YAP_Term exception)
void YAP_AsyncThrow(YAP_Term exception)
throw/2
. The function YAP_AsyncThrow is supposed to be used
from interrupt handlers.
int YAP_SetYAPFlag(yap_flag_t flag, int value)
C
.Currently,
only two boolean flags are accepted: YAPC_ENABLE_GC
and
YAPC_ENABLE_AGC
. The first enables/disables the standard garbage
collector, the second does the same for the atom garbage collector.`
int YAP_HaltRegisterHook(YAP_halt_hook f, void *closure)
0
if this cannot be determined on your operating system) and the closure
argument closure.
We will distinguish two kinds of predicates:
The first kind of predicates should be implemented as a C function with no arguments which should return zero if the predicate fails and a non-zero value otherwise. The predicate should be declared to YAP, in the initialization routine, with a call to
void YAP_UserCPredicate(char *name, YAP_Bool *fn(), unsigned long int arity);
where name is the name of the predicate, fn is the C function implementing the predicate and arity is its arity.
For the second kind of predicates we need three C functions. The first one is called when the predicate is first activated; the second one is called on backtracking to provide (possibly) other solutions; the last one is called on pruning. Note also that we normally also need to preserve some information to find out the next solution.
In fact the role of the two functions can be better understood from the following Prolog definition
p :- start. p :- repeat, continue.
where start
and continue
correspond to the two C functions
described above.
As an example we will consider implementing in C a predicate n100(N)
which, when called with an instantiated argument should succeed if that
argument is a numeral less or equal to 100, and, when called with an
uninstantiated argument, should provide, by backtracking, all the positive
integers less or equal to 100.
To do that we first declare a structure, which can only consist of Prolog terms, containing the information to be preserved on backtracking and a pointer variable to a structure of that type.
#include "YAPInterface.h" static int start_n100(void); static int continue_n100(void); typedef struct { YAP_Term next_solution; /* the next solution */ } n100_data_type; n100_data_type *n100_data;
We now write the C
function to handle the first call:
static int start_n100(void) { YAP_Term t = YAP_ARG1; YAP_PRESERVE_DATA(n100_data,n100_data_type); if(YAP_IsVarTerm(t)) { n100_data->next_solution = YAP_MkIntTerm(0); return continue_n100(); } if(!YAP_IsIntTerm(t) || YAP_IntOfTerm(t)<0 || YAP_IntOfTerm(t)>100) { YAP_cut_fail(); } else { YAP_cut_succeed(); } }
The routine starts by getting the dereference value of the argument.
The call to YAP_PRESERVE_DATA
is used to initialize the memory
which will hold the information to be preserved across
backtracking. The first argument is the variable we shall use, and the
second its type. Note that we can only use YAP_PRESERVE_DATA
once, so often we will want the variable to be a structure. This data
is visible to the garbage collector, so it should consist of Prolog
terms, as in the example. It is also correct to store pointers to
objects external to YAP stacks, as the garbage collector will ignore
such references.
If the argument of the predicate is a variable, the routine initializes the
structure to be preserved across backtracking with the information
required to provide the next solution, and exits by calling
continue_n100
to provide that solution.
If the argument was not a variable, the routine then checks if it was an
integer, and if so, if its value is positive and less than 100. In that
case it exits, denoting success, with YAP_cut_succeed
, or
otherwise exits with YAP_cut_fail
denoting failure.
The reason for using for using the functions YAP_cut_succeed
and
YAP_cut_fail
instead of just returning a non-zero value in the
first case, and zero in the second case, is that otherwise, if
backtracking occurred later, the routine continue_n100
would be
called to provide additional solutions.
The code required for the second function is
static int continue_n100(void) { int n; YAP_Term t; YAP_Term sol = YAP_ARG1; YAP_PRESERVED_DATA(n100_data,n100_data_type); n = YAP_IntOfTerm(n100_data->next_solution); if( n == 100) { t = YAP_MkIntTerm(n); YAP_Unify(sol,t); YAP_cut_succeed(); } else { YAP_Unify(sol,n100_data->next_solution); n100_data->next_solution = YAP_MkIntTerm(n+1); return(TRUE); } }
Note that again the macro YAP_PRESERVED_DATA
is used at the
beginning of the function to access the data preserved from the previous
solution. Then it checks if the last solution was found and in that
case exits with YAP_cut_succeed
in order to cut any further
backtracking. If this is not the last solution then we save the value
for the next solution in the data structure and exit normally with 1
denoting success. Note also that in any of the two cases we use the
function YAP_unify
to bind the argument of the call to the value
saved in n100_state->next_solution
.
Note also that the only correct way to signal failure in a backtrackable
predicate is to use the YAP_cut_fail
macro.
Backtrackable predicates should be declared to YAP, in a way similar to what happened with deterministic ones, but using instead a call to
void YAP_UserBackCutCPredicate(char *name, int *init(), int *cont(), int *cut(), unsigned long int arity, unsigned int sizeof);
where name is a string with the name of the predicate, init, cont, cut are the C functions used to start, continue and when pruning the execution of the predicate, arity is the predicate arity, and sizeof is the size of the data to be preserved in the stack. In this example, we would have something like
void init_n100(void) { YAP_UserBackCutCPredicate("n100", start_n100, continue_n100, cut_n100, 1, 1); }
The argument before last is the predicate's arity. Notice again the
last argument to the call. function argument gives the extra space we
want to use for PRESERVED_DATA
. Space is given in cells, where
a cell is the same size as a pointer. The garbage collector has access
to this space, hence users should use it either to store terms or to
store pointers to objects outside the stacks.
The code for cut_n100
could be:
static int cut_n100(void) { YAP_PRESERVED_DATA_CUT(n100_data,n100_data_type*); fprintf("n100 cut with counter %ld\n", YAP_IntOfTerm(n100_data->next_solution)); return TRUE; }
Notice that we have to use YAP_PRESERVED_DATA_CUT
: this is because the Prolog engine is at a different state during cut.
If no work is required at cut, we can use:
void init_n100(void) { YAP_UserBackCutCPredicate("n100", start_n100, continue_n100, NULL, 1, 1); }
in this case no code is executed at cut time.
The primitive predicate
load_foreign_files(Files,Libs,InitRoutine)
should be used, from inside YAP, to load object files produced by the C
compiler. The argument ObjectFiles should be a list of atoms
specifying the object files to load, Libs is a list (possibly
empty) of libraries to be passed to the unix loader (ld
) and
InitRoutine is the name of the C routine (to be called after the files
are loaded) to perform the necessary declarations to YAP of the
predicates defined in the files.
YAP will search for ObjectFiles in the current directory first. If
it cannot find them it will search for the files using the environment
variable YAPLIBDIR
, if defined, or in the default library.
YAP also supports the SWI-Prolog interface to loading foreign code:
open_shared_object(+
File, -
Handle)
open_shared_object(File, [], Handle)
. See also
load_foreign_library/[1,2].
On errors, an exception shared_object
(Action,
Message) is raised. Message is the return value from
dlerror().
open_shared_object(+
File, -
Handle, +
Options)
open_shared_object/2
, but allows for additional flags to
be passed. Options is a list of atoms. now
implies the
symbols are
resolved immediately rather than lazily (default). global
implies
symbols of the loaded object are visible while loading other shared
objects (by default they are local). Note that these flags may not
be supported by your operating system. Check the documentation of
dlopen()
or equivalent on your operating system. Unsupported
flags are silently ignored.
close_shared_object(+
Handle)
call_shared_object_function(+
Handle, +
Function)
PL_register_foreign()
.
YAP4 currently does not support save
and restore
for object code
loaded with load_foreign_files
. We plan to support save and restore
in future releases of YAP.
YAP4 includes several changes over the previous load_foreign_files
interface. These changes were required to support the new binary code
formats, such as ELF used in Solaris2 and Linux.
YAPInterface.h
to
take advantage of the new interface. c_interface.h
is still
available if you cannot port the code to the new interface.
YAP_ARG1
to YAP_ARG16
. This change breaks code such as
unify(&ARG1,&t)
, which is nowadays:
{ YAP_Unify(ARG1, t); }
cut_fail()
and cut_succeed()
are now functions.
Deref
is deprecated. All functions that return
Prolog terms, including the ones that access arguments, already
dereference their arguments.
YAP can be used as a library to be called from other programs. To do so, you must first create the YAP library:
make library make install_library
This will install a file libyap.a
in LIBDIR and the Prolog
headers in INCLUDEDIR. The library contains all the functionality
available in YAP, except the foreign function loader and for
YAP
's startup routines.
To actually use this library you must follow a five step process:
YAP_FastInit
asks for a contiguous chunk in your memory space, fills
it in with the data-base, and sets up YAP's stacks and
execution registers. You can use a saved space from a standard system by
calling save_program/1
.
YAP_RunGoal(query)
to actually evaluate your
query. The argument is the query term query
, and the result is 1
if the query succeeded, and 0 if it failed.
YAP_RestartGoal()
to obtain the next solution.
The next program shows how to use this system. We assume the saved program contains two facts for the procedure b:
#include <stdio.h> #include "YAP/YAPInterface.h" int main(int argc, char *argv[]) { if (YAP_FastInit("saved_state") == YAP_BOOT_ERROR) exit(1); if (YAP_RunGoal(YAP_MkAtomTerm(YAP_LookupAtom("do")))) { printf("Success\n"); while (YAP_RestartGoal()) printf("Success\n"); } printf("NO\n"); } |
The program first initializes YAP, calls the query for the first time and succeeds, and then backtracks twice. The first time backtracking succeeds, the second it fails and exits.
To compile this program it should be sufficient to do:
cc -o exem -I../YAP4.3.0 test.c -lYAP -lreadline -lm
You may need to adjust the libraries and library paths depending on the Operating System and your installation of YAP.
Note that YAP4.3.0 provides the first version of the interface. The interface may change and improve in the future.
The following C-functions are available from YAP:
YAP_Term
Clause)
Compile the Prolog term Clause and assert it as the last clause
for the corresponding procedure.
int
YAP_ContinueGoal(void
)
Continue execution from the point where it stopped.
void
YAP_Error(int
ID,YAP_Term
Cause,char *
error_description)
Generate an YAP System Error with description given by the string
error_description. ID is the error ID, if known, or
0
. Cause is the term that caused the crash.
void
YAP_Exit(int
exit_code)
Exit YAP immediately. The argument exit_code gives the error code
and is supposed to be 0 after successful execution in Unix and Unix-like
systems.
YAP_Term
YAP_GetValue(Atom
at)
Return the term value associated with the atom at. If no
such term exists the function will return the empty list.
char *
SavedState)
Initialize a copy of YAP from SavedState. The copy is
monolithic and currently must be loaded at the same address where it was
saved. YAP_FastInit
is a simpler version of YAP_Init
.
C
structure of type YAP_init_args
.
The fields of InitInfo are char *
SavedState,
int
HeapSize, int
StackSize, int
TrailSize, int
NumberofWorkers, int
SchedulerLoop, int
DelayedReleaseLoad, int
argc, char **
argv, int
ErrorNo, and
char *
ErrorCause. The function returns an integer, which
indicates the current status. If the result is YAP_BOOT_ERROR
booting failed.
If SavedState is not NULL, try to open and restore the file
SavedState. Initially YAP will search in the current directory. If
the saved state does not exist in the current directory YAP will use
either the default library directory or the directory given by the
environment variable YAPLIBDIR
. Note that currently
the saved state must be loaded at the same address where it was saved.
If HeapSize is different from 0 use HeapSize as the minimum size of the Heap (or code space). If StackSize is different from 0 use HeapSize as the minimum size for the Stacks. If TrailSize is different from 0 use TrailSize as the minimum size for the Trails.
The NumberofWorkers, NumberofWorkers, and DelayedReleaseLoad are only of interest to the or-parallel system.
The argument count argc and string of arguments argv arguments are to be passed to user programs as the arguments used to call YAP.
If booting failed you may consult ErrorNo
and ErrorCause
for the cause of the error, or call
YAP_Error(ErrorNo,0L,ErrorCause)
to do default processing.
void
YAP_PutValue(Atom
at, YAP_Term
value)
Associate the term value with the atom at. The term
value must be a constant. This functionality is used by YAP as a
simple way for controlling and communicating with the Prolog run-time.
YAP_Term
YAP_Read(int (*)(void)
GetC)
Parse a Term using the function GetC to input characters.
YAP_Term
YAP_Write(YAP_Term
t)
Copy a Term t and all associated constraints. May call the garbage
collector and returns 0L
on error (such as no space being
available).
void
YAP_Write(YAP_Term
t, void (*)(int)
PutC, int
flags)
Write a Term t using the function PutC to output
characters. The term is written according to a mask of the following
flags in the flag
argument: YAP_WRITE_QUOTED
,
YAP_WRITE_HANDLE_VARS
, and YAP_WRITE_IGNORE_OPS
.
void
YAP_WriteBuffer(YAP_Term
t, char *
buff, unsigned int
size, int
flags)
Write a YAP_Term t to buffer buff with size size. The
term is written according to a mask of the following flags in the
flag
argument: YAP_WRITE_QUOTED
,
YAP_WRITE_HANDLE_VARS
, and YAP_WRITE_IGNORE_OPS
.
void
YAP_InitConsult(int
mode, char *
filename)
Enter consult mode on file filename. This mode maintains a few
data-structures internally, for instance to know whether a predicate
before or not. It is still possible to execute goals in consult mode.
If mode is TRUE
the file will be reconsulted, otherwise
just consulted. In practice, this function is most useful for
bootstrapping Prolog, as otherwise one may call the Prolog predicate
compile/1
or consult/1
to do compilation.
Note that it is up to the user to open the file filename. The
YAP_InitConsult
function only uses the file name for internal
bookkeeping.
void
YAP_EndConsult(void
)
Finish consult mode.
Some observations:
mmap
. This problem will be addressed in future
versions of YAP.
boot.yap
and init.yap
files.
YAP has been designed to be as compatible as possible with other Prolog systems, and initially with C-Prolog. More recent work on YAP has included features initially proposed for the Quintus and SICStus Prolog systems.
Developments since YAP4.1.6
we have striven at making
YAP compatible with the ISO-Prolog standard.
C-Prolog Compatibility
YAP includes several extensions over the original C-Prolog system. Even so, most C-Prolog programs should run under YAP without changes.
The most important difference between YAP and C-Prolog is that, being
YAP a compiler, some changes should be made if predicates such as
assert
, clause
and retract
are used. First
predicates which will change during execution should be declared as
dynamic
by using commands like:
:- dynamic f/n.
where f
is the predicate name and n is the arity of the
predicate. Note that several such predicates can be declared in a
single command:
:- dynamic f/2, ..., g/1.
Primitive predicates such as retract
apply only to dynamic
predicates. Finally note that not all the C-Prolog primitive predicates
are implemented in YAP. They can easily be detected using the
unknown
system predicate provided by YAP.
Last, by default YAP enables character escapes in strings. You can disable the special interpretation for the escape character by using:
:- yap_flag(character_escapes,off).
or by using:
:- yap_flag(language,cprolog).
These are the Prolog built-ins that are fully compatible in both C-Prolog and YAP:
These are YAP built-ins that are also available in C-Prolog, but that are not fully compatible:
These are YAP built-ins not available in C-Prolog.
These are C-Prolog built-ins not available in YAP:
'LC'
'NOLC'
The Quintus Prolog system was the first Prolog compiler to use Warren's Abstract Machine. This system was very influential in the Prolog community. Quintus Prolog implemented compilation into an abstract machine code, which was then emulated. Quintus Prolog also included several new built-ins, an extensive library, and in later releases a garbage collector. The SICStus Prolog system, developed at SICS (Swedish Institute of Computer Science), is an emulator based Prolog system largely compatible with Quintus Prolog. SICStus Prolog has evolved through several versions. The current version includes several extensions, such as an object implementation, co-routining, and constraints.
Recent work in YAP has been influenced by work in Quintus and SICStus Prolog. Wherever possible, we have tried to make YAP compatible with recent versions of these systems, and specifically of SICStus Prolog. You should use
:- yap_flag(language, sicstus).
for maximum compatibility with SICStus Prolog.
SICStus Compatibility
Both YAP and SICStus Prolog obey the Edinburgh Syntax and are based on the WAM. Even so, there are quite a few important differences:
fcompile/1
and load/1
built-ins are
not available in YAP.
initialization/1
as per the ISO
standard. Use prolog_initialization/1
for the SICStus Prolog
compatible built-in.
on_exception/3
and
raise_exception
built-ins correspond to the ISO built-ins
catch/3
and throw/1
.
file_search_path/2
,
stream_interrupt/3
, reinitialize/0
, help/0
,
help/1
, trimcore/0
, load_files/1
,
load_files/2
, and require/1
.
The previous list is incomplete. We also cannot guarantee full compatibility for other built-ins (although we will try to address any such incompatibilities). Last, SICStus Prolog is an evolving system, so one can be expect new incompatibilities to be introduced in future releases of SICStus Prolog.
assert_static/1
and abolish/1
built-ins. This is not allowed in Quintus Prolog or SICStus Prolog.
The following differences only exist if the language
flag is set
to yap
(the default):
consult/1
predicate in YAP follows C-Prolog
semantics. That is, it adds clauses to the data base, even for
preexisting procedures. This is different from consult/1
in
SICStus Prolog.
:- dynamic a/1. ?- assert(a(1)). ?- retract(a(X)), X1 is X +1, assertz(a(X)).
With immediate semantics, new clauses or entries to the data base are
visible in backtracking. In this example, the first call to
retract/1
will succeed. The call to assertz/1 will then
succeed. On backtracking, the system will retry
retract/1
. Because the newly asserted goal is visible to
retract/1
, it can be retracted from the data base, and
retract(a(X))
will succeed again. The process will continue
generating integers for ever. Immediate semantics were used in C-Prolog.
With logical update semantics, any additions or deletions of clauses
for a goal will not affect previous activations of the
goal. In the example, the call to assertz/1
will not see the
update performed by the assertz/1
, and the query will have a
single solution.
Calling yap_flag(update_semantics,logical)
will switch
YAP to use logical update semantics.
dynamic/1
is a built-in, not a directive, in YAP.
:- yap_flag(unknown,error).
These are the Prolog built-ins that are fully compatible in both SICStus Prolog and YAP:
These are YAP built-ins that are also available in SICStus Prolog, but that are not fully compatible:
These are YAP built-ins not available in SICStus Prolog.
The Prolog standard was developed by ISO/IEC JTC1/SC22/WG17, the international standardization working group for the programming language Prolog. The book "Prolog: The Standard" by Deransart, Ed-Dbali and Cervoni gives a complete description of this standard. Development in YAP from YAP4.1.6 onwards have striven at making YAP compatible with ISO Prolog. As such:
YAP by default is not fully ISO standard compliant. You can set the
language
flag to iso
to obtain very good
compatibility. Setting this flag changes the following:
assert/1
,
retract/1
, and friends.
Calling set_prolog_flag(update_semantics,logical)
will switch
YAP to use logical update semantics.
atom_chars/2
(see Testing Terms), and number_chars/2
, (see Testing Terms), built-ins as per the original Quintus Prolog definition, and
not as per the ISO definition.
Calling set_prolog_flag(to_chars_mode,iso)
will switch
YAP to use the ISO definition for
atom_chars/2
and number_chars/2
.
:- set_prolog_flag(unknown,error).
set_prolog_flag/2
and op/3
).
strict_iso
flag automatically enables the ISO Prolog
standard. This feature should disable all features not present in the
standard.
The following incompatibilities between YAP and the ISO standard are known to still exist:
Please inform the authors on other incompatibilities that may still exist.
The Prolog syntax caters for operators of three main kinds:
Each operator has precedence in the range 1 to 1200, and this precedence is used to disambiguate expressions where the structure of the term denoted is not made explicit using brackets. The operator of higher precedence is the main functor.
If there are two operators with the highest precedence, the ambiguity is solved analyzing the types of the operators. The possible infix types are: xfx, xfy, and yfx.
With an operator of type xfx both sub-expressions must have lower precedence than the operator itself, unless they are bracketed (which assigns to them zero precedence). With an operator type xfy only the left-hand sub-expression must have lower precedence. The opposite happens for yfx type.
A prefix operator can be of type fx or fy. A postfix operator can be of type xf or yf. The meaning of the notation is analogous to the above.
a + b * c
means
a + (b * c)
as + and * have the following types and precedences:
:-op(500,yfx,'+'). :-op(400,yfx,'*').
Now defining
:-op(700,xfy,'++'). :-op(700,xfx,'=:='). a ++ b =:= c
means
a ++ (b =:= c)
The following is the list of the declarations of the predefined operators:
:-op(1200,fx,['?-', ':-']). :-op(1200,xfx,[':-','-->']). :-op(1150,fx,[block,dynamic,mode,public,multifile,meta_predicate, sequential,table,initialization]). :-op(1100,xfy,[';','|']). :-op(1050,xfy,->). :-op(1000,xfy,','). :-op(999,xfy,'.'). :-op(900,fy,['\+', not]). :-op(900,fx,[nospy, spy]). :-op(700,xfx,[@>=,@=<,@<,@>,<,=,>,=:=,=\=,\==,>=,=<,==,\=,=..,is]). :-op(500,yfx,['\/','/\','+','-']). :-op(500,fx,['+','-']). :-op(400,yfx,['<<','>>','//','*','/']). :-op(300,xfx,mod). :-op(200,xfy,['^','**']). :-op(50,xfx,same).
!/0
: Control,/2
: Control->*/2
: Control->/2
: Control;/2
: Control</2
: Arithmetic=../2
: Testing Terms=/2
: Testing Terms=/¯2
: Testing Terms=:=/2
: Arithmetic=</2
: Arithmetic==/2
: Comparing Terms=@=/2
: SWI-Prolog=\=/2
: Arithmetic>/2
: Arithmetic>=/2
: Arithmetic@</2
: Comparing Terms@=</2
: Comparing Terms@>/2
: Comparing Terms@>=/2
: Comparing Terms[-]/1
: Compiling[]/1
: Compiling\+/1
: Control\=/2
: Testing Terms\==/2
: Comparing Termsabolish/1
: Modifying the Databaseabolish/2
: Modifying the Databaseabolish_all_tables/0
: Tablingabolish_table/1
: Tablingabort/0
: Controlabsolute_file_name/2
: Streams and Filesabsolute_file_name/3
: Streams and Filesadd_edges/3
: UGraphsadd_to_array_element/4
: Arraysadd_to_heap/4
: Heapsadd_to_path/1
: Setting the Compileradd_to_path/2
: Setting the Compileradd_vertices/3
: UGraphsagc_margin (yap_flag/2 option)
: Miscaggregate/3
: Aggregateaggregate/4
: Aggregateaggregate_all/3
: Aggregateaggregate_all/4
: Aggregatealarm/3
: OSall/3
: Setsalways_prompt_user/0
: I/O Controlappend/2
: Listsappend/3
: Listsappend/3
: SWI-Prologarg/3
: Testing Termsargv (yap_flag/2 option)
: Miscarray/2
: Arraysarray_element/3
: Arraysassert/1
: Modifying the Databaseassert/2
: Database Referencesassert_static/1
: Modifying the Databaseasserta/1
: Modifying the Databaseasserta/2
: Database Referencesasserta_static/1
: Modifying the Databaseassertz/1
: Modifying the Databaseassertz/2
: Database Referencesassertz_static/1
: Modifying the Databaseassoc_to_list/2
: Association Listsat_end_of_stream/0
: Streams and Filesat_end_of_stream/1
: Streams and Filesatom/1
: Testing Termsatom_chars/2
: Predicates on Atomsatom_codes/2
: Predicates on Atomsatom_concat/2
: Predicates on Atomsatom_concat/3
: Predicates on Atomsatom_length/2
: Predicates on Atomsatom_number/2
: Predicates on Atomsatom_to_chars/2
: String I/Oatom_to_chars/3
: String I/Oatom_to_term/3
: String I/Oatomic/1
: Testing Termsatomic_concat/2
: Predicates on Atomsatomic_list_concat/2
: Predicates on Atomsatomic_list_concat/3
: Predicates on Atomsatoms (statistics/2 option)
: Miscattr_portray_hook/2
: New Style Attribute Declarationsattr_unify_hook/2
: New Style Attribute Declarationsattribute/1 (declaration)
: Attribute Declarationsattribute_goal/2
: Displaying Attributesattribute_goals/2
: New Style Attribute Declarationsattvar/1
: Attributed Unificationattvar/1
: New Style Attribute Declarationsavl_insert/4
: AVL Treesavl_lookup/3
: AVL Treesavl_new/1
: AVL Treesb_getval/2
: Global Variablesb_getval/2
: SWI-Prolog Global Variablesb_setval/2
: SWI-Prolog Global Variablesb_setval/2
: Global Variablesbagof/3
: Setsbb_delete/2
: BlackBoardbb_get/2
: BlackBoardbb_put/2
: BlackBoardbb_update/3
: BlackBoardbetween/3
: SWI-Prologbetween/3
: Arithmeticbounded (yap_flag/2 option)
: Miscbreak/0
: ControlC/3
: Grammarscall/1
: Controlcall/n
: Controlcall_cleanup/1
: Cleanupcall_cleanup/2
: Cleanupcall_count_data/0
: Call Countingcall_count_data/3
: Call Countingcall_counting (yap_flag/2 option)
: Misccall_residue/2
: Co-routiningcall_residue_vars/2
: Co-routiningcall_shared_object_function/2
: Loading Objectscall_with_args/n
: Controlcallable/1
: Testing Termscatch/3
: Controlcd/0
: OScd/1
: OSchar_code/2
: Predicates on Characterschar_conversion (yap_flag/2 option)
: Miscchar_conversion/2
: I/O of Termschar_type/2
: Predicates on Characterscharacter_count/2
: Streams and Filescharacter_escapes (yap_flag/2 option)
: Miscchdir/1
: SWI-Prologchecklist/2
: MapListchecknodes/3
: MapListclause/2
: Modifying the Databaseclause/3
: Modifying the Databasecleanup_all/0
: Cleanupclose/1
: Streams and Filesclose/2
: Streams and Filesclose_matlab/0
: MATLABclose_shared_object/1
: Loading Objectsclose_static_array/1
: Arrayscode_type/2
: Predicates on Characterscompare/3
: Comparing Termscompile/1
: Compilingcompile_expressions/0
: Setting the Compilercomplement/2
: UGraphscompose/3
: UGraphscompound/1
: Testing Termsconcat_atom/2
: SWI-Prologconcat_atom/3
: SWI-Prologconsult/1
: Compilingconvlist/3
: MapListcopy_line/2
: LineUtilitiescopy_term/2
: Testing Termscopy_term/3
: New Style Attribute Declarationscopy_term_nat/2
: New Style Attribute Declarationscputime (statistics/2 option)
: Misccreate_mutable/2
: Term Modificationcreate_prolog_flag/2
: Misccurrent_atom/1
: Looking at the Databasecurrent_char_conversion/2
: I/O of Termscurrent_foreign_library/2
: shlibcurrent_input/1
: Streams and Filescurrent_key/2
: Internal Databasecurrent_line_number/1
: Streams and Filescurrent_line_number/2
: Streams and Filescurrent_module/1
: Predscurrent_module/2
: Predscurrent_mutex/3
: Thread Synchronisationcurrent_op/3
: Misccurrent_output/1
: Streams and Filescurrent_predicate/1
: Looking at the Databasecurrent_predicate/2
: Looking at the Databasecurrent_prolog_flag/2
: Misccurrent_stream/3
: Streams and Filescurrent_thread/2
: Monitoring Threadscyclic_term/1
: Testing Termscyclic_term/1
: Termsdatime/1
: Systemdb_assert/1
: Insertion of Rowsdb_assert/2
: Insertion of Rowsdb_close/1
: Connecting to and disconnecting from a Database Serverdb_datalog_describe/1
: Describing a Relationdb_datalog_describe/2
: Describing a Relationdb_describe/1
: Describing a Relationdb_describe/2
: Describing a Relationdb_get_attributes_types/2
: Types of Attributesdb_get_attributes_types/3
: Types of Attributesdb_import/2
: Accessing a Relationdb_import/3
: Accessing a Relationdb_insert/2
: Insertion of Rowsdb_insert/3
: Insertion of Rowsdb_module/1
: Other MYDDAS Propertiesdb_my_result_set/1
: Other MYDDAS Propertiesdb_my_sql_mode/1
: Other MYDDAS Propertiesdb_my_sql_mode/2
: Other MYDDAS Propertiesdb_number_of_fields/2
: Number of Fieldsdb_number_of_fields/3
: Number of Fieldsdb_open/4
: Connecting to and disconnecting from a Database Serverdb_open/5
: Connecting to and disconnecting from a Database Serverdb_reference/1C
: Testing Termsdb_show_tables/1
: Enumerating Relationsdb_show_tables/2
: Enumerating Relationsdb_sql/2
: Accessing Tables in Data Sources Using SQLdb_sql/3
: Accessing Tables in Data Sources Using SQLdb_top_level/4
: The MYDDAS MySQL Top Leveldb_top_level/5
: The MYDDAS MySQL Top Leveldb_view/2
: View Level Interfacedb_view/3
: View Level Interfacedebug (yap_flag/2 option)
: Miscdebug/0
: Deb Predsdebugger_print_options (yap_flag/2 option)
: Miscdebugging/0
: Deb Predsdel_assoc/4
: Association Listsdel_attr/2
: New Style Attribute Declarationsdel_attrs/1
: New Style Attribute Declarationsdel_edges/3
: UGraphsdel_max_assoc/4
: Association Listsdel_min_assoc/4
: Association Listsdel_vertices/3
: UGraphsdelete/3
: Listsdelete_file/1
: Systemdelete_file/2
: Systemdgraph_add_edge/4
: DGraphsdgraph_add_edges/3
: DGraphsdgraph_add_vertex/3
: DGraphsdgraph_add_vertices/3
: DGraphsdgraph_complement/2
: DGraphsdgraph_compose/3
: DGraphsdgraph_del_edge/4
: DGraphsdgraph_del_edges/3
: DGraphsdgraph_del_vertex/3
: DGraphsdgraph_del_vertices/3
: DGraphsdgraph_edge/2
: DGraphsdgraph_edges/2
: DGraphsdgraph_isomorphic/4
: DGraphsdgraph_max_path/5
: DGraphsdgraph_min_path/5
: DGraphsdgraph_min_paths/3
: DGraphsdgraph_neighbors/3
: DGraphsdgraph_neighbours/3
: DGraphsdgraph_new/1
: DGraphsdgraph_path/3
: DGraphsdgraph_symmetric_closure/2
: DGraphsdgraph_to_ugraph/2
: DGraphsdgraph_to_undgraph/2
: UnDGraphsdgraph_top_sort/2
: DGraphsdgraph_top_sort/3
: DGraphsdgraph_transitive_closure/2
: DGraphsdgraph_transpose/2
: DGraphsdgraph_vertices/2
: DGraphsdialect (yap_flag/2 option)
: Miscdif/2
: Co-routiningdirectory (prolog_load_context/2 option)
: Miscdirectory_files/2
: Systemdiscontiguous/1 (directive)
: Setting the Compilerdiscontiguous_warnings (yap_flag/2 option)
: Miscdisplay/1
: I/O of Termsdisplay/2
: I/O for Streamsdo_not_compile_expressions/0
: Setting the Compilerdollar_as_lower_case (yap_flag/2 option)
: Miscdouble_quotes (yap_flag/2 option)
: Miscduplicate_term/2
: Testing Termsdynamic/1
: Databasedynamic_code (statistics/2 option)
: Miscdynamic_predicate/2
: Databaseedges/2
: UGraphselif/1 directive
: Conditional Compilationelse/0 directive
: Conditional Compilationempty_assoc/1
: Association Listsempty_heap/1
: Heapsempty_queue/1
: Queuesendif/0 directive
: Conditional Compilationensure_loaded/1
: Compilingenviron/2
: OSenviron/2
: Systemerase/1
: Internal Databaseeraseall/1
: Internal Databaseerased/1
: Internal Databaseexception/3
: Undefined Proceduresexclude/3
: MapListexec/3
: Systemexecutable(yap_flag/2 option)
: Miscexists/1
: I/O Controlexpand_exprs/2
: Setting the Compilerexpand_file_name/2
: Setting the Compilerexpand_term/2
: Grammarsfail/0
: Controlfalse/0
: Controlfast (yap_flag/2 option)
: Miscfields/2
: LineUtilitiesfields/3
: LineUtilitiesfile (prolog_load_context/2 option)
: Miscfile_base_name/2
: Streams and Filesfile_exists/1
: Systemfile_exists/2
: Systemfile_filter/3
: LineUtilitiesfile_filter_with_init/5
: LineUtilitiesfile_name_extension/3
: Streams and Filesfile_property/2
: Systemfile_search_path/2
: Setting the Compilerfileerrors (yap_flag/2 option)
: Miscfileerrors/0
: I/O Controlfilter/3
: LineUtilitiesfindall/3
: Setsfindall/4
: Setsflatten/2
: Listsfloat/1
: Testing Termsfloat_format (yap_flag/2 option)
: Miscflush_output/0
: Streams and Filesflush_output/1
: Streams and Filesforall/2
: Controlforall/2
: Forallforeach/2
: Aggregateformat/1
: I/O of Termsformat/2
: I/O of Termsformat/3
: I/O of Termsformat_to_chars/3
: String I/Oformat_to_chars/4
: String I/Ofragile
: Cleanupfree_variables/4
: Aggregatefreeze/2
: Co-routiningfrozen/2
: Co-routiningfunctor/3
: Testing Termsgarbage_collect/0
: Controlgarbage_collect_atoms/0
: Controlgarbage_collection (statistics/2 option)
: Miscgc (yap_flag/2 option)
: Miscgc/0
: Controlgc_margin (yap_flag/2 option)
: Miscgc_trace (yap_flag/2 option)
: Miscgen_assoc/3
: Association Listsgenerate_debugging_info (yap_flag/2 option)
: Miscget/1
: I/O of Charactersget/2
: I/O for Streamsget0/1
: I/O of Charactersget0/2
: I/O for Streamsget_assoc/3
: Association Listsget_assoc/5
: Association Listsget_attr/3
: New Style Attribute Declarationsget_attrs/2
: New Style Attribute Declarationsget_atts/2
: Attribute Manipulationget_byte/1
: I/O of Charactersget_byte/2
: I/O for Streamsget_char/1
: I/O of Charactersget_char/2
: I/O for Streamsget_code/1
: I/O of Charactersget_code/2
: I/O for Streamsget_from_heap/4
: Heapsget_label/3
: Treesget_mutable/2
: Term Modificationget_next_assoc/4
: Association Listsget_prev_assoc/4
: Association Listsget_value/2
: Internal Databasegetcwd/1
: OSgetrand/1
: Randomglobal_stack (statistics/2 option)
: Miscglue/3
: LineUtilitiesgoal_expansion/3
: Grammarsground/1
: Testing Termsgrow_stack/1
: Controlhalt/0
: Controlhalt/1
: Controlhead_queue/2
: Queuesheap (statistics/2 option)
: Mischeap_size/2
: Heapsheap_to_list/2
: Heapshide/1
: Setting the Compilerhide_predicate/1
: Setting the Compilerhost_id/1
: Systemhost_name/1
: Systemhost_type (yap_flag/2 option)
: Miscif/1 directive
: Conditional Compilationif/3
: Controlignore/1
: Controlinclude/1 (directive)
: Compilinginclude/3
: MapListincore/1
: Controlindex (yap_flag/2 option)
: Miscinformational_messages (yap_flag/2 option)
: Miscinitialization/0
: Miscinitialization/1 (directive)
: Setting the Compilerinitialization/2 (directive)
: Setting the Compilerinstance/2
: Internal Databaseinteger/1
: Testing Termsinteger_rounding_function (yap_flag/2 option)
: Miscintersection/3
: Listsis/2
: Arithmeticis_assoc/1
: Association Listsis_list/1
: Testing Termsis_mutable/1
: Term Modificationis_rbtree/1
: Red-Black Treesis_stream/1
: Streams and Filesis_tabled/1
: Tablingjoin_queue/3
: Queuesjump_queue/3
: Queueskey_statistics/3
: Internal Databasekey_statistics/4
: Internal Databasekeysort/2
: Comparing Termskill/2
: Systemlanguage (yap_flag/2 option)
: Misclast/2
: Listsleash/1
: Deb Predslength/2
: Comparing Termslength_queue/2
: Queueslibrary_directory/1
: Setting the Compilerline_count/2
: Streams and Filesline_position/2
: Streams and Fileslist_concat/2
: Listslist_join_queue/3
: Queueslist_jump_queue/3
: Queueslist_to_assoc/2
: Association Listslist_to_heap/2
: Heapslist_to_ord_set/2
: Ordered Setslist_to_queue/2
: Queueslist_to_rbtree/2
: Red-Black Treeslist_to_tree/2
: Treeslisting/0
: Looking at the Databaselisting/1
: Looking at the Databaseload_files/2
: Compilingload_foreign_library/1
: shlibload_foreign_library/2
: shliblocal_stack (statistics/2 option)
: Miscls/0
: OSmake/0
: Compilingmake_diagram/2
: Block Diagrammake_directory/2
: Systemmake_queue/1
: Queuesmap_assoc/2
: Association Listsmap_assoc/3
: Association Listsmap_tree/3
: Treesmapargs/3
: MapListmaplist/2
: Invoking Predicates on all Members of a Listmaplist/3
: Invoking Predicates on all Members of a Listmaplist/3
: MapListmaplist/4
: Invoking Predicates on all Members of a Listmaplist/4
: MapListmaplist/5
: MapListmapnodes/3
: MapListmatlab_cells/2
: MATLABmatlab_cells/3
: MATLABmatlab_eval_string/1
: MATLABmatlab_eval_string/2
: MATLABmatlab_get_variable/2
: MATLABmatlab_initialized_cells/4
: MATLABmatlab_item/3
: MATLABmatlab_item/4
: MATLABmatlab_matrix/4
: MATLABmatlab_on/0
: MATLABmatlab_sequence/3
: MATLABmatlab_set/4
: MATLABmatlab_vector/4
: MATLABmatlab_zeros/2
: MATLABmatlab_zeros/3
: MATLABmatlab_zeros/4
: MATLABmatrix_add/3
: matrixmatrix_agg_cols/2
: matrixmatrix_agg_lines/2
: matrixmatrix_arg_to_offset/3
: matrixmatrix_column/3
: matrixmatrix_dec/2
: matrixmatrix_dec/3
: matrixmatrix_dims/2
: matrixmatrix_expand/3
: matrixmatrix_get/3
: matrixmatrix_inc/2
: matrixmatrix_inc/3
: matrixmatrix_max/2
: matrixmatrix_maxarg/2
: matrixmatrix_min/2
: matrixmatrix_minarg/2
: matrixmatrix_ndims/2
: matrixmatrix_new/3
: matrixmatrix_new/4
: matrixmatrix_new_set/4
: matrixmatrix_offset_to_arg/3
: matrixmatrix_op/4
: matrixmatrix_op_to_cols/4
: matrixmatrix_op_to_lines/4
: matrixmatrix_reorder/3
: matrixmatrix_select/4
: matrixmatrix_set/3
: matrixmatrix_set_all/2
: matrixmatrix_shuffle/3
: matrixmatrix_size/2
: matrixmatrix_sum/2
: matrixmatrix_to_list/2
: matrixmatrix_type/2
: matrixmax_arity (yap_flag/2 option)
: Miscmax_assoc/3
: Association Listsmax_integer (yap_flag/2 option)
: Miscmax_list/2
: Listsmax_tagged_integer (yap_flag/2 option)
: Miscmax_threads (yap_flag/2 option)
: Miscmax_workers (yap_flag/2 option)
: Miscmember/2
: Listsmemberchk/2
: Listsmerge/3
: Ordered Setsmessage_hook/3
: Messagesmessage_queue_create/1
: Message Queuesmessage_queue_destroy/1
: Message Queuesmessage_to_string/2
: Messagesmeta_predicate/1 (directive)
: Meta-Predicates in Modulesmin_assoc/3
: Association Listsmin_integer (yap_flag/2 option)
: Miscmin_list/2
: Listsmin_of_heap/3
: Heapsmin_of_heap/5
: Heapsmktemp/2
: Systemmktime/2
: Systemmodule (prolog_load_context/2 option)
: Miscmodule/1
: Defining Modulesmodule/2 (directive)
: Defining Modulesmodule/3 (directive)
: Defining Modulesmodule_transparent/1 (directive)
: Meta-Predicates in Modulesmpi_barrier/0
: LAMmpi_bcast/2
: LAMmpi_bcast/3
: LAMmpi_comm_rank/1
: LAMmpi_comm_size/1
: LAMmpi_finalize/0
: LAMmpi_gc/0
: LAMmpi_init/0
: LAMmpi_irecv/3
: LAMmpi_isend/4
: LAMmpi_recv/3
: LAMmpi_send/3
: LAMmpi_test/2
: LAMmpi_test_recv/3
: LAMmpi_version/2
: LAMmpi_wait/2
: LAMmpi_wait_recv/3
: LAMmultifile/1 (directive)
: Setting the Compilermutex_create/1
: Thread Synchronisationmutex_destroy/1
: Thread Synchronisationmutex_lock/1
: Thread Synchronisationmutex_statistics/0
: Monitoring Threadsmutex_trylock/1
: Thread Synchronisationmutex_unlock/1
: Thread Synchronisationmutex_unlock_all/0
: Thread Synchronisationn_of_integer_keys_in_bb (yap_flag/2 option)
: Miscn_of_integer_keys_in_db (yap_flag/2 option)
: Miscname/2
: Predicates on Atomsnb_beam/1
: Non-Backtrackable Data Structuresnb_beam_add/3
: Non-Backtrackable Data Structuresnb_beam_close/1
: Non-Backtrackable Data Structuresnb_beam_del/3
: Non-Backtrackable Data Structuresnb_beam_empty/1
: Non-Backtrackable Data Structuresnb_beam_peek/3
: Non-Backtrackable Data Structuresnb_beam_size/2
: Non-Backtrackable Data Structuresnb_current/2
: SWI-Prolog Global Variablesnb_current/2
: Global Variablesnb_delete/1
: SWI-Prolog Global Variablesnb_delete/2
: Global Variablesnb_getval/2
: Global Variablesnb_getval/2
: SWI-Prolog Global Variablesnb_heap/1
: Non-Backtrackable Data Structuresnb_heap_add/3
: Non-Backtrackable Data Structuresnb_heap_close/1
: Non-Backtrackable Data Structuresnb_heap_del/3
: Non-Backtrackable Data Structuresnb_heap_empty/1
: Non-Backtrackable Data Structuresnb_heap_peek/3
: Non-Backtrackable Data Structuresnb_heap_size/2
: Non-Backtrackable Data Structuresnb_linkarg/3
: Global Variablesnb_linkval/2
: Global Variablesnb_queue/1
: Non-Backtrackable Data Structuresnb_queue_close/3
: Non-Backtrackable Data Structuresnb_queue_dequeue/2
: Non-Backtrackable Data Structuresnb_queue_empty/1
: Non-Backtrackable Data Structuresnb_queue_enqueue/2
: Non-Backtrackable Data Structuresnb_queue_peek/2
: Non-Backtrackable Data Structuresnb_queue_size/2
: Non-Backtrackable Data Structuresnb_set_shared_arg/3
: Global Variablesnb_set_shared_val/2
: Global Variablesnb_setarg/3
: Global Variablesnb_setval/2
: Global Variablesnb_setval/2
: SWI-Prolog Global Variablesneighbors/3
: UGraphsneighbours/3
: UGraphsnew_variables_in_term/3
: Termsnl/0
: I/O of Charactersnl/1
: I/O for Streamsno_source/0
: Setting the Compilerno_style_check/1
: Setting the Compilernodebug/0
: Deb Predsnofileerrors/0
: I/O Controlnogc/0
: Controlnonvar/1
: Testing Termsnospy/1
: Deb Predsnospyall/0
: Deb Predsnot/1
: Controlnotrace/0
: Deb Predsnth/3
: Listsnth/4
: Listsnth0/3
: Listsnth0/4
: Listsnth1/3
: Listsnth1/3
: SWI-Prolognth1/4
: Listsnth_clause/3
: Modifying the Databasenth_instance/3
: Internal Databasenth_instance/4
: Internal Databasenumber/1
: Testing Termsnumber_atom/2
: Predicates on Atomsnumber_chars/2
: Predicates on Atomsnumber_codes/2
: Predicates on Atomsnumber_to_chars/2
: String I/Onumber_to_chars/3
: String I/Onumbervars/3
: Testing Termsnumlist/3
: Listson_cleanup/1
: Cleanupon_signal/3
: OSonce/1
: Controlop/3
: Miscopen/3
: Streams and Filesopen/4
: Streams and Filesopen_chars_stream/2
: String I/Oopen_expands_filename (yap_flag/2 option)
: Miscopen_shared_object (yap_flag/2 option)
: Miscopen_shared_object/2
: Loading Objectsopen_shared_object/3
: Loading Objectsord_add_element/3
: Ordered Setsord_del_element/3
: Ordered Setsord_disjoint/2
: Ordered Setsord_insert/3
: Ordered Setsord_intersect/2
: Ordered Setsord_intersect/3
: Ordered Setsord_intersect/4
: Ordered Setsord_list_to_assoc/2
: Association Listsord_member/2
: Ordered Setsord_seteq/2
: Ordered Setsord_setproduct/3
: Ordered Setsord_subtract/3
: Ordered Setsord_symdiff/3
: Ordered Setsord_union/2
: Ordered Setsord_union/3
: Ordered Setsord_union/4
: Ordered Setsordsubset/2
: Ordered Setspartition/4
: MapListpartition/5
: MapListpath/1
: Setting the Compilerpeek_byte/1
: I/O of Characterspeek_byte/2
: I/O for Streamspeek_char/1
: I/O of Characterspeek_char/2
: I/O for Streamspeek_code/1
: I/O of Characterspeek_code/2
: I/O for Streamspermutation/2
: Listsphrase/2
: Grammarsphrase/3
: Grammarspid/1
: Systemplus/3
: Arithmeticpopen/3
: Systemportray_clause/1
: Looking at the Databaseportray_clause/2
: Looking at the Databasepredicate_property/2
: Looking at the Databasepredicate_statistics/4
: Looking at the Databasepredsort/3
: Comparing Termsprimitive/1
: Testing Termsprint/1
: I/O of Termsprint/2
: I/O for Streamsprint_message/2
: Messagesprint_message_lines/3
: Messagesprocess/2
: LineUtilitiesprofile_data/3
: Profilingprofiled_reset/0
: Profilingprofiling (yap_flag/2 option)
: Miscprofinit/0
: Profilingprofoff/0
: Profilingprofon/0
: Profilingprogram (statistics/2 option)
: Miscproject_attributes/2
: Displaying Attributesproject_attributes/2
: Projecting Attributesprolog_file_name/2
: Setting the Compilerprolog_flag/3
: Miscprolog_initialization/1
: Miscprolog_load_context/2
: Miscprolog_to_os_filename/2
: Setting the Compilerprompt/2
: Miscprompt_alternatives_on (yap_flag/2 option)
: Miscpublic/1 (directive)
: Setting the Compilerput/1
: I/O of Charactersput/2
: I/O for Streamsput_assoc/4
: Association Listsput_attr/3
: New Style Attribute Declarationsput_attrs/2
: New Style Attribute Declarationsput_atts/2
: Attribute Manipulationput_byte/1
: I/O of Charactersput_byte/2
: I/O for Streamsput_char/1
: I/O of Charactersput_char/2
: I/O for Streamsput_code/1
: I/O of Charactersput_code/2
: I/O for Streamsput_label/4
: Treesputenv/2
: OSpwd/0
: OSqueue_to_list/2
: Queuesrandom/1
: Randomrandom/3
: Randomrandseq/3
: Randomrandset/3
: Randomrannum/1
: Pseudo Randomranstart/0
: Pseudo Randomranstart/1
: Pseudo Randomranunif/2
: Pseudo Randomrational/1
: Testing Termsrb_apply/4
: Red-Black Treesrb_clone/3
: Red-Black Treesrb_del_max/4
: Red-Black Treesrb_del_min/4
: Red-Black Treesrb_delete/3
: Red-Black Treesrb_delete/4
: Red-Black Treesrb_empty/1
: Red-Black Treesrb_insert/4
: Red-Black Treesrb_keys/2
: Red-Black Treesrb_lookup/3
: Red-Black Treesrb_lookupall/3
: Red-Black Treesrb_map/3
: Red-Black Treesrb_max/3
: Red-Black Treesrb_min/3
: Red-Black Treesrb_new/1
: Red-Black Treesrb_next/4
: Red-Black Treesrb_partial_map/4
: Red-Black Treesrb_previous/4
: Red-Black Treesrb_size/2
: Red-Black Treesrb_update/4
: Red-Black Treesrb_visit/2
: Red-Black Treesreachable/3
: UGraphsread/1
: I/O of Termsread/2
: I/O for Streamsread_file_to_codes/3
: Read Utilitiesread_file_to_terms/3
: Read Utilitiesread_from_chars/2
: String I/Oread_line_to_codes/2
: Read Utilitiesread_line_to_codes/3
: Read Utilitiesread_stream_to_codes/3
: Read Utilitiesread_term/2
: I/O of Termsread_term/3
: I/O for Streamsreconsult/1
: Compilingrecorda/3
: Internal Databaserecorda_at/3
: Internal Databaserecordaifnot/3
: Internal Databaserecorded/3
: Internal Databaserecordz/3
: Internal Databaserecordz_at/3
: Internal Databaserecordzifnot/3
: Internal Databasereexport/1
: Re-Exporting Modulesreexport/2
: Re-Exporting Modulesregexp/3
: RegExpregexp/4
: RegExpremove_duplicates/2
: Listsremove_from_path/1
: Setting the Compilerrename/2
: OSrename_file/2
: Systemrepeat/0
: Controlreset_op_counters/0
: Low Level Profilingreset_static_array/1
: Arraysresize_static_array/3
: Arraysrestore/1
: Savingretract/1
: Modifying the Databaseretract/2
: Database Referencesretractall/1
: Modifying the Databasereverse/2
: Listsruntime (statistics/2 option)
: Miscsame_length/2
: Listssave/1
: Savingsave/2
: Savingsave_program/1
: Savingsave_program/2
: Savingscan_integer/3
: LineUtilitiesscan_natural/3
: LineUtilitiessearch_for/2
: LineUtilitiessee/1
: C-Prolog File Handlingseeing/1
: C-Prolog File Handlingseen/0
: C-Prolog File Handlingselect/3
: Listsselectchk/3
: Listsselectlist/3
: MapListserve_queue/3
: Queuesset_input/1
: Streams and Filesset_output/1
: Streams and Filesset_prolog_flag/2
: Miscset_stream_position/2
: Streams and Filesset_value/2
: Internal Databasesetarg/3n
: Term Modificationsetenv/2
: SWI-Prologsetof/3
: Setssetrand/1
: Randomsetup_call_catcher_cleanup/4
: Cleanupsetup_call_cleanup/3
: Cleanupsh/0
: OSshared_object_search_path (yap_flag/2 option)
: Miscshell/0
: Systemshell/1
: Systemshow_op_counters/1
: Low Level Profilingshow_ops_by_group/1
: Low Level Profilingshow_table/1
: Tablingshowprofres/0
: Profilingshowprofres/1
: Profilingsimple/1
: Testing Termssingle_var_warnings (yap_flag/2 option)
: Miscsingletons/1 (read_term/2 option)
: I/O of Termsskip/1
: I/O of Charactersskip/2
: I/O for Streamssleep/1
: Systemsocket/2
: Socketssocket/4
: Socketssocket_accept/2
: Socketssocket_accept/3
: Socketssocket_bind/2
: Socketssocket_buffering/4
: Socketssocket_close/1
: Socketssocket_connect/3
: Socketssocket_listen/2
: Socketssocket_select/5
: Socketssort/2
: Comparing Termssource/0
: Setting the Compilersource_file/1
: Miscsource_file/2
: Miscsource_location/2
: Miscsource_mode/2
: Setting the Compilersplay_access/5
: Splay Treessplay_delete/4
: Splay Treessplay_init/3
: Splay Treessplay_insert/4
: Splay Treessplay_join/3
: Splay Treessplay_split/5
: Splay Treessplit/2
: LineUtilitiessplit/3
: LineUtilitiesspy/1
: Deb Predsspy_write/2
: Deb Predssrandom/1
: Arithmeticstack_dump_on_error (yap_flag/2 option)
: Miscstack_shifts (statistics/2 option)
: Miscstart_low_level_trace/0
: Low Level Tracingstart_matlab/1
: MATLABstatic_array/3
: Arraysstatic_array_location/4
: Arraysstatic_array_properties/3
: Arraysstatic_array_to_term/3
: Arraysstatic_code (statistics/2 option)
: Miscstatistics/0
: Miscstatistics/2
: Miscstream_position/2
: Streams and Filesstream_position_data/3
: Streams and Filesstream_property/2
: Streams and Filesstream_select/3
: Streams and Filesstrict_iso (yap_flag/2 option)
: Miscstyle_check/1
: Setting the Compilersub_atom/5
: Predicates on Atomssublist/2
: Listssubsumes/2
: Termssubsumes_chk/2
: Termssubsumes_term/2
: Testing Termssubtract/3
: Listssucc/3
: Arithmeticsuffix/2
: Listssum_list/2
: Listssum_list/3
: Listssumargs/4
: MapListsumlist/2
: Listssumlist/4
: MapListsumnodes/4
: MapListsyntax_errors (yap_flag/2 option)
: Miscsyntax_errors/1 (read_term/2 option)
: I/O of Termssystem/0
: Systemsystem/1
: OSsystem/2
: Systemsystem_options (yap_flag/2 option)
: Miscsystem_predicate/2
: Looking at the Databasetab/1
: I/O of Characterstab/2
: I/O for Streamstable/1
: Tablingtable_statistics/1
: Tablingtabling_mode (yap_flag/2 option)
: Tablingtabling_mode/2
: Tablingtabling_statistics/0
: Tablingtell/1
: C-Prolog File Handlingtelling/1
: C-Prolog File Handlingterm_attvars/2
: New Style Attribute Declarationsterm_expansion/2
: Grammarsterm_hash/2
: Termsterm_hash/4
: Termsterm_position/1 (read_term/2 option)
: I/O of Termsterm_to_atom/2
: SWI-Prologterm_to_atom/2
: String I/Oterm_variables/2
: New Style Attribute Declarationsthread_at_exit/1
: Creating and Destroying Prolog Threadsthread_create/1
: Creating and Destroying Prolog Threadsthread_create/2
: Creating and Destroying Prolog Threadsthread_create/3
: Creating and Destroying Prolog Threadsthread_detach/1
: Creating and Destroying Prolog Threadsthread_exit/1
: Creating and Destroying Prolog Threadsthread_get_message/1
: Message Queuesthread_get_message/2
: Message Queuesthread_join/2
: Creating and Destroying Prolog Threadsthread_local/1 (directive)
: Threads and Dynamic Predicatesthread_peek_message/1
: Message Queuesthread_peek_message/2
: Message Queuesthread_property/2
: Monitoring Threadsthread_self/1
: Creating and Destroying Prolog Threadsthread_send_message/1
: Message Queuesthread_send_message/2
: Message Queuesthread_setconcurrency/2
: Creating and Destroying Prolog Threadsthread_signal/2
: Signalling Threadsthread_sleep/1
: Creating and Destroying Prolog Threadsthread_statistics/3
: Monitoring Threadsthread_yield/0
: Creating and Destroying Prolog Threadsthreads/0
: Monitoring Threadsthrow/1
: Controltime/1
: Misctime_file/2
: Streams and Filestime_out/3
: Timeouttmp_file/2
: Systemtmpnam/1
: Systemto_chars_modes (yap_flag/2 option)
: Misctold/0
: C-Prolog File Handlingtop_sort/2
: UGraphstop_sort/3
: UGraphstoplevel_hook (yap_flag/2 option)
: Misctoplevel_print_options (yap_flag/2 option)
: Misctrace/0
: Deb Predstrail (statistics/2 option)
: Misctransitive_closure/2
: UGraphstranspose/3
: UGraphstree_size/2
: Treestree_to_list/2
: Treestrie_check_entry/3
: Triestrie_close/1
: Triestrie_close_all/0
: Triestrie_get_entry/2
: Triestrie_load/2
: Triestrie_max_stats/4
: Triestrie_mode/1
: Triestrie_open/1
: Triestrie_print/1
: Triestrie_put_entry/3
: Triestrie_remove_entry/1
: Triestrie_remove_subtree/1
: Triestrie_save/2
: Triestrie_stats/4
: Triestrie_usage/4
: Triestrue/0
: Controlttyget/1
: C-Prolog to Terminalttyget0/1
: C-Prolog to Terminalttynl/0
: C-Prolog to Terminalttyput/1
: C-Prolog to Terminalttyskip/1
: C-Prolog to Terminalttytab/1
: C-Prolog to Terminaltypein_module (yap_flag/2 option)
: Miscugraph_to_dgraph/2
: DGraphsundgraph_add_edges/3
: UnDGraphsundgraph_add_vertices/3
: UnDGraphsundgraph_complement/2
: UnDGraphsundgraph_del_edges/3
: UnDGraphsundgraph_del_vertices/3
: UnDGraphsundgraph_edge/2
: UnDGraphsundgraph_edges/2
: UnDGraphsundgraph_neighbors/3
: UnDGraphsundgraph_neighbours/3
: UnDGraphsundgraph_new/1
: UnDGraphsundgraph_vertices/2
: UnDGraphsunhide/1
: Setting the Compilerunifiable/3
: Termsunify_with_occurs_check/2
: Testing Termsunix (yap_flag/2 option)
: Miscunix/1
: OSunknown (yap_flag/2 option)
: Miscunknown/2
: Undefined Proceduresunknown_predicate_handler/3
: Undefined Proceduresunload_foreign_library/1
: shlibunload_foreign_library/2
: shlibupdate_array/3
: Arraysupdate_mutable/2
: Term Modificationupdate_semantics (yap_flag/2 option)
: Miscuse_foreign_library/1
: shlibuse_foreign_library/2
: shlibuse_module/1
: Using Modulesuse_module/2
: Using Modulesuse_module/3
: Using Modulesuser_error (yap_flag/2 option)
: Miscuser_flags (yap_flag/2 option)
: Miscuser_input (yap_flag/2 option)
: Miscuser_output (yap_flag/2 option)
: Miscvar/1
: Testing Termsvariable_in_term/2
: Termsvariable_names/1 (read_term/2 option)
: I/O of Termsvariables/1 (read_term/2 option)
: I/O of Termsvariables_within_term/3
: Termsvariant/2
: Termsverbose (yap_flag/2 option)
: Miscverbose_load (yap_flag/2 option)
: Miscverify_attributes/3
: Attributed Unificationversion (yap_flag/2 option)
: Miscversion/0
: Miscversion/1
: Miscversion_data (yap_flag/2 option)
: Miscvertices/2
: UGraphsvertices_edges_to_ugraph/3
: UGraphswait/2
: Systemwalltime (statistics/2 option)
: Miscwhen/2
: Co-routiningwindoes (yap_flag/2 option)
: Miscwith_mutex/2
: Thread Synchronisationwith_output_to/2
: I/O of Termswith_output_to_chars/2
: String I/Owith_output_to_chars/3
: String I/Owith_output_to_chars/4
: String I/Oworking_directory/2
: Systemworking_directory/2
: SWI-Prologwrite/1
: I/O of Termswrite/2
: I/O for Streamswrite_canonical/1
: I/O for Streamswrite_canonical/2
: I/O for Streamswrite_depth/2
: I/O Controlwrite_depth/3
: I/O Controlwrite_strings (yap_flag/2 option)
: Miscwrite_term/2
: I/O of Termswrite_term/3
: I/O for Streamswrite_to_chars/2
: String I/Owrite_to_chars/3
: String I/Owriteln/1
: I/O of Termswriteq/1
: I/O of Termswriteq/2
: I/O for StreamsYAP_AddressFromSlot (C-Interface function)
: Calling YAP From CYAP_AGCHook (C-Interface function)
: Manipulating TermsYAP_AllocSpaceFromYAP (C-Interface function)
: Memory AllocationYAP_ArgOfTerm (C-Interface function)
: Manipulating TermsYAP_ArgsOfTerm (C-Interface function)
: Manipulating TermsYAP_ArgsToSlots (C-Interface function)
: Calling YAP From CYAP_ArityOfFunctor (C-Interface function)
: Manipulating TermsYAP_AsyncThrow (C-Interface function)
: Miscellaneous C-FunctionsYAP_AtomGetHold (C-Interface function)
: Manipulating TermsYAP_AtomName (C-Interface function)
: Manipulating TermsYAP_AtomNameLength (C-Interface function)
: Manipulating TermsYAP_AtomOfTerm (C-Interface function)
: Manipulating TermsYAP_AtomReleaseHold (C-Interface function)
: Manipulating TermsYAP_AtomToPred (C-Interface function)
: Calling YAP From CYAP_BigNumOfTerm (C-Interface function)
: Manipulating TermsYAP_BufferToAtomList (C-Interface function)
: Manipulating StringsYAP_BufferToDiffList (C-Interface function)
: Manipulating StringsYAP_BufferToString (C-Interface function)
: Manipulating StringsYAP_CallProlog (C-Interface function)
: Calling YAP From CYAP_ClearExceptions (C-Interface function)
: Calling YAP From CYAP_CloseAllOpenStreams (C-Interface function)
: Controlling StreamsYAP_CompileClause/1
: YAPLibraryYAP_ContinueGoal/0
: YAPLibraryYAP_CopyTerm/1
: YAPLibraryYAP_CurrentSlot (C-Interface function)
: Calling YAP From CYAP_cutfail (C-Interface function)
: Writing CYAP_cutsucceed (C-Interface function)
: Writing CYAP_EndConsult/0
: YAPLibraryYAP_EnterGoal (C-Interface function)
: Calling YAP From CYAP_Erase (C-Interface function)
: Utility FunctionsYAP_Error/1
: YAPLibraryYAP_ExactlyEqual (C-Interface function)
: Utility FunctionsYAP_Exit/1
: YAPLibraryYAP_FastInit/1
: YAPLibraryyap_flag/2
: MiscYAP_FloatOfTerm (C-Interface function)
: Manipulating TermsYAP_FlushAllStreams (C-Interface function)
: Controlling StreamsYAP_FreeSpaceFromYAP (C-Interface function)
: Memory AllocationYAP_FullLookupAtom (C-Interface function)
: Manipulating TermsYAP_FunctorOfTerm (C-Interface function)
: Manipulating TermsYAP_FunctorToPred (C-Interface function)
: Calling YAP From CYAP_GetValue/1
: YAPLibraryYAP_HaltRegisterHook (C-Interface function)
: Miscellaneous C-FunctionsYAP_HeadOfTerm (C-Interface function)
: Manipulating TermsYAP_Init/1
: YAPLibraryYAP_InitConsult/2
: YAPLibraryYAP_InitSlot (C-Interface function)
: Calling YAP From CYAP_IntOfTerm (C-Interface function)
: Manipulating TermsYAP_IsApplTerm (C-Interface function)
: Manipulating TermsYAP_IsAtomTerm (C-Interface function)
: Manipulating TermsYAP_IsBigNumTerm (C-Interface function)
: Manipulating TermsYAP_IsDBRefTerm (C-Interface function)
: Manipulating TermsYAP_IsFloatTerm (C-Interface function)
: Manipulating TermsYAP_IsIntTerm (C-Interface function)
: Manipulating TermsYAP_IsIsWideAtom (C-Interface function)
: Manipulating TermsYAP_IsNonVarTerm (C-Interface function)
: Manipulating TermsYAP_IsPairTerm (C-Interface function)
: Manipulating TermsYAP_IsVarTerm (C-Interface function)
: Manipulating TermsYAP_IsWideAtom (C-Interface function)
: Manipulating TermsYAP_LeaveGoal (C-Interface function)
: Calling YAP From CYAP_LookupAtom (C-Interface function)
: Manipulating TermsYAP_LookupWideAtom (C-Interface function)
: Manipulating TermsYAP_MkApplTerm (C-Interface function)
: Manipulating TermsYAP_MkAtomTerm (C-Interface function)
: Manipulating TermsYAP_MkBigNumTerm (C-Interface function)
: Manipulating TermsYAP_MkFloatTerm (C-Interface function)
: Manipulating TermsYAP_MkFunctor (C-Interface function)
: Manipulating TermsYAP_MkIntTerm (C-Interface function)
: Manipulating TermsYAP_MkNewApplTerm (C-Interface function)
: Manipulating TermsYAP_MkNewPairTerm (C-Interface function)
: Manipulating TermsYAP_MkPairTerm (C-Interface function)
: Manipulating TermsYAP_NameOfFunctor (C-Interface function)
: Manipulating TermsYAP_NBufferToAtomList (C-Interface function)
: Manipulating StringsYAP_NBufferToDiffList (C-Interface function)
: Manipulating StringsYAP_NBufferToString (C-Interface function)
: Manipulating StringsYAP_NewSlots (C-Interface function)
: Calling YAP From CYAP_NWideBufferToAtomList (C-Interface function)
: Manipulating StringsYAP_NWideBufferToDiffList (C-Interface function)
: Manipulating StringsYAP_NWideBufferToString (C-Interface function)
: Manipulating StringsYAP_OpenStream (C-Interface function)
: Controlling StreamsYAP_PRESERVE_DATA (C-Interface function)
: Writing CYAP_PRESERVED_DATA (C-Interface function)
: Writing CYAP_PRESERVED_DATA_CUT (C-Interface function)
: Writing CYAP_PutInSlot (C-Interface function)
: Calling YAP From CYAP_PutValue/2
: YAPLibraryYAP_Read/1
: YAPLibraryYAP_ReadBuffer (C-Interface function)
: Manipulating StringsYAP_Record (C-Interface function)
: Utility FunctionsYAP_Recorded (C-Interface function)
: Utility FunctionsYAP_RecoverSlots (C-Interface function)
: Calling YAP From CYAP_Reset (C-Interface function)
: Calling YAP From CYAP_RestartGoal (C-Interface function)
: Calling YAP From CYAP_RetryGoal (C-Interface function)
: Calling YAP From CYAP_RunGoal (C-Interface function)
: Calling YAP From CYAP_SetYAPFlag (C-Interface function)
: Miscellaneous C-FunctionsYAP_ShutdownGoal (C-Interface function)
: Calling YAP From CYAP_SlotsToArgs (C-Interface function)
: Calling YAP From CYAP_StreamToFileNo (C-Interface function)
: Controlling StreamsYAP_StringToBuffer (C-Interface function)
: Manipulating StringsYAP_TailOfTerm (C-Interface function)
: Manipulating TermsYAP_Throw (C-Interface function)
: Miscellaneous C-FunctionsYAP_Unify (C-Interface function)
: Unifying TermsYAP_UserBackCPredicate (C-Interface function, deprecated)
: Writing CYAP_UserBackCutCPredicate (C-Interface function)
: Writing CYAP_UserCPredicate (C-Interface function)
: Writing CYAP_WideAtomName (C-Interface function)
: Manipulating TermsYAP_WideBufferToAtomList (C-Interface function)
: Manipulating StringsYAP_WideBufferToDiffList (C-Interface function)
: Manipulating StringsYAP_WideBufferToString (C-Interface function)
: Manipulating StringsYAP_Write/3
: YAPLibraryYAP_WriteBuffer/4
: YAPLibraryYAPBINDIR
: Running YAP InteractivelyYAPLIBDIR
: Running YAP InteractivelyYAPSHAREDIR
: Running YAP InteractivelyC
C
C
back to Prolog