| [Top] | [Contents] | [Index] | [ ? ] |
This file documents the YAP Prolog System version 4.3.22, 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 the CLP(Q,R) manual as distributed by the Austrian Research Institute for Artificial Intelligence (OFAI). Permission on this document follows the following license:
Copyright © 1992,1993,1994,1995 OFAI Austrian Research Institute for Artificial Intelligence (OFAI) Schottengasse 3 A-1010 Vienna, Austria
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted qto copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the OFAI.
This file contains a chapter on CHR. This package is distributed under license from LMU (Ludwig-Maximilians-University), Munich, Germany:
Permission is granted to copy and distribute modified versions of this chapter under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this chapter into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by LMU.
Copyright © 1996-98 LMU (Ludwig-Maximilians-University)
Munich, Germany
Introduction 1. Installing YAP Installation 2. Running YAP 3. Syntax The syntax of YAP 4. Loading Programs Loading Prolog programs 5. The Module System Using Modules in YAP 6. Built-In Predicates 7. Library Predicates 8. Extensions Extensions to Standard YAP 9. Rational Trees Working with Rational Trees 10. Coroutining Changing the Execution of Goals 11. Attributed Variables Using attributed Variables 12. CLP(Q,R) Manual The CLP(Q,R) System 13. Constraint Handling Rules The CHR System 14. Logtalk The Logtalk Object-Oriented System 15. Parallelism Running in Or-Parallel 16. Tabling Storing Intermediate Solutions of programs 18. Profiling the Abstract Machine Profiling Abstract Machine Instructions 17. Tracing at Low Level Tracing at Abstract Machine Level 19. Debugging Using the Debugger 20. Indexing Efficiency Considerations 21. C Language interface to YAP Interfacing predicates written in C 22. Using YAP as a Library Using YAP as a library in other programs 23. Compatibility with Other Prolog systems Compatibility with other Prolog systems Predicate Index An item for each predicate Concept Index An item for each concept
Built In Predicates
6.1 Control Predicates Controlling the execution of Prolog programs 6.2 Handling Undefined Procedures Handling calls to Undefined Procedures 6.3 Predicates on terms Predicates on Terms 6.4 Comparing Terms Comparison of Terms 6.5 Arithmetic Arithmetic in YAP 6.6 I/O Predicates Input/Output with YAP 6.7 Using the Clausal Data Base Modifying Prolog's Database 6.10 Collecting Solutions to a Goal Finding All Possible Solutions 6.11 Grammar Rules 6.16 Predicate Information 6.12 Access to Operating System Functionality 6.13 Term Modification Updating Prolog Terms 6.14 Profiling Prolog Programs Profiling Prolog Execution 6.15 Arrays Supporting Global and Local Arrays 6.16 Predicate Information Information on Predicates 6.17 Miscellaneous Miscellaneous Predicates
Subnodes of Running
2.1 Running Yap Interactively Interacting with Yap 2.2 Running Prolog Files Running Prolog files as scripts
Subnodes of Syntax
3.1 Syntax of Terms 3.2 Prolog Tokens Syntax of Prolog tokens
Subnodes of Tokens
3.2.1 Numbers Integer and Floating-Point Numbers 3.2.2 Character Strings Sequences of Characters 3.2.3 Atoms Atomic Constants 3.2.4 Variables Logical Variables 3.2.5 Punctuation Tokens Tokens that separate other tokens 3.2.6 Layout Comments and Other Layout Rules
Subnodes of Numbers
3.2.1.1 Integers How Integers are read and represented 3.2.1.2 Floating-point Numbers Floating Point Numbers
Subnodes of Loading Programs
4.1 Program loading and updating Program Loading and Updating 4.2 Changing the Compiler's Behaviour Changing the compiler's parameters 4.3 Saving and Loading Prolog States Saving and Restoring Programs
Subnodes of Modules
5.1 Module Concepts The Key Ideas in Modules 5.2 Defining a New Module How To Define a New Module 5.3 Using Modules How to Use a Module 5.4 Meta-Predicates in Modules How to Handle New Meta-Predicates
Subnodes of Input/Output
6.6.1 Handling Streams and Files 6.6.2 Handling Streams and Files C-Prolog Compatible File Handling 6.6.3 Handling Input/Output of Terms Input/Output of terms 6.6.4 Handling Input/Output of Characters Input/Output of Characters 6.6.5 Input/Output Predicates applied to Streams Input/Output using Streams 6.6.6 Compatible C-Prolog predicates for Terminal I/O C-Prolog compatible Character I/O to terminal 6.6.7 Controlling Input/Output Controlling your Input/Output 6.6.8 Using Sockets From Yap Using Sockets from YAP
Subnodes of Database
6.7.1 Modification of the Data Base Asserting and Retracting 6.7.2 Looking at the Data Base Finding out what is in the Data Base 6.7.3 Using Data Base References 6.8 Internal Data Base YAP's Internal Database 6.9 The Blackboard Storing and Fetching Terms in the BlackBoard
Subnodes of Library
7.1 Apply Macros Apply a Predicate to a list or to sub-terms. 7.2 Association Lists Binary Tree Implementation of Association Lists. 7.3 AVL Trees Predicates to add and lookup balanced binary trees. 7.4 Heaps Labelled binary tree where the key of each node is less than or equal to the keys of its children. 7.5 List Manipulation 7.6 Ordered Sets Ordered Set Manipulation 7.7 Pseudo Random Number Integer Generator Pseudo Random Numbers 7.8 Queues Queue Manipulation 7.9 Random Number Generator Random Numbers 7.10 Regular Expressions Regular Expression Manipulation 7.11 Splay Trees 7.12 Reading From and Writing To Strings Writing To and Reading From Strings 7.13 Calling The Operating System from YAP System Utilities 7.14 Utilities On Terms Utilities on Terms 7.15 Calls With Timeout Call With Timeout 7.16 Updatable Binary Trees 7.17 Unweighted Graphs
Subnodes of Debugging
19.1 Debugging Predicates 19.2 Interacting with the debugger
Subnodes of Compatibility
23.1 Compatibility with the C-Prolog interpreter 23.2 Compatibility with the Quintus and SICStus Prolog systems 23.3 Compatibility with the ISO Prolog standard
Subnodes of Attributes
11.1 Attribute Declarations Declaring New Attributes 11.2 Attribute Manipulation Setting and Reading Attributes 11.3 Attributed Unification Tuning the Unification Algorithm 11.4 Displaying Attributes Displaying Attributes in User-Readable Form 11.5 Projecting Attributes Obtaining the Attributes of Interest 11.6 Attribute Examples Two Simple Examples of how to use Attributes.
Subnodes of CLP(Q,R)
Subnodes of CHR
Copyright 13.1 Introduction 13.2 Introductory Examples 13.3 CHR Library 13.4 Debugging CHR Programs 13.5 Programming Hints 13.6 Constraint Handlers 13.7 Backward Compatibility
Subnodes of C-Interface
21.1 Terms Primitives available to the C programmer 21.2 Unification How to Unify Two Prolog Terms 21.3 Strings From character arrays to Lists of codes and back 21.4 Memory Allocation Stealing Memory From Yap 21.5 Controlling Yap Streams from CControl How Yap sees Streams 21.6 From Cback to PrologFrom C to Yap to C to Yap 21.7 Writing predicates in C Writing Predicates in C 21.8 Loading Object Files 21.9 Saving and Restoring 21.10 Changes to the C-Interface in Yap4 Changes in Foreign Predicates Interface
Subnodes of C-Prolog
C-Prolog
23.1.1 Major Differences between YAP and C-Prolog. 23.1.2 Yap predicates fully compatible with C-Prolog Yap predicates fully compatible with
23.1.3 Yap predicates not strictly compatible with C-Prolog Yap predicates not strictly as C-Prolog 23.1.4 Yap predicates not available in C-Prolog 23.1.5 Yap predicates not available in C-Prolog C-Prolog predicates not available in YAP
Subnodes of SICStus Prolog
SICStus Prolog
23.2.1 Major Differences between YAP and SICStus Prolog. 23.2.2 Yap predicates fully compatible with SICStus Prolog Yap predicates fully compatible with
SICStus Prolog
23.2.3 Yap predicates not strictly compatible with SICStus Prolog Yap predicates not strictly as
23.2.4 Yap predicates not available in SICStus Prolog
Tables
A. Summary of Yap Predefined Operators Predefined operators
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This document provides User information on version 4.3.22 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 yappers@ncc.up.pt. To subscribe to the mailing list, send a request to majordomo@ncc.up.pt with body "subscribe yappers".
Online 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'{i}tor Santos Costa, Lu'{i}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 authorisation to include these packages.
The packages are, in alphabetical order:
Permission is granted to copy and distribute modified versions of this chapter under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this chapter into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by LMU.
Copyright © 1996-98 LMU (Ludwig-Maximilians-University)
Munich, Germany
Copyright © 1992,1993,1994,1995 OFAI Austrian Research Institute for Artificial Intelligence (OFAI) Schottengasse 3 A-1010 Vienna, Austria
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted qto copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the OFAI.
Copyright © 1998-2001 Paulo Moura
http://www.swi-prolog.org
for more information on SWI-Prolog and for a detailed description of its foreign interface.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
1.1 Tuning the Functionality of YAP Tuning the Functionality of YAP Machine 1.2 Tuning YAP for a Particular Machine and Compiler
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 coroutining and/or CLP
you need to do
../configure --enable-coroutining ...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
subsdirectory 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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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-tabling={local,batched} allows one of the two
forms of tabling. 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-gmp[=DIR] give a path to where one can find the
GMP library if not installed in the default path.
Next follow machine dependent details:
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
1.3 Tuning YAP for GCC.Using the GNUCC ncompiler 1.3.1 Compiling Under Visual C++ Using Microsoft's Visual C++ environment 1.3.2 Compiling Under SGI's cc Compiling Under SGI's cc
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 architecural 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 recognise different processors within the same instruction set, eg, 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 --... |
GCC, compiling with
-g seems to result in broken code.
WIN32: The cygwin environment is our suggested approach. The
http://sourceware.cygnus.com
and mirrors. Yap should compile under cygwin 20.1 but we suggest using the newer 1.1.1 or recent, which has a more complete implementation of the WIN32 API and uses GCC2.95.2 instead of egcs. The compilation steps under the cygwin shell are as follows:
mkdir cyg
$YAPSRC/configure --enable-coroutining \\
--enable-max-performance
make
make install
|
By default, Yap will use the --enable-cygwin=no 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
/PROGRA~1/Yap in the standard Makefile. This string will usually
be expanded into c:\Program Files\Yap by Windows.
The cygwin environment does not provide gm. You can fecth 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-coroutining \\
--enable-max-performance \\
--enable-cygwin=yes
make
make install
|
cygwin1.dll in its path.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
preprocessor's variable YAPDLL_EXPORTS to match your project names
in the files c_interface.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). ^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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 --... |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
2.1 Running Yap Interactively Interacting with Yap 2.2 Running Prolog Files Running Prolog files as scripts
We next describe how to invoke Yap in Unix systems.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 n
-h n
-t n
-l YAP_FILE
-L YAP_FILE
-b BOOT_FILE
-c IP_HOST port
filename
--
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' from the current directory or from the YAP library.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
YAP can also be used to run Prolog files as scripts, at least in Unix-like environments. A simple example is shown next:
#!/usr/local/bin/yap -L
#
# Hello World script file using Yap
#
:- 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.
By default, arguments to a script are considered 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 |
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 builtin. Hence, running
./dump_args test |
test on the standard output.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
3.1 Syntax of Terms Syntax of terms 3.2 Prolog Tokens Syntax of Prolog tokens
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
|
Notes:
|
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Prolog tokens are grouped into the following categories:
3.2.1 Numbers Integer and Floating-Point Numbers 3.2.2 Character Strings Sequences of Characters 3.2.3 Atoms Atomic Constants 3.2.4 Variables Logical Variables 3.2.5 Punctuation Tokens Tokens that separate other tokens 3.2.6 Layout Comments and Other Layout Rules
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Numbers can be further subdivided into integer and floating-point numbers.
3.2.1.1 Integers How Integers are read and represented 3.2.1.2 Floating-point Numbers Floating Point Numbers
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Integer numbers are described by the following regular expression:
|
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
|
Numbers of the form 0'a are used to represent character
constants. So, the following tokens denote the same integer:
|
YAP (version 4.3.22) 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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Floating-point numbers are described by:
|
where <dot> denotes the decimal-point character '.', <exponent-marker> denotes one of 'e' or 'E', and <sign> denotes one of '+' or '-'.
Examples:
|
Floating-point numbers are represented as a double in the target machine. This is usually a 64-bit number.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 '\'
|
string_character in any character except the double quote
and escape characters.
Examples:
|
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 Yap4.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:
|
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 origional versions of YAP up to 4.2.0. Escape sequences can be disable by using:
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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:
|
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Variables are described by:
<variable-starter><variable-character>+ |
<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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Punctuation tokens consist of one of the following characters:
|
These characters are used to group terms.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Loading Programs
4.1 Program loading and updating Program Loading and Updating 4.2 Changing the Compiler's Behaviour Changing the compiler's parameters 4.3 Saving and Loading Prolog States Saving and Restoring Programs
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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]. |
file1 file4 and reconsult file2 and
file3.
compile(+F)
reconsult/1.
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.
include(+F) [ISO]
include directive includes the text files or sequence of text
files specified by F into the file being currently consulted.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
|
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]
Declare that the arguments are discontiguous procedures, that is, clauses for discontigous procedures may be separated by clauses from other procedures.
initialization(+G) [ISO]
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)
public P [ISO]
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 an 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 both a way to access predicates private to a module and that 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: only meta-calls that cross module boundaries are slowed down by the presence of modules.
5.1 Module Concepts The Key Ideas in Modules 5.2 Defining a New Module How To Define a New Module 5.3 Using Modules How to Use a Module 5.4 Meta-Predicates in Modules How to Handle New Meta-Predicates
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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). |
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 into, say:
nasa:launch(apollo,13). |
launch(apollo,13) as if the current source
module was nasa.
Note that this rule breaks encapsulation and should be used with care.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 predicates consult/1, reconsult/1,
ensure_loaded/1 or use_module/2. The non-public predicates
of a module file are not visible by other files; they can, however, be
accessed if the module name is prefixed to the file name through the
:/2 operator.
The built-in module/1 sets the current source module:
module(+M,+L, +Options)
module/2, this predicate defines the file where it
appears 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)
Module:File, when
loading the file.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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:
:- module(example,[a/1]). ... a(G) :- call(G) ... |
example.
On the other hand, when executing call/1 the system only knows
where call/1 was defined, that is, it only knows of
primitives. A similar problem arises for assert/1 and
friends.
The meta_call/1 declaration informs the system that some
arguments of a procedure are goals, clauses or clauses heads, and that
these arguments must be expanded to receive the current source module:
meta_predicate G1,....,Gn
call/1 and setof/3 would be of the form:
:- meta_predicate call(:), setof(?,:,?). |
If the argument is : or an integer, the argument is a call and
must be expanded. Otherwise, the argument should not be expanded. Note
that the system already includes declarations for all built-ins.
In the previous example, the only argument to call/1 must be
expanded, resulting in the following code:
:- module(example,[a/1]). ... a(G) :- call(example:G) ... |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Builtins, Debugging, Syntax, Top
6.1 Control Predicates Controlling the Execution of Prolog Programs 6.2 Handling Undefined Procedures Handling calls to Undefined Procedures 6.3 Predicates on terms Predicates on Terms 6.4 Comparing Terms Comparison of Terms 6.5 Arithmetic Arithmetic in Yap 6.6 I/O Predicates Input/Output with Yap 6.7 Using the Clausal Data Base Modifying Prolog's Database 6.10 Collecting Solutions to a Goal Finding All Possible Solutions 6.11 Grammar Rules 6.16 Predicate Information 6.12 Access to Operating System Functionality 6.13 Term Modification Updating Prolog Terms 6.14 Profiling Prolog Programs Profiling Prolog Execution 6.15 Arrays Supporting Global and Local Arrays 6.16 Predicate Information Information on Predicates 6.17 Miscellaneous Miscellaneous Predicates
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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). |
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. \+(_). |
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. |
(P -> Q; R) :- P, !, Q. (P -> Q; R) :- 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. |
(->)/2 does not affect the scope of cuts in its
arguments.
repeat [ISO]
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, !. |
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) [IS0]
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_with_args(+Name,...,?Ai,...)
+P
call(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. |
a(X) :- call(X). |
if(?G,?H,?I) [IS0]
The builtin 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) [IS0]
once(G) :- call(G), !. |
Note that cuts inside once/1 can only cut the other goals inside
once/1.
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>) ] |
halt [ISO]
halt/0 returns the exit code 0.
halt(+ I) [ISO]
catch(+Goal,+Exception,+Action) [IS0]
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.
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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 through three different ways:
yap_flag/2 or
set_prolog_flag/2 built-ins. This solution generalises 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'), fail.
|
unknown(U,undefined(X)). |
Undefined predicate: user:xyz(A1,A2) |
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.
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
var(T) [ISO]
atom(T) [ISO]
atomic(T) [ISO]
compound(T) [ISO]
db_reference(T)
float(T) [ISO]
integer(T) [ISO]
nonvar(T) [ISO]
var(T).
number(T) [ISO]
T is an integer or a float.
primitive(T)
simple(T)
callable(T)
name(A,L)
name(yap,L). |
L = [121,97,112]. |
name(3,L). |
L = [51]. |
atom_chars(?A,?L) [ISO]
The ISO-Prolog standard dictates that atom_chars/2 should unify
the second argument with a list of one-char atoms, and not the character
codes. For compatibility with previous versions of YAP, and
with other Prolog implementations, YAP unifies the second
argument with the character codes, as in atom_codes/2. Use the
set_prolog_flag(to_chars_mode,iso) to obtain ISO standard
compatibility.
atom_codes(?A,?L) [ISO]
atom_concat(+As,?A)
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)
The predicate holds when at least one of the arguments is ground (otherwise, an error message will be displayed). The argument I must be unifiable with a number, and the argument L with the list of the ASCII codes for the characters of the external representation of I.
The ISO-Prolog standard dictates that number_chars/2 should unify
the second argument with a list of one-char atoms, and not the character
codes. For compatibility with previous versions of YAP, and
with other Prolog implementations, YAP unifies the second
argument with the character codes, as in number_codes/2. Use the
set_prolog_flag(to_chars_mode,iso) to obtain ISO standard
compatibility.
number_codes(?A,?L) [ISO]
number_atom(?I,?L)
The predicate holds when at least one of the arguments is ground (otherwise, an error message will be displayed). The argument I must be unifiable with a number, and the argument L must be unifiable with an atom representing the number.
char_code(?A,?I) [ISO]
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
substrings of A.
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)
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.
T =.. L [ISO]
X = Y [ISO]
X \= Y [ISO]
term_variables(?T,+L)
term_hash(+T,+Depth,+Max,-O)
term_hash(+T,-O)
term_hash/4 such that Depth is bound
to -1 and Max is bound to a large platform-indepent integer.
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)). |
A = b and Z = f(B). On the
other hand:
unify_with_occurs_check(a(X,b,Z),a(X,A,f(Z)). |
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]
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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;
X == 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. |
?- X = Y, X == Y. |
?- X == 2. |
?- X = 2, X == 2. |
X \== Y [ISO]
X @< Y [ISO]
X @=< Y [ISO]
X @> Y [ISO]
X @>= Y [ISO]
sort(+L,-S)
==) elements.
keysort(+L,S)
Key-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). |
S = [1-b,1-a,1-b,2-c,3-a] |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
+X
-X [ISO]
X+Y [ISO]
X-Y [ISO]
X*Y [ISO]
X/Y [ISO]
X//Y [ISO]
X mod Y [ISO]
X rem Y
mod.
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]
atan2(X)
sinh(X)
cosh(X)
tanh(X)
asinh(X)
acosh(X)
atanh(X)
integer(X) [ISO]
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)
max(X,Y)
min(X,Y)
X ^ Y
exp(X,Y)
X ** Y [ISO]
X /\ Y [ISO]
X \/ Y [ISO]
X # Y [ISO]
X << Y
X >> Y [ISO]
\ X [ISO]
gcd(X,Y)
msb(X)
[X]
X is Y*10+C-"0" |
X is Y*10+C-[48]. |
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
inf
iso
language mode.
nan
iso
language mode.
cputime
heapused
local
global
random
The primitive YAP predicates involving arithmetic expressions are:
X is +Y [2]
X is 2+3*4 |
X = 14.
+X < +Y [ISO]
+X =< +Y [ISO]
+X > +Y [ISO]
+X >= +Y [ISO]
+X =:= +Y [ISO]
+X =\= +Y [ISO]
srandom(+X)
Notes:
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
6.6.1 Handling Streams and Files 6.6.2 Handling Streams and Files C-Prolog Compatible File Handling 6.6.3 Handling Input/Output of Terms Input/Output of terms 6.6.4 Handling Input/Output of Characters Input/Output of Characters 6.6.5 Input/Output Predicates applied to Streams Input/Output using Streams 6.6.6 Compatible C-Prolog predicates for Terminal I/O C-Prolog compatible Character I/O to terminal 6.6.7 Controlling Input/Output Controlling your Input/Output 6.6.8 Using Sockets From Yap Using Sockets from Yap
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
text stream (default), or a
binary stream.
reposition(+Bool)
true), or
not (false). By default, YAP enables repositioning for all
files, except terminal files and sockets.
eof_action(+Action)
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)
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
close(+S) [ISO]
user_input,
user_output, and user_error can never be closed.
By default, give a file name, close/1 will also try to close a
corresponding open stream. This feature is not available in ISO or
SICStus languages mode and is deprecated.
close(+S,+O) [ISO]
The only valid options are force(true) and force(false).
YAP currently ignores these options.
absolute_file_name(+Name,-FullPath)
user if the file
name is user.
current_stream(F,M,S)
flush_output [ISO]
flush_output(+S) [ISO]
set_input(+S)
read/1
and get/1 will start using stream S.
set_output(+S)
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]
Obtain the properties for the open streams. If the first argument is
unbound, the procedure will backtrack through all open
streams. Otherwise, the first argument must be a stream term (you may
use current_stream to obtain a current stream given a file name).
The following properties are recognised:
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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]
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]
display(+T)
write_canonical(+T) [ISO]
write_term(+T, +Opts) [ISO]
quoted(+Bool)
true, quote atoms if this would be necessary for the atom to
be recognised as an atom by YAP's parser. The default value is
false.
ignore_ops(+Bool)
true, ignore operator declarations when writing the term. The
default value is false.
numbervars(+Bool)
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.
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.
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
|
'~ND'
'~Nd', except that ',' is 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'
writeq/1:
?- format("Good night ~w",'Hello'+[1,2]).
Good night Hello+[1,2]
|
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:
|
Note that we reserve 16 characters for the column.
The following example shows how to do right-alignment:
|
The ~t escape sequence forces filling before Hello.
We next show how to do centering:
|
The two ~t escape sequence force filling both before and after
Hello. Space is then evenly divided bewteen the right and the
left sides.
format(+S,+T,+L)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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]
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
read(+S,-T) [ISO]
read_term(+S,-T,+Options) [ISO]
read_term/2.
write(+S,T) [ISO]
write_canonical(+S,+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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
write/1 or write/2. The default value for both arguments is 0,
meaning unlimited depth and length.
?- write_depth(3,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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 builtins 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)
Call socket/4 with TYPE bound to 'SOCK_STREAM' and
PROTOCOL bound to 0.
socket_close(+SOCKET)
Close socket SOCKET. Note that sockets used in
socket_connet (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)
Interface to system call 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)
Interface to system call 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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
6.7.1 Modification of the Data Base Asserting and Retracting 6.7.2 Looking at the Data Base Finding out what is in the Data Base 6.7.3 Using Data Base References 6.8 Internal Data Base Yap's Internal Database 6.9 The Blackboard Storing and Fetching Terms in the BlackBoard
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
These predicates can be used either for static or for dynamic predicates:
assert(+C)
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, as long as the predicate is not in use. 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 predicate can be used for dynamic predicates and for static predicates, but only 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 the dynamic procedures.
The following predicate can only be used for dynamic predicates:
retract(+C) [ISO]
on. For more information on
source/0 (see section 4.2 Changing the Compiler's Behaviour).
retractall(+G)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
built_in
dynamic
static
meta_predicate(M)
multifile
imported_from(Mod)
exported
public
source
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 section 6.7.1 Modification of the Data Base) 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)
clause(+H,B,-R)
clause(H,B) but R is unified with the
reference to the clause in the database.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
recorda(+K,T,-R)
recordz(+K,T,-R)
recordaifnot(+K,T,-R)
recordzifnot(+K,T,-R)
recorded(+K,T,R)
erase(+R)
erase just fails.
erased(+R)
instance(+R,-T)
C :- true. When
R is not a reference to an existing clause or a recorded term,
this goal fails.
eraseall(+R)
eraseall just fails.
current_key(A,P)
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).
|
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). |
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,_). |
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
postprocess 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). |
findall(X,a(X,Y),L). |
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 eliminating
repeated elements. Thus, assuming the same clauses as in the above
example, the reply to the query
all(X,a(X,Y),L). |
X = _32 Y = _33 L = [2,1]; no |
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). |
X = _32 Y = 1 L = [1,2]; X = _32 Y = 2 L = [2]; no |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 |
Items can be:
Grammar related built-in predicates:
expand_term(T,-X)
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.
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)
L-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).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following built-in predicates allow access to underlying Operating System functionality:
cd(+D)
environ(?E,-S)
getcwd(-D)
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
cancelled.
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',[])).
|
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, _)).
|
The procedure has three arguments: the Time 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 maniputated through on_signal/3.
Their POSIX names, YAP names and default behaviour 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.
SIGHUP (Hangup)
SIGUSR1 and SIGUSR2 (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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
set_mutable(?D,+M)
update_mutable(+D,+M)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Predicates compiled with YAP's flag profiling set to
on, keep information on the number of times the predicate was
called. This information can be used to detect what are the most
commonly called predicates in the program.
The YAP profiling sub-system is currently under-development. Functionality for this sub-system will increase with newer implementation.
Notes:
list_profile :-
% get number of calls for each profiled procedure
findall(D-P,profile_data(P,calls,D),LP),
% sort them
sort(LP,SLP),
% output so that the most often called
% predicates will come last:
write_profile_data(SLP).
write_profile_data([]).
write_profile_data([D-P|SLP]) :-
% swap the two calls if you want the most often
% called predicates first.
format('~w: ~w~n', [P,D]),
write_profile_data(SLP).
|
These are the current predicates to access and clear profiling data:
profile_data(?Na/Ar, ?Paramater, -Data)
calls
retries
profile_reset
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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). |
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]. |
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)
mmapped_array(+Name, +Size, +Type, +File)
static_array/3, but the array is memory mapped to file
File. This means that the array is initialised 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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Built-ins that return information on the current predicates and modules:
current_module(M)
current_module(M,F)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
statistics/0
?- statistics.
Heap space : 2441216
Heap in use: 820220, max. used: 1623516
Trail space : 131068
Trail in use: 16, max. used: 13048
Stack space : 1523712
Global in use: 88, max. used: 658700
Local in use: 276, max. used: 515336
90 msec. for 5 heap overflows.
90 msec. for 3 stack overflows.
0 msec. for 0 trail overflows.
800 msec. for 3 garbage collections which
collected 208348 bytes.
Runtime : 23.07 sec.
|
statistics(?Param,-Info)
cputime
[Time since Boot,Time From Last Call to Cputime]
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).
trail
[Trail Used,Trail Free]
walltime
[Time since Boot,Time From Last Call to Runtime]
yap_flag(?Param,?Value)
argv
--.
bounded [ISO]
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.
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 behaviour. The default value is codes.
fast
on allow fast machine code, if off (default) disable it. Only
available in experimental implementations.
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.
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 multiprecision
library. If bounded is false, requestes for max_integer
will fail.
min_integer [ISO]
GMP multiprecision library. If
bounded is false, requestes for min_integer will fail.
n_of_integer_keys_in_bb
n_of_integer_keys_in_db
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.
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.
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 not guarantee that prolograms 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.
syntax_errors
read/1,
read/2, or read_term/3:
dec10
fail
error
quiet
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(G)
true if none is
presented. Only the first solution is considered and the goal is not
backtracked into.
typein_module
unknown [ISO]
unknown/2 built-in.
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
?-
|
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_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.
version
write_strings
on if enables or off if disabled. The default value for
this flag is off.
current_prolog_flag(?Flag,-Value) [ISO]
Obtain the value for a YAP Prolog flag. Equivalent to calling
yap_flag/2 with the second argument unbound, and unifying the
returned second argument with Value.
prolog_flag(?Flag,-OldValue,+NewValue)
Obtain the value for a YAP Prolog flag and then set it to a new
value. Equivalent to first calling 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]
Set the value for YAP Prolog flag Flag. Equivalent to
calling yap_flag/2 with both arguments bound.
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 posfix 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
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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, Builtins, Top
7.1 Apply Macros Apply a Predicate to a list or to sub-terms. 7.2 Association Lists Binary Tree Implementation of Association Lists. 7.3 AVL Trees Predicates to add and lookup balanced binary trees. 7.4 Heaps Labelled binary tree where the key of each node is less than or equal to the keys of its children. 7.5 List Manipulation 7.6 Ordered Sets Ordered Set Manipulation 7.7 Pseudo Random Number Integer Generator Pseudo Random Numbers 7.8 Queues Queue Manipulation 7.9 Random Number Generator Random Numbers 7.10 Regular Expressions Regular Expression Manipulation 7.11 Splay Trees 7.12 Reading From and Writing To Strings Writing To and Reading From Strings 7.13 Calling The Operating System from YAP System Utilities 7.14 Utilities On Terms Utilities on Terms 7.15 Calls With Timeout Call With Timeout 7.16 Updatable Binary Trees 7.17 Unweighted Graphs
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This library provides a set of utilities to apply a predicate to all
elements of a list or to all sub-terms of a term. They allow one 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 following routines are available once included with the
use_module(library(apply_macros)) command.
maplist(+Pred, ?ListIn, ?ListOut)
checklist(+Pred, +List)
selectlist(+Pred, +ListIn, ?ListOut)
convlist(+Pred, +ListIn, ?ListOut)
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)
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) :-
(compound(TermIn) ; atom(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]).
mapnodes(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')]).
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following association list manipulation predicates are available
once included with the use_module(library(assoc)) command.
assoc_to_list(+Assoc,?List)
empty_assoc(+Assoc)
gen_assoc(+Assoc,?Key,?Value)
get_assoc(+Key,+Assoc,?Value)
get_assoc(+Key,+Assoc,?Value,+NAssoc,?NValue)
list_to_assoc(+List,?Assoc)
map_assoc(+Pred,+Assoc,?New)
ord_list_to_assoc(+List,?Assoc)
put_assoc(+Key,+Assoc,+Val,+New)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
avl_insert(+Key,?Value,+T0,+TF)
avl_lookup(+Key,-Value,+T)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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,
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following list manipulation routines are available once included
with the use_module(library(lists)) command.
append(?Prefix,?Suffix,?Combined)
delete(+List, ?Element, ?Residue)
is_list(+List)
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
nth(?N, ?List, ?Elem)
nth0/3, except that it counts from
1, that is nth(1, [H|_], H).
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.
nth(?N, ?List, ?Elem, ?Rest)
nth(1, 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.
permutation(+List,?Perm)
remove_dups(+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, ?Set, ?Residue)
sublist(?Sublist, ?List)
append(_,Sublist,S) and append(S,_,List) hold.
suffix(?Suffix, ?List)
append(_,Suffix,List) holds.
sum_list(?Numbers, ?Total)
sumlist(?Numbers, ?Total)
sum_list/2, please do use sum_list/2
instead.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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_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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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. |
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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(-Number, +LOW, +HIGH)
[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).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
Match regular expression RegExp to input string String according to options Opts. The options may be:
nocase: Causes upper-case characters in String to
be treated as lower case during the matching process.
regexp(+RegExp,+String,+Opts,SubMatchVars)
Match regular expression RegExp to input string String according to options Opts. The variable SubMatchVars should be originally a list of unbound variables all will contain a sequence of matches, that is, the head of SubMatchVars will contain the characters in String that matched the leftmost parenthesized subexpression within RegExp, the next head of list will contain the characters that matched the next parenthesized subexpression to the right in RegExp, and so on.
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])
|
"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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 builtin opens the string for reading. These commands
are available through the use_module(library(charsio)) command.
format_to_chars(+Form, +Args, -Result)
Execute the built-in procedure format/2 with form Form and
arguments Args outputting the result to the string of character
codes Result.
format_to_chars(+Form, +Args, -Result0, -Result)
Execute the built-in procedure 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)
Execute the built-in procedure write/1 with argument Term
outputting the result to the string of character codes Result.
write_to_chars(+Term, -Result0, -Result)
Execute the built-in procedure write/1 with argument Term
outputting the result to the difference list of character codes
Result-Result0.
atom_to_chars(+Atom, -Result)
Convert the atom Atom to the string of character codes Result.
atom_to_chars(+Atom, -Result0, -Result)
Convert the atom Atom to the difference list of character codes Result-Result0.
number_to_chars(+Number, -Result)
Convert the number Number to the string of character codes Result.
number_to_chars(+Number, -Result0, -Result)
Convert the atom Number to the difference list of character codes Result-Result0.
read_from_chars(+Chars, -Term)
Parse the list of character codes Chars and return the result in the term Term. The character codes to be read must terminate with a dot character such that either (i) the dot character is followed by blank characters; or (ii) the dot character is the last character in the string.
open_chars_stream(+Chars, -Stream)
Open the list of character codes Chars as a stream Stream.
with_output_to_chars(?Goal, -Chars)
Execute goal Goal such that its standard output will be sent to a memory buffer. After successful execution the contents of the memory buffer will be converted to the list of character codes Chars.
with_output_to_chars(?Goal, ?Chars0, -Chars)
Execute goal Goal such that its standard output will be sent to a memory buffer. After successful execution the contents of the memory buffer will be converted to the difference list of character codes Chars-Chars0.
with_output_to_chars(?Goal, -Stream, ?Chars0, -Chars)
Execute goal Goal such that its standard output will be sent to a memory buffer. After successful execution the contents of the memory buffer will be converted to the difference list of character codes Chars-Chars0 and Stream receives the stream corresponding to the memory buffer.
The implementation of the character IO operations relies on three YAP builtins:
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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) ? |
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,..,'.']
|
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. 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 builtin function rename.
environ(?EnvVar,+EnvValue)
?- environ('HOME',X).
X = 'C:\\cygwin\\home\\administrator' ?
|
host_id(-Id)
Unify Id with an identifier of the current host. Yap uses the
hostid function when available,
host_name(-Name)
Unify Name with a name for the current host. Yap uses the
hostname function in Unix systems when available, and the
GetComputerName function in WIN32 systems.
kill(Id,+SIGNAL)
Send signal SIGNAL to process Id. In Unix this predicate is
a direct interface to kill so one can send signals to groups of
processes. In WIN32 the predicate is an interface to
TerminateProcess, so it kills Id indepent of SIGNAL.
mktemp(Spec,-File)
Direct interface to 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)
Unify Id with the process identifier for the current process. An interface to the getpid function.
tmpnam(-File)
Interface with tmpnam: create an unique file and unify its name with File.
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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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(timeout)) command.
acyclic_term(?Term)
cyclic_term(?Term)
term_hash(+Term, ?Hash)
If Term is ground unify Hash with a positive integer
calculated from the structure of the term. Otherwise the argument
Hash is left unbound. The range of the positive integer is from
0 to, but not including, 33554432.
term_hash(+Term, +Depth, +Range, ?Hash)
Unify Hash with a positive integer calculated from the structure
of the term. The range of the positive integer is from 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.
term_variables(?Term, -Variables)
Unify Variables with a list of all variables in term Term.
variant(?Term1, ?Term2)
Succeed if Term1 and Term2 are variant terms.
subsumes(?Term1, ?Term2)
Succeed if Term1 subsumes Term2. Variables in term Term1 are bound so that the two terms become equal.
subsumes_chk(?Term1, ?Term2)
Succeed if Term1 subsumes Term2 but does not bind any variable in Term1.
variable_in_term(?Term,?Var)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 through 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. 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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following graph manipulation routines are based from 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 builtins 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-[]] ? |
?- 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(+Vertices, +Graph, -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-[]]
|
sub_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-[]]
|
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] |
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] |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
9. Rational Trees Working with Rational Trees 10. Coroutining Changing the Execution of Goals 11. Attributed Variables Using attributed Variables 12. CLP(Q,R) Manual The CLP(Q,R) System 14. Logtalk The Logtalk Object-Oriented system 15. Parallelism Running in Or-Parallel 16. Tabling Storing Intermediate Solutions of programs 18. Profiling the Abstract Machine Profiling Abstract Machine Instructions 17. Tracing at Low Level Tracing at Abstract Machine Level
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
By default, rational trees are not supported in YAP, and these
terms can easily lead to infinite computation. For example, X =
a(X), X = X will 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 builtins 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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 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)
C1,C2
C1;C2
?=(V1,C2)
nonvar(V)
ground(V)
Note that when/2 will fail if the conditions fail.
call_residue(:G,L)
Call goal G. If subgoals of G are still blocked, return
a list containing these goals and the variables they are blocked in. The
goals are then considered as unblocked. The next example shows a case
where 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
|
dif/2 as having
suspended.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
11.1 Attribute Declarations Declaring New Attributes 11.2 Attribute Manipulation Setting and Reading Attributes 11.3 Attributed Unification Tuning the Unification Algorithm 11.4 Displaying Attributes Displaying Attributes in User-Readable Form 11.5 Projecting Attributes Obtaining the Attributes of Interest 11.6 Attribute Examples Two Simple Examples of how to use Attributes.
YAP now supports the attributed variables packaged 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 and Fruewirth and Holzbaur's CHR, but other applications have been proposed in the literature.
The command
| ?- use_module(library(atts)). |
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
builtins that manipulate attributes so that attribute names are
preprocessed depending on the module. The user:goal_expansion/3
mechanism is used for this purpose.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The attribute manipulation predicates always work as follows:
The following three procedures are available to the user. Notice that these builtins are rewritten by the system into internal builtins, and that the rewriting process depends on the module on which the builtins have been invoked.
Module:get_atts(-Var,?ListOfAttributes)
+(Attribute), -(Attribute) (the kbd
prefix may be dropped). The meaning of + and - is:
+(Attribute)
-(Attribute)
Module:put_atts(-Var,?ListOfAttributes)
+(Attribute)
set_mutable/2).
-(Attribute)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The user-predicate predicate verify_attributes/3 is called when
attempting to unify an attributed variable which might have attributes
in some Module.
Module:verify_attributes(-Var, +Value, -Goals)
The predicate is called when trying to unify the attributed variable Var with the Prolog term Value. Note that Value may be itself an attributed variable, or may contain attributed variables. The goal verify_attributes/3 is actually called before Var is unified with Value.
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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Attributes are usually presented as goals. The following routines are
used by builtin predicates such as call_residue/2 and by the
Prolog top-level to display attributes:
Module:attribute_goal(-Var, -Goal)
Module:project_attributes(-QueryVars, +AttrVars)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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.
Module: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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 th 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.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
CLP(Q,R)
This Manual documents a Prolog implementation of clp(Q,R), based on SICStus featuring extensible unification via attributed variables.
Edition 1.3.3 December 1995
Christian Holzbaur christian@ai.univie.ac.at
Copyright © 1992,1993,1994,1995 OFAI Austrian Research Institute for Artificial Intelligence (OFAI) Schottengasse 3 A-1010 Vienna, Austria
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted qto copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the OFAI.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The clp(Q,R) system described in this document is an instance of the general Constraint Logic Programming scheme introduced by [Jaffar & Michaylov 87].
The implementation is at least as complete as other existing clp(R) implementations: It solves linear equations over rational or real valued variables, covers the lazy treatment of nonlinear equations, features a decision algorithm for linear inequalities that detects implied equations, removes redundancies, performs projections (quantifier elimination), allows for linear dis-equations, and provides for linear optimization.
The full clp(Q,R) distribution, including a stand-alone manual and an examples directory that is possibly more up to date than the version in the SICStus Prolog distribution, is available from: http://www.ai.univie.ac.at/clpqr/.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When referring to this implementation of clp(Q,R) in publications, you should use the following reference:
Holzbaur C.: OFAI clp(q,r) Manual, Edition 1.3.3, Austrian Research Institute for Artificial Intelligence, Vienna, TR-95-09, 1995.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The development of this software was supported by the Austrian Fonds zur Foerderung der Wissenschaftlichen Forschung under grant P9426-PHY. Financial support for the Austrian Research Institute for Artificial Intelligence is provided by the Austrian Federal Ministry for Science and Research.
We include a collection of examples that has been distributed with the Monash University version of clp(R) [Heintze et al. 87], and its inclusion into this distribution was kindly permitted by Roland Yap.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Rational numbers are not first class citizens in SICStus Prolog, so rational arithmetics has to be emulated. Because of the emulation it is too expensive to support arithmetics with automatic coercion between all sorts of numbers, like you find it in CommonLisp, for example.
You must choose whether you want to operate in the field of Q (Rationals) or R (Reals):
?- use_module(library(clpq)). |
or
?- use_module(library(clpr)). |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Throughout this chapter, the prompts clp(q) ?- and clp(r)
?- are used to differentiate between clp(Q) and clp(R) in exemplary
interactions.
In general there are many ways to express the same linear relationship. This degree of freedom is manifest in the fact that the printed manual and an actual interaction with the current version of clp(Q,R) may show syntactically different answer constraints, despite the fact the same semantic relationship is being expressed. There are means to control the presentation, see see section 12.14 Variable Ordering. The approximative nature of floating point numbers may also produce numerical differences between the text in this manual and the actual results of clp(R), for a given edition of the software.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The solver interface for both Q and R consists of the following predicates which are exported from module(linear).
{+Constraint}
Constraint is a term accepted by the the grammar below. The
corresponding constraint is added to the current constraint store and
checked for satisfiability. If you want to overload {}/1 with other
solvers, you can avoid its importation via: use_module(clpq, []).
Constraint --> C
| C , C conjunction
C --> Expr =:= Expr equation
| Expr = Expr equation
| Expr < Expr strict inequation
| Expr > Expr strict inequation
| Expr =< Expr nonstrict inequation
| Expr >= Expr nonstrict inequation
| Expr =\= Expr disequation
Expr --> variable Prolog variable
| number floating point or integer
| + Expr unary plus
| - Expr unary minus
| Expr + Expr addition
| Expr - Expr subtraction
| Expr * Expr multiplication
| Expr / Expr division
| abs(Expr) absolute value
| sin(Expr) trigonometric sine
| cos(Expr) trigonometric cosine
| tan(Expr) trigonometric tangent
| pow(Expr,Expr) raise to the power
| exp(Expr,Expr) raise to the power
| min(Expr,Expr) minimum of the two
arguments
| max(Expr,Expr) maximum of the two
arguments
| #(Const) symbolic numerical
constant
|
Conjunctive constraints {-C,C} have been made part of the syntax in order to enable grouped submission of constraints, which could be exploited by future versions of this software. Symbolic numerical constants are provided for compatibility only, see see section 12.19 Monash Examples.
entailed(+Constraint)
Succeeds iff the linear Constraint is entailed by the current constraint store. This predicate does not change the state of the constraint store.
clp(q) ?- {A =< 4}, entailed(A=\=5).
{A=<4}
yes
clp(q) ?- {A =< 4}, entailed(A=\=3).
no
|
inf(+Expr, -Inf )
sup(+Expr, -Sup)
Computes the supremum of the linear expression Expr and unifies it with Sup. Failure indicates unboundedness.
clp(q) ?- { 2*X+Y =< 16, X+2*Y =< 11,
X+3*Y =< 15, Z = 30*X+50*Y
}, sup(Z, Sup).
Sup = 310,
{Z=30*X+50*Y},
{X+1/2*Y=<8}
{X+3*Y=<15},
{X+2*Y=<11}
|
minimize(+Expr)
Computes the infimum of the linear expression Expr and equates it with the expression, i.e. as if defined as:
minimize(Expr) :- inf(Expr, Expr). |
maximize(+Expr)
Computes the supremum of the linear expression Expr and equates it with the expression.
clp(q) ?- { 2*X+Y =< 16, X+2*Y =< 11,
X+3*Y =< 15, Z = 30*X+50*Y
}, maximize(Z).
X = 7,
Y = 2,
Z = 310
|
bb_inf(+Ints, +Expr, -Inf)
Computes the infimum of the linear expression Expr under the additional constraint that all of variables in the list Ints assume integral values at the infimum. This allows for the solution of mixed integer linear optimization problems, see see section 12.21 A Mixed Integer Linear Optimization Example.
ordering(+Spec)
Provides a means to control one aspect of the presentation of the answer constraints, see see section 12.14 Variable Ordering.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Equality constraints are added to the store implicitly each time variables that have been mentioned in explicit constraints are bound - either to another such variable or to a number.
clp(r) ?- {2*A+3*B=C/2}, C=10.0, A=B.
A = 1.0,
B = 1.0,
C = 10.0
|
Is equivalent modulo rounding errors to
clp(r) ?- {2*A+3*B=C/2, C=10, A=B}.
A = 1.0,
B = 0.9999999999999999,
C = 10.0
|
The shortcut bypassing the use of {}q/1 is allowed and makes sense
because the interpretation of this equality in Prolog and clp(R)
coincides. In general, equations involving interpreted functors,
+/2 in this case, must be fed to the solver explicitly:
clp(r) ?- X=3.0+1.0, X=4.0. no |
Further, variables known by clp(R) may be bound directly to floats only. Likewise, variables known by clp(Q) may be bound directly to rational numbers only, see see section 12.12 Numerical Precision and Rationals. Failing to do so is rewarded with an exception:
clp(q) ?- {2*A+3*B=C/2}, C=10.0, A=B.
[ERROR: not.normalized(10.0)]
|
This is because 10.0 is not a rational constant. To make clp(Q) happy you have to say:
clp(q) ?- {2*A+3*B=C/2}, C=rat(10,1), A=B.
A = 1,
B = 1,
C = 10
|
If you use {}/1, you don't have to worry about such
details. Alternatively, you may use the automatic expansion facility,
check see section 12.18 Syntactic Sugar.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
What was covered so far was how the user populates the constraint store. The other direction of the information flow consists of the success and failure of the above predicates and the binding of variables to numerical values and the aliasing of variables. Example:
clp(r) ?- {A-B+C=10, C=5+5}.
B = A,
C = 10.0
|
The linear constraints imply A=B and the solver consequently
exports this binding to the Prolog world, which is manifest in the fact
that the test A==B will succeed. More about answer presentation
in see section 12.13 Projection and Redundancy Elimination.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The clp(Q,R) system is restricted to deal with linear constraints because the decision algorithms for general nonlinear constraints are prohibitively expensive to run. If you need this functionality badly, you should look into symbolic algebra packages. Although the clp(Q,R) system cannot solve nonlinear constraints, it will collect them faithfully in the hope that through the addition of further (linear) constraints they might get simple enough to solve eventually. If an answer contains constraints, you have to be aware of the fact that success is qualified modulo the existence of a solution to the system of residual (nonlinear) constraints:
clp(r) ?- {sin(X) = cos(X)}.
nonlin:{sin(X)-cos(X)=0.0}
|
There are indeed infinitely many solutions to this constraint (X =
0.785398 + n*Pi), but clp(Q,R) has no direct means to find and
represent them.
The systems goes through some lengths to recognize linear expressions as such. The method is based on a normal form for multivariate polynomials. In addition, some simple isolation axioms, that can be used in equality constraints, have been added. The current major limitation of the method is that full polynomial division has not been implemented.
This is an example where the isolation axioms are sufficient to determine the value of X.
clp(r) ?- {sin(cos(X)) = 1/2}.
X = 1.0197267436954502
|
If we change the equation into an inequation, clp(Q,R) gives up:
clp(r) ?- {sin(cos(X)) < 1/2}.
nonlin:{sin(cos(X))-0.5!0.0}
|
The following is easy again:
clp(r) ?- {sin(X+2+2)/sin(4+X) = Y}.
Y = 1.0
|
And so is this:
clp(r) ?- {(X+Y)*(Y+X)/X = Y*Y/X+99}.
{Y=49.5-0.5*X}
|
An ancient symbol manipulation benchmark consists in rising the
expression X+Y+Z+1 to the 15th power:
clp(q) ?- {exp(X+Y+Z+1,15)=0}.
nonlin:{Z^15+Z^14*15+Z^13*105+Z^12*455+Z^11*1365+Z^10*3003+...
... polynomial continues for a few pages ...
=0}
|
Computing its roots is another story.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Binding variables that appear in nonlinear residues will reduce the complexity of the nonlinear expressions and eventually results in linear expressions:
clp(q) ?- {exp(X+Y+1,2) = 3*X*X+Y*Y}.
nonlin:{Y*2-X^2*2+Y*X*2+X*2+1=0}
|
Equating X and Y collapses the expression completely and even determines the values of the two variables:
clp(q) ?- {exp(X+Y+1,2) = 3*X*X+Y*Y}, X=Y.
X = -1/4,
Y = -1/4
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
These axioms are used to rewrite equations such that the variable to be solved for is moved to the left hand side and the result of the evaluation of the right hand side can be assigned to the variable. This allows, for example, to use the exponentiation operator for the computation of roots and logarithms, see below.
A = B * C
A = B / C
X = min(Y,Z)
X = max(Y,Z)
X = abs(Y)
X = pow(Y,Z), X = exp(Y,Z)
clp(r) ?- { 12=pow(2,X) }.
X = 3.5849625007211565
clp(r) ?- { 12=pow(X,3.585) }.
X = 1.9999854993443926
clp(r) ?- { X=pow(2,3.585) }.
X = 12.000311914286545
|
X = sin(Y)
clp(r) ?- { 1/2 = sin(X) }.
X = 0.5235987755982989
|
X = cos(Y)
X = tan(Y)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The fact that you can switch between clp(R) and clp(Q) should solve most of your numerical problems regarding precision. Within clp(Q), floating point constants will be coerced into rational numbers automatically. Transcendental functions will be approximated with rationals. The precision of the approximation is limited by the floating point precision. These two provisions allow you to switch between clp(R) and clp(Q) without having to change your programs.
What is to be kept in mind however is the fact that it may take quite big rationals to accommodate the required precision. High levels of precision are for example required if your linear program is ill-conditioned, i.e., in a full rank system the determinant of the coefficient matrix is close to zero. Another situation that may call for elevated levels of precision is when a linear optimization problem requires exceedingly many pivot steps before the optimum is reached.
If your application approximates irrational numbers, you may be out of space particularly soon. The following program implements N steps of Newton's approximation for the square root function at point 2.
%
% from file: library('clpqr/examples/root')
%
root(N, R) :-
root(N, 1, R).
root(0, S, R) :- !, S=R.
root(N, S, R) :-
N1 is N-1,
{ S1 = S/2 + 1/S },
root(N1, S1, R).
|
It is known that this approximation converges quadratically, which means that the number of correct digits in the decimal expansion roughly doubles with each iteration. Therefore the numerator and denominator of the rational approximation have to grow likewise:
clp(q) ?- use+odule(library('clpqr/examples/root')).
clp(q) ?- root(3,R),print_decimal(R,70).
1.4142156862 7450980392 1568627450 9803921568 6274509803 9215686274
5098039215
R = 577/408
clp(q) ?- root(4,R),print_decimal(R,70).
1.4142135623 7468991062 6295578890 1349101165 5962211574 4044584905
0192000543
R = 665857/470832
clp(q) ?- root(5,R),print_decimal(R,70).
1.4142135623 7309504880 1689623502 5302436149 8192577619 7428498289
4986231958
R = 886731088897/627013566048
clp(q) ?- root(6,R),print_decimal(R,70).
1.4142135623 7309504880 1688724209 6980785696 7187537723 4001561013
1331132652
R = 1572584048032918633353217/1111984844349868137938112
clp(q) ?- root(7,R),print_decimal(R,70).
1.4142135623 7309504880 1688724209 6980785696 7187537694 8073176679
7379907324
R = 4946041176255201878775086487573351061418968498177 /
3497379255757941172020851852070562919437964212608
|
Iterating for 8 steps produces no further change in the first 70 decimal
digits of sqrt(2). After 15 steps the approximating rational
number has a numerator and a denominator with 12543 digits each, and the
next step runs out of memory.
Another irrational number that is easily computed is e. The
following program implements an alternating series for 1/e, where
the absolute value of last term is an upper bound on the error.
%
% from file: library('clpqr/examples/root')
%
e(N, E) :-
{ Err =:= exp(10,-(N+2)), Half =:= 1/2 },
inv_e_series(Half, Half, 3, Err, Inv.E),
{ E =:= 1/Inv_E }.
inv_e_series(Term, S0, ., Err, Sum) :-
{ abs(Term) =< Err }, !,
S0 = Sum.
inv_e_series(Term, S0, N, Err, Sum) :-
N1 is N+1,
{ Term1 =:= -Term/N, S1 =:= Term1+S0 },
inv_e_series(Term1, S1, N1, Err, Sum).
|
The computation of the rational number E that approximates
e up to at least 1000 digits in its decimal expansion requires
the evaluation of 450 terms of the series, i.e. 450 calls of
inv.e. series/5.
clp(q) ?- e(1000,E).
E = 7149056228932760213666809592072842334290744221392610955845565494
3708750229467761730471738895197792271346693089326102132000338192
0131874187833985420922688804220167840319199699494193852403223700
5853832741544191628747052136402176941963825543565900589161585723
4023097417605004829991929283045372355639145644588174733401360176
9953973706537274133283614740902771561159913069917833820285608440
3104966899999651928637634656418969027076699082888742481392304807
9484725489080844360397606199771786024695620205344042765860581379
3538290451208322129898069978107971226873160872046731879753034549
3130492167474809196348846916421782850086985668680640425192038155
4902863298351349469211627292865440876581064873866786120098602898
8799130098877372097360065934827751120659213470528793143805903554
7928682131082164366007016698761961066948371407368962539467994627
1374858249110795976398595034606994740186040425117101588480000000
0000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000
/
2629990810403002651095959155503002285441272170673105334466808931
6863103901346024240326549035084528682487048064823380723787110941
6809235187356318780972302796570251102928552003708556939314795678
1978390674393498540663747334079841518303636625888963910391440709
0887345797303470959207883316838346973393937778363411195624313553
8835644822353659840936818391050630360633734935381528275392050975
7271468992840907541350345459011192466892177866882264242860412188
0652112744642450404625763019639086944558899249788084559753723892
1643188991444945360726899532023542969572584363761073528841147012
2634218045463494055807073778490814692996517359952229262198396182
1838930043528583109973872348193806830382584040536394640895148751
0766256738740729894909630785260101721285704616818889741995949666
6303289703199393801976334974240815397920213059799071915067856758
6716458821062645562512745336709063396510021681900076680696945309
3660590933279867736747926648678738515702777431353845466199680991
73361873421152165477774911660108200059
|
The decimal expansion itself looks like this:
clp(q) ?- e(1000, E), print_decimal(E, 1000). 2. 7182818284 5904523536 0287471352 6624977572 4709369995 9574966967 6277240766 3035354759 4571382178 5251664274 2746639193 2003059921 8174135966 2904357290 0334295260 5956307381 3232862794 3490763233 8298807531 9525101901 1573834187 9307021540 8914993488 4167509244 7614606680 8226480016 8477411853 7423454424 3710753907 7744992069 5517027618 3860626133 1384583000 7520449338 2656029760 6737113200 7093287091 2744374704 7230696977 2093101416 9283681902 5515108657 4637721112 5238978442 5056953696 7707854499 6996794686 4454905987 9316368892 3009879312 7736178215 4249992295 7635148220 8269895193 6680331825 2886939849 6465105820 9392398294 8879332036 2509443117 3012381970 6841614039 7019837679 3206832823 7646480429 5311802328 7825098194 5581530175 6717361332 0698112509 9618188159 3041690351 5988885193 4580727386 6738589422 8792284998 9208680582 5749279610 4841984443 6346324496 8487560233 6248270419 7862320900 2160990235 3043699418 4914631409 3431738143 6405462531 5209618369 0888707016 7683964243 7814059271 4563549061 3031072085 1038375051 0115747704 1718986106 8739696552 1267154688 9570350354 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Once a derivation succeeds, the Prolog system presents the bindings for the variables in the query. In a CLP system, the set of answer constraints is presented in analogy. A complication in the CLP context are variables and associated constraints that were not mentioned in the query. A motivating example is the familiar mortgage relation:
%
% from file: library('clpqr/examples/mg')
%
mg(P,T,I,B,MP):-
{
T = 1,
B + MP = P * (1 + I)
}.
mg(P,T,I,B,MP):-
{
T > 1,
P1 = P * (1 + I) - MP,
T1 = T - 1
}, mg(P1, T1, I, B, MP).
|
A sample query yields:
clp(r) ?- use_module(library('clpqr/examples/mg')).
clp(r) ?- mg(P,12,0.01,B,Mp).
{B=1.1268250301319698*P-12.682503013196973*Mp}
|
Without projection of the answer constraints onto the query variables we would observe the following interaction:
clp(r) ?- mg(P,12,0.01,B,Mp).
{B=12.682503013196973*_A-11.682503013196971*P},
{Mp= -(_A)+1.01*P},
{_B=2.01*_A-1.01*P}
{_C=3.0301*_A-2.0301*P},
{_D=4.060401000000001*_A-3.0604009999999997*P},
{_E=5.101005010000001*_A-4.10100501*P},
{_F=6.152015060100001*_A-5.152015060099999*P},
{_G=7.213535210701001*_A-6.213535210700999*P},
{_H=8.285670562808011*_A-7.285670562808009*P},
{_I=9.368527268436091*_A-8.36852726843609*P},
{_J=10.462212541120453*_A-9.46221254112045*P},
{_K=11.566834666531657*_A-10.566834666531655*P}
|
The variables _A ... _K are not part of the query, they originate from the mortgage program proper. Although the latter answer is equivalent to the former in terms of linear algebra, most users would prefer the former.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In general, there are many ways to express the same linear relationship between variables. clp(Q,R) does not care to distinguish between them, but the user might. The predicate ordering(+Spec) gives you some control over the variable ordering. Suppose that instead of B, you want Mp to be the defined variable:
clp(r) ?- mg(P,12,0.01,B,Mp).
{B=1.1268250301319698*P-12.682503013196973*Mp}
|
This is achieved with:
clp(r) ?- mg(P,12,0.01,B,Mp), ordering([Mp]).
{Mp= -0.0788487886783417*B+0.08884878867834171*P}
|
One could go one step further and require P to appear before (to the left of) B in a addition:
clp(r) ?- mg(P,12,0.01,B,Mp), ordering([Mp,P]).
{Mp=0.08884878867834171*P-0.0788487886783417*B}
|
Spec in ordering(+Spec) is either a list of variables with
the intended ordering, or of the form A<B. The latter
form means that A goes to the left of B. In fact,
ordering([A,B,C,D]) is shorthand for:
ordering(A < B), ordering(A < C), ordering(A < D), ordering(B < C), ordering(B < D), ordering(C < D) |
The ordering specification only affects the final presentation of the constraints. For all other operations of clp(Q,R), the ordering is immaterial. Note that ordering/1 acts like a constraint: you can put it anywhere in the computation, and you can submit multiple specifications.
clp(r) ?- ordering(B < Mp), mg(P,12,0.01,B,Mp).
{B= -12.682503013196973*Mp+1.1268250301319698*P}
yes
clp(r) ?- ordering(B < Mp), mg(P,12,0.01,B,Mp), ordering(P < Mp).
{P=0.8874492252651537*B+11.255077473484631*Mp}
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In meta-programming applications one needs to get a grip on the results
computed by the clp(Q,R) solver. The SISCtus Prolog predicate
call_residue/2 provides this functionality:
clp(r) ?- call_residue({2*A+B+C=10,C-D=E,A<10}, Constraints).
Constraints = [
[A]-{A<10.0},
[B]-{B=10.0-2.0*A-C},
[D]-{D=C-E}
]
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
As soon as linear inequations are involved, projection gets more demanding complexity wise. The current clp(Q,R) version uses a Fourier-Motzkin algorithm for the projection of linear inequalities. The choice of a suitable algorithm is somewhat dependent on the number of variables to be eliminated, the total number of variables, and other factors. It is quite easy to produce problems of moderate size where the elimination step takes some time. For example, when the dimension of the projection is 1, you might be better off computing the supremum and the infimum of the remaining variable instead of eliminating n-1 variables via implicit projection.
In order to make answers as concise as possible, redundant constraints are removed by the system as well. In the following set of inequalities, half of them are redundant.
%
% from file: library('clpqr/examples/elimination')
%
example(2, [X0,X1,X2,X3,X4]) :-
{
+87*X0 +52*X1 +27*X2 -54*X3 +56*X4 =< -93,
+33*X0 -10*X1 +61*X2 -28*X3 -29*X4 =< 63,
-68*X0 +8*X1 +35*X2 +68*X3 +35*X4 =< -85,
+90*X0 +60*X1 -76*X2 -53*X3 +24*X4 =< -68,
-95*X0 -10*X1 +64*X2 +76*X3 -24*X4 =< 33,
+43*X0 -22*X1 +67*X2 -68*X3 -92*X4 =< -97,
+39*X0 +7*X1 +62*X2 +54*X3 -26*X4 =< -27,
+48*X0 -13*X1 +7*X2 -61*X3 -59*X4 =< -2,
+49*X0 -23*X1 -31*X2 -76*X3 +27*X4 =< 3,
-50*X0 +58*X1 -1*X2 +57*X3 +20*X4 =< 6,
-13*X0 -63*X1 +81*X2 -3*X3 +70*X4 =< 64,
+20*X0 +67*X1 -23*X2 -41*X3 -66*X4 =< 52,
-81*X0 -44*X1 +19*X2 -22*X3 -73*X4 =< -17,
-43*X0 -9*X1 +14*X2 +27*X3 +40*X4 =< 39,
+16*X0 +83*X1 +89*X2 +25*X3 +55*X4 =< 36,
+2*X0 +40*X1 +65*X2 +59*X3 -32*X4 =< 13,
-65*X0 -11*X1 +10*X2 -13*X3 +91*X4 =< 49,
+93*X0 -73*X1 +91*X2 -1*X3 +23*X4 =< -87
}.
|
Consequently, the answer consists of the system of nine non-redundant inequalities only:
clp(q) ?- use_module(library('clpqr/examples/elimination')).
clp(q) ?- example(2, [X0,X1,X2,X3,X4]).
{X0-2/17*X1-35/68*X2-X3-35/68*X4?=5/4},
{X0-73/93*X1+91/93*X2-1/93*X3+23/93*X4=<-29/31},
{X0-29/25*X1+1/50*X2-57/50*X3-2/5*X4>=-3/25},
{X0+7/39*X1+62/39*X2+18/13*X3-2/3*X4=<-9/13},
{X0+2/19*X1-64/95*X2-4/5*X3+24/95*X4>=-33/95},
{X0+2/3*X1-38/45*X2-53/90*X3+4/15*X4=<-34/45},
{X0-23/49*X1-31/49*X2-76/49*X3+27/49*X4=<3/49},
{X0+44/81*X1-19/81*X2+22/81*X3+73/81*X4>=17/81},
{X0+9/43*X1-14/43*X2-27/43*X3-40/43*X4>=-39/43}
|
The projection (the shadow) of this polyhedral set into the X0,X1 space can be computed via the implicit elimination of non-query variables:
clp(q) ?- example(2, [X0,X1--.]).
{X0+2619277/17854273*X1>=-851123/17854273},
{X0+6429953/16575801*X1=<-12749681/16575801},
{X0+19130/1213083*X1>=795400/404361},
{X0-1251619/3956679*X1?=21101146/3956679},
{X0+601502/4257189*X1>=220850/473021}
|
Projection is quite a powerful concept that leads to surprisingly terse executable specifications of nontrivial problems like the computation of the convex hull from a set of points in an n-dimensional space: Given the program
%
% from file: library('clpqr/examples/elimination')
%
conv.hull(Points, Xs) :-
lin_comb(Points, Lambdas, Zero, Xs),
zero(Zero),
polytope(Lambdas).
polytope(Xs) :-
positive_sum(Xs, 1).
positive_sum([], Z) :- {Z=0}.
positive_sum([X--Xs], SumX) :-
{X >= 0, SumX = X+Sum },
positive_sum(Xs, Sum).
zero([]).
zero([Z--Zs]) :- {Z=0}, zero(Zs).
lin_comb([], [], S1, S1).
lin_comb([Ps--Rest], [K--Ks], S1, S3) :-
lin_comb_r(Ps, K, S1, S2),
lin_comb(Rest, Ks, S2, S3).
lin_comb_r([], ., [], []).
lin_comb_r([P--Ps], K, [S--Ss], [Kps--Ss1]) :-
{ Kps = K*P+S },
lin_comb_r(Ps, K, Ss, Ss1).
|
we can post the following query:
clp(q) ?- conv.hull([ [1,1], [2,0], [3,0], [1,2], [2,2] ], [X,Y]).
{Y=<2},
{X+1/2*Y=<3},
{X>=1},
{Y>=0},
{X+Y>=2}
|
This answer is easily verified graphically:
|
2- * *
|
|
1| *
|
|
0 ---|---*---*----
1 2 3
|
The convex hull program directly corresponds to the mathematical definition of the convex hull. What does the trick in operational terms is the implicit elimination of the Lambdas from the program formulation. Please note that this program does not limit the number of points or the dimension of the space they are from. Please note further that quantifier elimination is a computationally expensive operation and therefore this program is only useful as a benchmark for the projector and not so for the intended purpose.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A beautiful example of disequations at work is due to [Colmerauer 90]. It addresses the task of tiling a rectangle with squares of all-different, a priori unknown sizes. Here is a translation of the original Prolog-III program to clp(Q,R):
%
% from file: library('clpqr/examples/squares')
filled_rectangle( A, C) :-
{ A >= 1 },
distinct_squares( C),
filled_zone( [-1,A,1], _, C, []).
distinct_squares( []).
distinct_squares( [B|C]) :-
{ B > 0 },
outof( C, B),
distinct_squares( C).
outof( [], _).
outof( [B1|C], B) :-
{ B =\= B1 }, % *** note disequation ***
outof( C, B).
filled_zone( [V|L], [V|L], C0, C0) :-
{ V >= 0 }.
filled_zone( [V|L], L3, [B|C], C2) :-
{ V < 0 },
placed_square( B, L, L1),
filled_zone( L1, L2, C, C1),
{ Vb=V+B },
filled_zone( [Vb,B|L2], L3, C1, C2).
placed_square( B, [H,H0,H1|L], L1) :-
{ B > H, H0=0, H2=H+H1 },
placed_square( B, [H2|L], L1).
placed_square( B, [B,V|L], [X|L]) :-
{ X=V-B }.
placed_square( B, [H|L], [X,Y|L]) :-
{ B < H, X= -B, Y=H-B }.
|
There are no tilings with less than nine squares except the trivial one where the rectangle equals the only square. There are eight solutions for nine squares. Six further solutions are rotations of the first two.
clp(q) ?- use_module(library('clpqr/examples/squares')).
clp(q) ?- filled_rectangle(A, Squares).
A = 1,f
Squares = [1] ? ;
A = 33/32,
Squares = [15/32,9/16,1/4,7/32,1/8,7/16,1/32,5/16,9/32] ? ;
A = 69/61,
Squares = [33/61,36/61,28/61,5/61,2/61,9/61,25/61,7/61,16/61]
|
Depending on your hardware, the above query may take a few minutes. Supplying the knowledge about the minimal number of squares beforehand cuts the computation time by a factor of roughly four:
clp(q) ?- length(Squares, 9), filled.rectangle(A, Squares). A = 33/32, Squares = [15/32,9/16,1/4,7/32,1/8,7/16,1/32,5/16,9/32] ? ; A = 69/61, Squares = [33/61,36/61,28/61,5/61,2/61,9/61,25/61,7/61,16/61] |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There is a package that transforms programs and queries from a
eval-quote variant of clp(Q,R) into corresponding programs and queries
in a quote-eval variant. Before you use it, you need to know that in an
eval-quote language, all symbols are interpreted unless explicitly
quoted. This means that interpreted terms cannot be manipulated
syntactically directly. Meta-programming in a CLP context by definition
manipulates interpreted terms, therefore you need quote/1 (just
as in LISP) and some means to put syntactical terms back to their
interpreted life: {}/1.
In a quote-eval language, meta-programming is (pragmatically) simpler because everything is implicitly quoted until explicitly evaluated. On the other hand, now object programming suffers from the dual inconvenience.
We chose to make our version of clp(Q,R) of the quote-eval type because this matches the intended use of the already existing boolean solver of SICStus. In order to keep the users of the eval-quote variant happy, we provide a source transformation package. It is activated via:
| ?- use_module(library('clpqr/expand')).
|
Loading the package puts you in a mode where the arithmetic functors
like +/2, */2 and all numbers (functors of arity 0) are
interpreted semantically.
clp(r) ?- 2+2=X. X = 4.0 |
The package works by purifying programs and queries in the sense that all references to interpreted terms are made explicit. The above query is expanded prior to evaluation into:
linear:{2.0+2.0=X}
|
The same mechanism applies when interpreted terms are nested deeper:
some_predicate(10, f(A+B/2), 2*cos(A)) |
Expands into:
linear:{Xc=2.0*cos(A)},
linear:{Xb=A+B/2},
linear:{Xa=10.0},
some_predicate(Xa, f(Xb), Xc)
|
This process also applies when files are consulted or compiled. In fact, this is the only situation where expansion can be applied with relative safety. To see this, consider what happens when the toplevel evaluates the expansion, namely some calls to the clp(Q,R) solver, followed by the call of the purified query. As we learned in see section 12.8 Feedback and Bindings, the solver may bind variables, which produces a goal with interpreted functors in it (numbers), which leads to another stage of expansion, and so on.
We recommend that you only turn on expansion temporarily while
consulting or compiling files needing expansion with expand/0 and
noexpand/0.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This collection of examples has been distributed with the Monash University Version of clp(R) [Heintze et al. 87], and its inclusion into this distribution was kindly permitted by Roland Yap.
In order to execute the examples, a small compatibility package has to be loaded first:
clp(r) ?- use_module(library('clpqr/monash')).
|
Then, assuming you are using clp(R):
clp(r) ?- expand, [library('clpqr/examples/monash/rkf45')],
noexpand.
clp(r) ?- go.
Point 0.00000 : 0.75000 0.00000
Point 0.50000 : 0.61969 0.47793
Point 1.00000 : 0.29417 0.81233
Point 1.50000 : -0.10556 0.95809
Point 2.00000 : -0.49076 0.93977
Point 2.50000 : -0.81440 0.79929
Point 3.00000 : -1.05440 0.57522
Iteration finished
------------------
439 derivative evaluations
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The Monash examples have been written for clp(R). Nevertheless, all but
rkf45 complete nicely in clp(Q). With rkf45, clp(Q) runs out of
memory. This is an instance of the problem discussed in see section 12.12 Numerical Precision and Rationals.
The Monash University clp(R) interpreter features a dump/n
predicate. It is used to print the target variables according to the
given ordering. Within this version of clp(Q,R), the corresponding
functionality is provided via ordering/1. The difference is that
ordering/1 does only specify the ordering of the variables and no
printing is performed. We think Prolog has enough predicates to perform
output already. You can still run the examples referring to
dump/n from the Prolog toplevel:
clp(r) ?- expand, [library('clpqr/examples/monash/mortgage')], noexpand.
% go2
%
clp(r) ?- mg(P,120,0.01,0,MP), dump([P,MP]).
{P=69.7005220313972*MP}
% go3
%
clp(r) ?- mg(P,120,0.01,B,MP), dump([P,B,MP]).
{P=0.30299477968602706*B+69.7005220313972*MP}
% go4
%
clp(r) ?- mg(999, 3, Int, 0, 400), dump.
nonlin:{_B-_B*Int+.A+400.0=0.0},
nonlin:{_A-_A*Int+400.0=0.0},
{_B=599.0+999.0*Int}
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In this section we are going to exercise our solver a little by the computation of a small mixed integer optimization problem (MIP) from miplib, a collection of MIP models, housed at Rice University. Here are the original comments on the example:
NAME: flugpl
ROWS: 18
COLUMNS: 18
INTEGER: 11
NONZERO: 46
BEST SOLN: 1201500 (opt)
LP SOLN: 1167185.73
SOURCE: Harvey M. Wagner
John W. Gregory (Cray Research)
E. Andrew Boyd (Rice University)
APPLICATION: airline model
COMMENTS: no integer variables are binary
|
%
% from file: library('clpqr/examples/mip')
%
example(flugpl, Obj, Vs, Ints, []) :-
Vs = [ Anm1,Anm2,Anm3,Anm4,Anm5,Anm6,
Stm1,Stm2,Stm3,Stm4,Stm5,Stm6,
UE1,UE2,UE3,UE4,UE5,UE6],
Ints = [Stm6, Stm5, Stm4, Stm3, Stm2,
Anm6, Anm5, Anm4, Anm3, Anm2, Anm1],
Obj = 2700*Stm1 + 1500*Anm1 + 30*UE1
+ 2700*Stm2 + 1500*Anm2 + 30*UE2
+ 2700*Stm3 + 1500*Anm3 + 30*UE3
+ 2700*Stm4 + 1500*Anm4 + 30*UE4
+ 2700*Stm5 + 1500*Anm5 + 30*UE5
+ 2700*Stm6 + 1500*Anm6 + 30*UE6,
allpos(Vs),
{ Stm1 = 60, 0.9*Stm1 +1*Anm1 -1*Stm2 = 0,
0.9*Stm2 +1*Anm2 -1*Stm3 = 0, 0.9*Stm3 +1*Anm3 -1*Stm4 = 0,
0.9*Stm4 +1*Anm4 -1*Stm5 = 0, 0.9*Stm5 +1*Anm5 -1*Stm6 = 0,
150*Stm1 -100*Anm1 +1*UE1 >= 8000,
150*Stm2 -100*Anm2 +1*UE2 >= 9000,
150*Stm3 -100*Anm3 +1*UE3 >= 8000,
150*Stm4 -100*Anm4 +1*UE4 >= 10000,
150*Stm5 -100*Anm5 +1*UE5 >= 9000,
150*Stm6 -100*Anm6 +1*UE6 >= 12000,
-20*Stm1 +1*UE1 =< 0, -20*Stm2 +1*UE2 =< 0, -20*Stm3 +1*UE3 =< 0,
-20*Stm4 +1*UE4 =< 0, -20*Stm5 +1*UE5 =< 0, -20*Stm6 +1*UE6 =< 0,
Anm1 =< 18, 57 =< Stm2, Stm2 =< 75, Anm2 =< 18,
57 =< Stm3, Stm3 =< 75, Anm3 =< 18, 57 =< Stm4,
Stm4 =< 75, Anm4 =< 18, 57 =< Stm5, Stm5 =< 75,
Anm5 =< 18, 57 =< Stm6, Stm6 =< 75, Anm6 =< 18
}.
allpos([]).
allpos([X|Xs]) :- {X >= 0}, allpos(Xs).
|
We can first check whether the relaxed problem has indeed the quoted infimum:
clp(r) ?- example(flugpl, Obj, _, _, _), inf(Obj, Inf). Inf = 1167185.7255923203 |
Computing the infimum under the additional constraints that Stm6, Stm5, Stm4, Stm3, Stm2, Anm6, Anm5, Anm4, Anm3, Anm2, Anm1 assume integer values at the infimum is computationally harder, but the query does not change much:
clp(r) ?- example(flugpl, Obj, _, Ints, _), bb_inf(Ints, Obj, Inf). Inf = 1201500.0000000005 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The system consists roughly of the following components:
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The internal data structure for rational numbers is
rat(Num,Den). Den is always positive, i.e. the
sign of the rational number is the sign of Num. Further, Num
and Den are relative prime. Note that inte