[Top] [Contents] [Index] [ ? ]

YAP Prolog

This file documents the YAP Prolog System version 5.1.3, a high-performance Prolog compiler developed at LIACC, Universidade do Porto. YAP is based on David H. D. Warren's WAM (Warren Abstract Machine), with several optimizations for better performance. YAP follows the Edinburgh tradition, and is largely compatible with DEC-10 Prolog, Quintus Prolog, and especially with C-Prolog.

This file contains extracts of the SWI-Prolog manual, as written by Jan Wielemaker. Our thanks to the author for his kind permission in allowing us to include his text in this document.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Introduction

This document provides User information on version 5.1.3 of YAP (Yet Another Prolog). The YAP Prolog System is a high-performance Prolog compiler developed at LIACC, Universidade do Porto. YAP provides several important features:

YAP is based on the David H. D. Warren's WAM (Warren Abstract Machine), with several optimizations for better performance. YAP follows the Edinburgh tradition, and was originally designed to be largely compatible with DEC-10 Prolog, Quintus Prolog, and especially with C-Prolog.

YAP implements most of the ISO-Prolog standard. We are striving at full compatibility, and the manual describes what is still missing. The manual also includes a (largely incomplete) comparison with SICStus Prolog.

The document is intended neither as an introduction to Prolog nor to the implementation aspects of the compiler. A good introduction to programming in Prolog is the book The Art of Prolog, by L. Sterling and E. Shapiro, published by "The MIT Press, Cambridge MA". Other references should include the classical Programming in Prolog, by W.F. Clocksin and C.S. Mellish, published by Springer-Verlag.

YAP 4.3 is known to build with many versions of gcc (<= gcc-2.7.2, >= gcc-2.8.1, >= egcs-1.0.1, gcc-2.95.*) and on a variety of Unixen: SunOS 4.1, Solaris 2.*, Irix 5.2, HP-UX 10, Dec Alpha Unix, Linux 1.2 and Linux 2.* (RedHat 4.0 thru 5.2, Debian 2.*) in both the x86 and alpha platforms. It has been built on Windows NT 4.0 using Cygwin from Cygnus Solutions (see README.nt) and using Visual C++ 6.0.

The overall copyright and permission notice for YAP4.3 can be found in the Artistic file in this directory. YAP follows the Perl Artistic license, and it is thus non-copylefted freeware.

If you have a question about this software, desire to add code, found a bug, want to request a feature, or wonder how to get further assistance, please send e-mail to yap-users AT lists.sourceforge.net. To subscribe to the mailing list, visit the page https://lists.sourceforge.net/lists/listinfo/yap-users.

On-line documentation is available for YAP at:

http://www.ncc.up.pt/~vsc/YAP/

Recent versions of YAP, including both source and selected binaries, can be found from this same URL.

This manual was written by Vítor Santos Costa, Luís Damas, Rogério Reis, and Rúben Azevedo. The manual is largely based on the DECsystem-10 Prolog User's Manual by D.L. Bowen, L. Byrd, F. C. N. Pereira, L. M. Pereira, and D. H. D. Warren. We have also used comments from the Edinburgh Prolog library written by R. O'Keefe. We would also like to gratefully acknowledge the contributions from Ashwin Srinivasian.

We are happy to include in YAP several excellent packages developed under separate licenses. Our thanks to the authors for their kind authorization to include these packages.

The packages are, in alphabetical order:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1. Installing YAP

To compile YAP it should be sufficient to:

  1. mkdir ARCH.
  2. cd ARCH.
  3. ../configure ...options....

    Notice that by default configure gives you a vanilla configuration. For instance, in order to use co-routining and/or CLP you need to do

     
    ../configure --enable-coroutining ...options...
    

    Please see section Tuning the Functionality of YAP for extra options.

  4. check the Makefile for any extensions or changes you want to make.

    YAP uses autoconf. Recent versions of YAP try to follow GNU conventions on where to place software.

  5. make.
  6. If the compilation succeeds, try ./yap.
  7. If you feel satisfied with the result, do make install.
  8. make install-info will create the info files in the standard info directory.
  9. 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] [ ? ]

1.1 Tuning the Functionality of YAP

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:

Next section discusses machine dependent details.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2 Tuning YAP for a Particular Machine and Compiler

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.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3 Tuning YAP for 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

Here follow a few hints:

On x86 machines the flags:

 
YAP_EXTRAS= ... -DBP_FREE=1

tells us to use the %bp register (frame-pointer) as the emulator's program counter. This seems to be stable and is now default.

On Sparc/Solaris2 use:

 
YAP_EXTRAS= ...   -mno-app-regs -DOPTIMISE_ALL_REGS_FOR_SPARC=1

and YAP will get two extra registers! This trick does not work on SunOS 4 machines.

Note that versions of GCC can be tweaked to recognize different processors within the same instruction set, e.g. 486, Pentium, and PentiumPro for the x86; or Ultrasparc, and Supersparc for Sparc. Unfortunately, some of these tweaks do may make YAP run slower or not at all in other machines with the same instruction set, so they cannot be made default.

Last, the best options also depends on the version of GCC you are using, and it is a good idea to consult the GCC manual under the menus "Invoking GCC"/"Submodel Options". Specifically, you should check -march=XXX for recent versions of GCC/EGCS. In the case of GCC2.7 and other recent versions of GCC you can check:

486:

In order to take advantage of 486 specific optimizations in GCC 2.7.*:

 
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:

PentiumPros are known not to require alignment. Check your version of 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

space you can use the abi 64 bits or eabi option, as in:

 
CC="gcc -mabi=64" ./configure --...

Be careful. At least for some versions of GCC, compiling with -g seems to result in broken code.

WIN32: GCC is distributed in the MINGW32 and CYGWIN packages.

The Mingw32 environment is available from the URL:

http://www.mingw.org

You will need to install the msys and mingw packages. You should be able to do configure, make and make install.

If you use mingw32 you may want to search the contributed packages for the gmp multi-precision arithmetic library. If you do setup YAP with gmp note that libgmp.dll must be in the path, otherwise YAP will not be able to execute.

CygWin environment is available from the URL:

http://www.cygwin.com

and mirrors. We suggest using recent versions of the cygwin shell. The compilation steps under the cygwin shell are as follows:

 
mkdir cyg
$YAPSRC/configure --enable-coroutining \\
                  --enable-depth-limit \\
                  --enable-max-performance
make
make install

By default, YAP will use the -mno-cygwin option to disable the use of the cygwin dll and to enable the mingw32 subsystem instead. YAP thus will not need the cygwin dll. It instead accesses the system's CRTDLL.DLL C run time library supplied with Win32 platforms through the mingw32 interface. Note that some older WIN95 systems may not have CRTDLL.DLL, in this case it should be sufficient to import the file from a newer WIN95 or WIN98 machine.

You should check the default installation path which is set to /YAP in the standard Makefile. This string will usually be expanded into c:\YAP by Windows.

The cygwin environment does not provide gmp on the MINGW subsystem. You can fetch a dll for the gmp library from http://www.sf.net/projects/mingwrep.

It is also possible to configure YAP to be a part of the cygwin environment. In this case you should use:

 
mkdir cyg
$YAPSRC/configure --enable-max-performance \\
                  --enable-cygwin=yes
make
make install

YAP will then compile using the cygwin library and will be installed in cygwin's /usr/local. You can use YAP from a cygwin console, or as a standalone application as long as it can find cygwin1.dll in its path. Note that you may use to use --enable-depth-limit for Aleph compatibility, and that you may want to be sure that GMP is installed.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3.1 Compiling Under Visual C++

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:

  1. create a project named yapdll using File.New. The project will be a DLL project, initially empty.

    Notice that either the project is named yapdll or you must replace the preprocessors variable YAPDLL_EXPORTS to match your project names in the files YAPInterface.h and c_interface.c.

  2. add all .c files in the $YAPSRC/C directory and in the $YAPSRC\OPTYAP directory to the Project's Source Files (use FileView).
  3. add all .h files in the $YAPSRC/H directory, $YAPSRC\include directory and in the $YAPSRC\OPTYAP subdirectory to the Project's Header Files.
  4. Ideally, you should now use 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.
  5. You may want to go to Build.Set Active Configuration and set Project Type to Release
  6. To use YAP's own include directories you have to set the Project option 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
    
  7. Build: the system should generate an yapdll.dll and an yapdll.lib.
  8. Copy the file 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:

  1. create a second project say wyap with File.New. The project will be a WIN32 console project, initially empty.
  2. add $YAPSRC\console\yap.c to the Source Files.
  3. add $YAPSRC\VC\include\config.h and the files in $YAPSRC\include to the Header Files.
  4. You may want to go to Build.Set Active Configuration and set Project Type to Release.
  5. you will eventually need to bootstrap the system by booting from boot.yap, so write:
     
            -b $YAPSRC\pl\boot.yap
    

    in Project.Project Settings.Debug.Program Arguments.

  6. You need the sockets and yap libraries. Add
     
    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.

  7. set 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
    
  8. Build the system.
  9. Use 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] [ ? ]

1.3.2 Compiling Under SGI's cc

YAP should compile under the Silicon Graphic's cc compiler, although we advise using the GNUCC compiler, if available.

64 bit

Support for 64 bits should work by using (under Bourne shell syntax):

 
CC="cc -64" $YAP_SRC_PATH/configure --...

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2. Running YAP

We next describe how to invoke YAP in Unix systems.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.1 Running YAP Interactively

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:

-?

print a short error message.

-s n

allocate n K bytes for local and global stacks

-h n

allocate n K bytes for heap and auxiliary stacks

-t n

allocate n K bytes for the trail stack

-l YAP_FILE

compile the Prolog file YAP_FILE before entering the top-level.

-L YAP_FILE

compile the Prolog file YAP_FILE and then halt. This option is useful for implementing scripts.

-g Goal

run the goal Goal before top-level. The goal is converted from an atom to a Prolog term.

-z Goal

run the goal Goal as top-level. The goal is converted from an atom to a Prolog term.

-b BOOT_FILE

boot code is in Prolog file BOOT_FILE. The filename must define the predicate '$live'/0.

-c IP_HOST port

connect standard streams to host IP_HOST at port port

filename

restore state saved in the given file

-f

do not consult initial files

-q

do not print informational messages

--

separator for arguments to Prolog code. These arguments are visible through the unix/1 built-in predicate.

Note that YAP will output an error message on the following conditions:

When restoring a saved state, YAP will allocate the same amount of memory as that in use when the state was saved, unless a different amount is specified by flags in the command line. By default, YAP restores the file ‘startup’ from the current directory or from the YAP library.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.2 Running Prolog Files

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
#
# put a dot because of syntax errors .

:- write('Hello World'), nl.

The #! characters specify that the script should call the binary file YAP. Notice that many systems will require the complete path to the YAP binary. The -L flag indicates that YAP should consult the current file when booting and then halt. The remaining arguments are then passed to YAP. Note that YAP will skip the first lines if they start with # (the comment sign for Unix's shell). YAP will consult the file and execute any commands.

A slightly more sophisticated example is:

 
#!/usr/bin/yap -L --
#
# Hello World script file using YAP
# .

:- initialization(main).

main :- write('Hello World'), nl.

The initialization directive tells YAP to execute the goal main after consulting the file. Source code is thus compiled and main executed at the end. The . is useful while debugging the script as a Prolog program: it guarantees that the syntax error will not propagate to the Prolog code.

Notice that the -- is required so that the shell passes the extra arguments to YAP. As an example, consider the following script dump_args:

 
#!/usr/bin/yap -L --
#.

main( [] ).
main( [H|T] ) :-
        write( H ), nl,
        main( T ).

:- unix( argv(AllArgs) ), main( AllArgs ).

If you this run this script with the arguments:

 
./dump_args -s 10000

the script will start an YAP process with stack size 10MB, and the list of arguments to the process will be empty.

Often one wants to run the script as any other program, and for this it is convenient to ignore arguments to YAP. This is possible by using L -- as in the next version of dump_args:

 
#!/usr/bin/yap -L --

main( [] ).
main( [H|T] ) :-
        write( H ), nl,
        main( T ).

:- unix( argv(AllArgs) ), main( AllArgs ).

The -- indicates the next arguments are not for YAP. Instead, they must be sent directly to the argv built-in. Hence, running

 
./dump_args test

will write test on the standard output.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3. Syntax

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.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.1 Syntax of Terms

Below, we describe the syntax of YAP terms from the different classes of tokens defined above. The formalism used will be BNF, extended where necessary with attributes denoting integer precedence or operator type.

 

 term       ---->     subterm(1200)   end_of_term_marker

 subterm(N) ---->     term(M)         [M <= N]

 term(N)    ---->     op(N, fx) subterm(N-1)
             |        op(N, fy) subterm(N)
             |        subterm(N-1) op(N, xfx) subterm(N-1)
             |        subterm(N-1) op(N, xfy) subterm(N)
             |        subterm(N) op(N, yfx) subterm(N-1)
             |        subterm(N-1) op(N, xf)
             |        subterm(N) op(N, yf)

 term(0)   ---->      atom '(' arguments ')'
             |        '(' subterm(1200)  ')'
             |        '{' subterm(1200)  '}'
             |        list
             |        string
             |        number
             |        atom
             |        variable

 arguments ---->      subterm(999)
             |        subterm(999) ',' arguments

 list      ---->      '[]'
             |        '[' list_expr ']'

 list_expr ---->      subterm(999)
             |        subterm(999) list_tail

 list_tail ---->      ',' list_expr
             |        ',..' subterm(999)
             |        '|' subterm(999)

Notes:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2 Prolog Tokens

Prolog tokens are grouped into the following categories:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.1 Numbers

Numbers can be further subdivided into integer and floating-point numbers.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.1.1 Integers

Integer numbers are described by the following regular expression:

 

<integer> := {<digit>+<single-quote>|0{xXo}}<alpha_numeric_char>+

where {...} stands for optionality, + optional repetition (one or more times), <digit> denotes one of the characters 0 ... 9, | denotes or, and <single-quote> denotes the character "'". The digits before the <single-quote> character, when present, form the number basis, that can go from 0, 1 and up to 36. Letters from A to Z are used when the basis is larger than 10.

Note that if no basis is specified then base 10 is assumed. Note also that the last digit of an integer token can not be immediately followed by one of the characters 'e', 'E', or '.'.

Following the ISO standard, YAP also accepts directives of the form 0x to represent numbers in hexadecimal base and of the form 0o to represent numbers in octal base. For usefulness, YAP also accepts directives of the form 0X to represent numbers in hexadecimal base.

Example: the following tokens all denote the same integer

 
10  2'1010  3'101  8'12  16'a  36'a  0xa  0o12

Numbers of the form 0'a are used to represent character constants. So, the following tokens denote the same integer:

 
0'd  100

YAP (version 5.1.3) 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] [ ? ]

3.2.1.2 Floating-point Numbers

Floating-point numbers are described by:

 

   <float> := <digit>+{<dot><digit>+}
               <exponent-marker>{<sign>}<digit>+
            |<digit>+<dot><digit>+
               {<exponent-marker>{<sign>}<digit>+}

where <dot> denotes the decimal-point character '.', <exponent-marker> denotes one of 'e' or 'E', and <sign> denotes one of '+' or '-'.

Examples:

 
10.0   10e3   10e-3   3.1415e+3

Floating-point numbers are represented as a double in the target machine. This is usually a 64-bit number.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.2 Character Strings

Strings are described by the following rules:

 
  string --> '"' string_quoted_characters '"'

  string_quoted_characters --> '"' '"' string_quoted_characters
  string_quoted_characters --> '\'
                          escape_sequence string_quoted_characters
  string_quoted_characters -->
                          string_character string_quoted_characters

  escape_sequence --> 'a' | 'b' | 'r' | 'f' | 't' | 'n' | 'v'
  escape_sequence --> '\' | '"' | ''' | '`'
  escape_sequence --> at_most_3_octal_digit_seq_char '\'
  escape_sequence --> 'x' at_most_2_hexa_digit_seq_char '\'

where string_character in any character except the double quote and escape characters.

Examples:

 
""   "a string"   "a double-quote:""" 

The first string is an empty string, the last string shows the use of double-quoting. The implementation of YAP represents strings as lists of integers. Since YAP 4.3.0 there is no static limit on string size.

Escape sequences can be used to include the non-printable characters a (alert), b (backspace), r (carriage return), f (form feed), t (horizontal tabulation), n (new line), and v (vertical tabulation). Escape sequences also be include the meta-characters \, ", ', and `. Last, one can use escape sequences to include the characters either as an octal or hexadecimal number.

The next examples demonstrates the use of escape sequences in YAP:

 
"\x0c\" "\01\" "\f" "\\" 

The first three examples return a list including only character 12 (form feed). The last example escapes the escape character.

Escape sequences were not available in C-Prolog and in original versions of YAP up to 4.2.0. Escape sequences can be disable by using:

 
:- yap_flag(character_escapes,off).

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.3 Atoms

Atoms are defined by one of the following rules:

 
   atom --> solo-character
   atom --> lower-case-letter name-character*
   atom --> symbol-character+
   atom --> single-quote  single-quote
   atom --> ''' atom_quoted_characters '''


  atom_quoted_characters --> ''' ''' atom_quoted_characters
  atom_quoted_characters --> '\' atom_sequence string_quoted_characters
  atom_quoted_characters --> character string_quoted_characters

where:

 
   <solo-character>     denotes one of:    ! ;
   <symbol-character>   denotes one of:    # & * + - . / : < 
                                           = > ? @ \ ^ ` ~
   <lower-case-letter>  denotes one of:    a...z
   <name-character>     denotes one of:    _ a...z A...Z 0....9
   <single-quote>       denotes:           '

and string_character denotes any character except the double quote and escape characters. Note that escape sequences in strings and atoms follow the same rules.

Examples:

 
a   a12x   '$a'   !   =>  '1 2'

Version 4.2.0 of YAP removed the previous limit of 256 characters on an atom. Size of an atom is now only limited by the space available in the system.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.4 Variables

Variables are described by:

 
   <variable-starter><variable-character>+

where

 
  <variable-starter>   denotes one of:    _ A...Z
  <variable-character> denotes one of:    _ a...z A...Z

If a variable is referred only once in a term, it needs not to be named and one can use the character _ to represent the variable. These variables are known as anonymous variables. Note that different occurrences of _ on the same term represent different anonymous variables.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.5 Punctuation Tokens

Punctuation tokens consist of one of the following characters:

 
 ( ) , [ ] { } |

These characters are used to group terms.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.6 Layout

Any characters with ASCII code less than or equal to 32 appearing before a token are ignored.

All the text appearing in a line after the character % is taken to be a comment and ignored (including %). Comments can also be inserted by using the sequence /* to start the comment and */ to finish it. In the presence of any sequence of comments or layout characters, the YAP parser behaves as if it had found a single blank character. The end of a file also counts as a blank character for this purpose.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3 Wide Character Support

YAP now implements a SWI-Prolog compatible interface to wide characters and the Universal Character Set (UCS). The following text was adapted from the SWI-Prolog manual.

YAP now supports wide characters, characters with character codes above 255 that cannot be represented in a single byte. Universal Character Set (UCS) is the ISO/IEC 10646 standard that specifies a unique 31-bits unsigned integer for any character in any language. It is a superset of 16-bit Unicode, which in turn is a superset of ISO 8859-1 (ISO Latin-1), a superset of US-ASCII. UCS can handle strings holding characters from multiple languages and character classification (uppercase, lowercase, digit, etc.) and operations such as case-conversion are unambiguously defined.

For this reason YAP, following SWI-Prolog, has two representations for atoms. If the text fits in ISO Latin-1, it is represented as an array of 8-bit characters. Otherwise the text is represented as an array of wide chars, which may take 16 or 32 bits. This representational issue is completely transparent to the Prolog user. Users of the foreign language interface sometimes need to be aware of these issues though.

Character coding comes into view when characters of strings need to be read from or written to file or when they have to be communicated to other software components using the foreign language interface. In this section we only deal with I/O through streams, which includes file I/O as well as I/O through network sockets.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3.1 Wide character encodings on streams

Although characters are uniquely coded using the UCS standard internally, streams and files are byte (8-bit) oriented and there are a variety of ways to represent the larger UCS codes in an 8-bit octet stream. The most popular one, especially in the context of the web, is UTF-8. Bytes 0...127 represent simply the corresponding US-ASCII character, while bytes 128...255 are used for multi-byte encoding of characters placed higher in the UCS space. Especially on MS-Windows the 16-bit Unicode standard, represented by pairs of bytes is also popular.

Prolog I/O streams have a property called encoding which specifies the used encoding that influence get_code/2 and put_code/2 as well as all the other text I/O predicates.

The default encoding for files is derived from the Prolog flag encoding, which is initialised from the environment. If the environment variable LANG ends in "UTF-8", this encoding is assumed. Otherwise the default is text and the translation is left to the wide-character functions of the C-library (note that the Prolog native UTF-8 mode is considerably faster than the generic mbrtowc() one). The encoding can be specified explicitly in load_files/2 for loading Prolog source with an alternative encoding, open/4 when opening files or using set_stream/2 on any open stream (not yet implemented). For Prolog source files we also provide the encoding/1 directive that can be used to switch between encodings that are compatible to US-ASCII (ascii, iso_latin_1, utf8 and many locales). For additional information and Unicode resources, please visit http://www.unicode.org/.

YAP currently defines and supports the following encodings:

octet

Default encoding for binary streams. This causes the stream to be read and written fully untranslated.

ascii

7-bit encoding in 8-bit bytes. Equivalent to iso_latin_1, but generates errors and warnings on encountering values above 127.

iso_latin_1

8-bit encoding supporting many western languages. This causes the stream to be read and written fully untranslated.

text

C-library default locale encoding for text files. Files are read and written using the C-library functions mbrtowc() and wcrtomb(). This may be the same as one of the other locales, notably it may be the same as iso_latin_1 for western languages and utf8 in a UTF-8 context.

utf8

Multi-byte encoding of full UCS, compatible to ascii. See above.

unicode_be

Unicode Big Endian. Reads input in pairs of bytes, most significant byte first. Can only represent 16-bit characters.

unicode_le

Unicode Little Endian. Reads input in pairs of bytes, least significant byte first. Can only represent 16-bit characters.

Note that not all encodings can represent all characters. This implies that writing text to a stream may cause errors because the stream cannot represent these characters. The behaviour of a stream on these errors can be controlled using open/4 or set_stream/2 (not implemented). Initially the terminal stream write the characters using Prolog escape sequences while other streams generate an I/O exception.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3.2 BOM: Byte Order Mark

From Wide character encodings on streams, you may have got the impression text-files are complicated. This section deals with a related topic, making live often easier for the user, but providing another worry to the programmer. BOM or Byte Order Marker is a technique for identifying Unicode text-files as well as the encoding they use. Such files start with the Unicode character 0xFEFF, a non-breaking, zero-width space character. This is a pretty unique sequence that is not likely to be the start of a non-Unicode file and uniquely distinguishes the various Unicode file formats. As it is a zero-width blank, it even doesn't produce any output. This solves all problems, or ...

Some formats start of as US-ASCII and may contain some encoding mark to switch to UTF-8, such as the encoding="UTF-8" in an XML header. Such formats often explicitly forbid the the use of a UTF-8 BOM. In other cases there is additional information telling the encoding making the use of a BOM redundant or even illegal.

The BOM is handled by the open/4 predicate. By default, text-files are probed for the BOM when opened for reading. If a BOM is found, the encoding is set accordingly and the property bom(true) is available through stream_property/2. When opening a file for writing, writing a BOM can be requested using the option bom(true) with open/4.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4. Loading Programs

Loading Programs 4.1 Program loading and updating  Program Loading and Updating 4.2 Changing the Compiler's Behavior  Changing the compiler's parameters 4.3 Conditional Compilation  Compiling program fragments 4.4 Saving and Loading Prolog States  Saving and Restoring Programs


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.1 Program loading and updating

consult(+F)

Adds the clauses written in file F or in the list of files F to the program.

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)

Updates the program replacing the previous definitions for the predicates defined in F.

[+F]

The same as consult(F).

[-+F]

The same as reconsult(F)

Example:

 
?- [file1, -file2, -file3, file4].

will consult file1 file4 and reconsult file2 and file3.

compile(+F)

In YAP, the same as reconsult/1.

load_files(+Files, +Options)

General implementation of consult. Execution is controlled by the following flags:

autoload(+Autoload)

SWI-compatible option where if Autoload is true predicates are loaded on first call. Currently not supported.

derived_from(+File)

SWI-compatible option to control make. Currently not supported.

encoding(+Encoding)

Character encoding used in consulting files. Please see section Wide Character Support for supported encodings.

expand(+Bool)

Not yet implemented. In SWI-Prolog, if true, run the filenames through expand_file_name/2 and load the returned files. Default is false, except for consult/1 which is intended for interactive use.

if(+Condition)

Load the file only if the specified Condition is satisfied. The value true the file unconditionally, changed loads the file if it was not loaded before, or has been modified since it was loaded the last time, not_loaded loads the file if it was not loaded before.

imports(+ListOrAll)

If all and the file is a module file, import all public predicates. Otherwise import only the named predicates. Each predicate is referred to as <name>/<arity>. This option has no effect if the file is not a module file.

must_be_module(+Bool)

If true, raise an error if the file is not a module file. Used by use_module/[1,2].

silent(+Bool)

If true, load the file without printing a message. The specified value is the default for all files loaded as a result of loading the specified files.

stream(+Input)

This SWI-Prolog extension compiles the data from the stream Input. If this option is used, Files must be a single atom which is used to identify the source-location of the loaded clauses as well as remove all clauses if the data is re-consulted.

This option is added to allow compiling from non-file locations such as databases, the web, the user (see consult/1) or other servers.

compilation_mode(+Mode)

This extension controls how procedures are compiled. If Mode is compile clauses are compiled and no source code is stored; is assert_all clauses are asserted into the data-base.

ensure_loaded(+F) [ISO]

When the files specified by F are module files, 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]

The include directive includes the text files or sequence of text files specified by F into the file being currently consulted.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.2 Changing the Compiler's Behavior

This section presents a set of built-ins predicates designed to set the environment for the compiler.

source_mode(-O,+N)

The state of source mode can either be on or off. When the source mode is on, all clauses are kept both as compiled code and in a "hidden" database. O is unified with the previous state and the mode is set according to N.

source

After executing this goal, YAP keeps information on the source of the predicates that will be consulted. This enables the use of 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

The opposite to source.

The same as source_mode(_,off).

compile_expressions

After a call to this predicate, arithmetical expressions will be compiled. (see example below). This is the default behavior.

do_not_compile_expressions

After a call to this predicate, arithmetical expressions will not be compiled.

 
?- source, do_not_compile_expressions.
yes
?- [user].
| p(X) :- X is 2 * (3 + 8).
| :- end_of_file.
?- compile_expressions.
yes
?- [user].
| q(X) :- X is 2 * (3 + 8).
| :- end_of_file.
:- listing.

p(A):-
      A is 2 * (3 + 8).

q(A):-
      A is 22.
hide(+Atom)

Make atom Atom invisible.

unhide(+Atom)

Make hidden atom Atom visible.

hide_predicate(+Pred)

Make predicate Pred invisible to current_predicate/2, listing, and friends.

expand_exprs(-O,+N)

Puts YAP in state 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)

Unifies D with the current directory search-path of YAP. Note that this search-path is only used by YAP to find the files for consult/1, reconsult/1 and restore/1 and should not be taken for the system search path.

add_to_path(+D)

Adds D to the end of YAP's directory search path.

add_to_path(+D,+N)

Inserts D in the position, of the directory search path of YAP, specified by N. N must be either of first or last.

remove_from_path(+D)

Remove D from YAP's directory search path.

style_check(+X)

Turns on style checking according to the attribute specified by X, which must be one of the following:

single_var

Checks single occurrences of named variables in a clause.

discontiguous

Checks non-contiguous clauses for the same predicate in a file.

multiple

Checks the presence of clauses for the same predicate in more than one file when the predicate has not been declared as multifile

all

Performs style checking for all the cases mentioned above.

By default, style checking is disabled in YAP unless we are in 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)

Turns off style checking according to the attribute specified by X, which has the same meaning as in style_check/1.

The no_style_check/1 built-in is now deprecated. Please use the set_prolog_flag/1 instead.

multifile P [ISO]

Instructs the compiler about the declaration of a predicate P in more than one file. It must appear in the first of the loaded files where the predicate is declared, and before declaration of any of its clauses.

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]

The compiler will execute goals G after consulting the current file.

library_directory(+D)

Succeeds when D is a current library directory name. Library directories are the places where files specified in the form library(File) are searched by the predicates consult/1, reconsult/1, use_module/1 or ensure_loaded/1.

file_search_path(+NAME,-DIRECTORY)

Allows writing file names as compound terms. The NAME and DIRECTORY must be atoms. The predicate may generate multiple solutions. The predicate is originally defined as follows:

 
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)

Succeeds when D is a current library directory name. Library directories are the places where files specified in the form library(File) are searched by the predicates consult/1, reconsult/1, use_module/1 or ensure_loaded/1.

prolog_file_name(+Name,-FullPath)

Unify FullPath with the absolute path YAP would use to consult file Name.

public P [ISO]

Instructs the compiler that the source of a predicate of a list of predicates P must be kept. This source is then accessible through the 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] [ ? ]

4.3 Conditional Compilation

Conditional compilation builds on the same principle as term_expansion/2, goal_expansion/2 and the expansion of grammar rules to compile sections of the source-code conditionally. One of the reasons for introducing conditional compilation is to simplify writing portable code.

Note that these directives can only be appear as separate terms in the input. Typical usage scenarios include:

if(+Goal)

Compile subsequent code only if Goal succeeds. For enhanced portability, Goal is processed by expand_goal/2 before execution. If an error occurs, the error is printed and processing proceeds as if Goal has failed.

else

Start `else' branch.

endif

End of conditional compilation.

elif(+Goal)

Equivalent to :- else. :-if(Goal) ... :- endif. In a sequence as below, the section below the first matching elif is processed, If no test succeeds the else branch is processed.

 
:- if(test1).
section_1.
:- elif(test2).
section_2.
:- elif(test3).
section_3.
:- else.
section_else.
:- endif.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.4 Saving and Loading Prolog States

save(+F)

Saves an image of the current state of YAP in file F. From YAP4.1.3 onwards, YAP saved states are executable files in the Unix ports.

save(+F,-OUT)

Saves an image of the current state of YAP in file F. From YAP4.1.3 onwards, YAP saved states are executable files in the Unix ports.

Unify OUT with 1 when saving the file and OUT with 0 when restoring the saved state.

save_program(+F)

Saves an image of the current state of the YAP database in file F.

save_program(+F, :G)

Saves an image of the current state of the YAP database in file F, and guarantee that execution of the restored code will start by trying goal G.

restore(+F)

Restores a previously saved state of YAP from file 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] [ ? ]

5. The Module System

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.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1 Module Concepts

The YAP module system applies to predicates. All predicates belong to a module. System predicates belong to the module primitives, and by default new predicates belong to the module user. Predicates from the module primitives are automatically visible to every module.

Every predicate must belong to a module. This module is called its source module.

By default, the source module for a clause occurring in a source file with a module declaration is the declared module. For goals typed in a source file without module declarations, their module is the module the file is being loaded into. If no module declarations exist, this is the current type-in module. The default type-in module is user, but one can set the current module by using the built-in module/1.

Note that in this module system one can explicitly specify the source mode for a clause by prefixing a clause with its module, say:

 
user:(a :- b).

In fact, to specify the source module for a clause it is sufficient to specify the source mode for the clause's head:

 
user:a :- b.

The rules for goals are similar. If a goal appears in a text file with a module declaration, the goal's source module is the declared module. Otherwise, it is the module the file is being loaded into or the type-in module.

One can override this rule by prefixing a goal with the module it is supposed to be executed into, say:

 
nasa:launch(apollo,13).

will execute the goal launch(apollo,13) as if the current source module was nasa.

Note that this rule breaks encapsulation and should be used with care.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.2 Defining a New Module

A new module is defined by a module declaration:

module(+M,+L)

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 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)

Similar to 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

the filename for a module to import into the current module.

library(file)

a library file to import into the current module.

hide(Opt)

if Opt is false, keep source code for current module, if true, disable.

module(+M)

Defines M to be the current working or type-in module. All files which are not binded to a module are assumed to belong to the working module (also referred to as type-in module). To compile a non-module file into a module which is not the working one, prefix the file name with the module name, in the form Module:File, when loading the file.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.3 Using Modules

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)

Loads the files specified by F, importing all their public predicates. Predicate name clashes are resolved by asking the user about importing or not the predicate. A warning is displayed when F is not a module file.

use_module(+F,+L)

Loads the files specified by F, importing the predicates specified in the list L. Predicate name clashes are resolved by asking the user about importing or not the predicate. A warning is displayed when F is not a module file.

use_module(?M,?F,+L)

If module M has been defined, import the procedures in L to the current module. Otherwise, load the files specified by F, importing the predicates specified in the list L.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.4 Meta-Predicates in Modules

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)

...

The expected behavior for this procedure is to execute goal G within the current module, that is, within 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_predicate/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

Each Gi is a mode specification. For example, a declaration for 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)

...

You can avoid goal expansion by using module_transparent/1.

module_transparent +Preds

Preds is a comma separated list of name/arity pairs (like dynamic/1). Each goal associated with a transparent declared predicate will inherit the context module from its parent goal.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.5 Re-Exporting Predicates From Other Modules

It is sometimes convenient to re-export predicates originally defined in a different module. This is often useful if you are adding to the functionality of a module, or if you are composing a large module with several small modules. The following declarations can be used for that purpose:

reexport(+F)

Export all predicates defined in file F as if they were defined in the current module.

reexport(+F,+Decls)

Export predicates defined in file F according to Decls. The declarations may be of the form:

Re-exporting predicates must be used with some care. Please, take into account the following observations:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6. Built-In Predicates

Built-ins, 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 Message Handling  Message Handling in YAP 6.4 Predicates on terms  Predicates on Terms 6.5 Predicates on Atoms  Manipulating Atoms 6.6 Predicates on Characters  Manipulating Characters 6.7 Comparing Terms  Comparison of Terms 6.8 Arithmetic  Arithmetic in YAP 6.9 I/O Predicates  Input/Output with YAP 6.10 Using the Clausal Data Base  Modifying Prolog's Database 6.13 Collecting Solutions to a Goal  Finding All Possible Solutions 6.14 Grammar Rules  Grammar Rules 6.21 Predicate Information  Predicate Information 6.15 Access to Operating System Functionality  Access to Operating System Functionality 6.16 Term Modification  Updating Prolog Terms 6.17 Global Variables  Manipulating Global Variables 6.18 Profiling Prolog Programs  Profiling Prolog Execution 6.19 Counting Calls  Limiting the Maximum Number of Reductions 6.20 Arrays  Supporting Global and Local Arrays 6.21 Predicate Information  Information on Predicates 6.22 Miscellaneous  Miscellaneous Predicates


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.1 Control Predicates

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]

Conjunction of goals (and).

Example:

 
 p(X) :- q(X), r(X).

should be read as "p(X) if q(X) and r(X)".

+P ; +Q [ISO]

Disjunction of goals (or).

Example:

 
 p(X) :- q(X); r(X).

should be read as "p(X) if q(X) or r(X)".

true [ISO]

Succeeds once.

fail [ISO]

Fails always.

false

The same as fail

! [ISO]

Read as "cut". Cuts any choices taken in the current procedure. When first found "cut" succeeds as a goal, but if backtracking should later return to it, the parent goal (the one which matches the head of the clause containing the "cut", causing the clause activation) will fail. This is an extra-logical predicate and cannot be explained in terms of the declarative semantics of Prolog.

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]

Goal P is not provable. The execution of this predicate fails if and only if the goal P finitely succeeds. It is not a true logical negation, which is impossible in standard Prolog, but "negation-by-failure".

This predicate might be defined as:

 
 \+(P) :- P, !, fail.
 \+(_).

if P did not include "cuts".

not +P

Goal P is not provable. The same as '\+ 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]

Read as "if-then-else" or "commit". This operator is similar to the conditional operator of imperative languages and can be used alone or with an else part as follows:

+P -> +Q

"if P then Q".

+P -> +Q; +R

"if P then Q else R".

These two predicates could be defined respectively in Prolog as:

 
 (P -> Q) :- P, !, Q.

and

 
 (P -> Q; R) :- P, !, Q.
 (P -> Q; R) :- R.

if there were no "cuts" in P, Q and R.

Note that the commit operator works by "cutting" any alternative solutions of P.

Note also that you can use chains of commit operators like:

 
    P -> Q ; R -> S ; T.

Note that (->)/2 does not affect the scope of cuts in its arguments.

+Conditon *-> +Action ; +Else

This construct implements the so-called soft-cut. The control is defined as follows: If Condition succeeds at least once, the semantics is the same as (Condition, Action). If Condition does not succeed, the semantics is that of (\+ Condition, Else). In other words, If Condition succeeds at least once, simply behave as the conjunction of Condition and Action, otherwise execute Else.

The construct A *-> B, i.e. without an Else branch, is translated as the normal conjunction A, B.

repeat [ISO]

Succeeds repeatedly.

In the next example, repeat is used as an efficient way to implement a loop. The next example reads all terms in a file:

 
 a :- repeat, read(X), write(X), nl, X=end_of_file, !.

the loop is effectively terminated by the cut-goal, when the test-goal X=end succeeds. While the test fails, the goals read(X), write(X), and nl are executed repeatedly, because backtracking is caught by the repeat goal.

The built-in repeat/1 could be defined in Prolog by:

 
 repeat.
 repeat :- repeat.
call(+P) [ISO]

If P is instantiated to an atom or a compound term, the goal 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)

The same as call/1.

call_with_args(+Name,...,?Ai,...)

Meta-call where Name is the name of the procedure to be called and the Ai are the arguments. The number of arguments varies between 0 and 10.

If Name is a complex term, then call_with_args/n behaves as call/n:

 
call(p(X1,...,Xm), Y1,...,Yn) :- p(X1,...,Xm,Y1,...,Yn).
+P

The same as 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.

is converted to:

 
 a(X) :- call(X).
if(?G,?H,?I)

Call goal H once per each solution of goal H. If goal H has no solutions, call goal I.

The built-in if/3 is similar to ->/3, with the difference that it will backtrack over the test goal. Consider the following small data-base:

 
a(1).        b(a).          c(x).
a(2).        b(b).          c(y).

Execution of an if/3 query will proceed as follows:

 
   ?- if(a(X),b(Y),c(Z)).

X = 1,
Y = a ? ;

X = 1,
Y = b ? ;

X = 2,
Y = a ? ;

X = 2,
Y = b ? ;

no

The system will backtrack over the two solutions for a/1 and the two solutions for b/1, generating four solutions.

Cuts are allowed inside the first goal G, but they will only prune over G.

If you want G to be deterministic you should use if-then-else, as it is both more efficient and more portable.

once(:G) [ISO]

Execute the goal G only once. The predicate is defined by:

 
 once(G) :- call(G), !.

Note that cuts inside once/1 can only cut the other goals inside once/1.

forall(:Cond,:Action)

For all alternative bindings of Cond Action can be proven. The example verifies that all arithmetic statements in the list L are correct. It does not say which is wrong if one proves wrong.

 
?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]),
                 Result =:= Formula).
ignore(:Goal)

Calls Goal as once/1, but succeeds, regardless of whether Goal succeeded or not. Defined as:

 
ignore(Goal) :-
        Goal, !.
ignore(_).
abort

Abandons the execution of the current goal and returns to top level. All break levels (see break/0 below) are terminated. It is mainly used during debugging or after a serious execution error, to return to the top-level.

break

Suspends the execution of the current goal and creates a new execution level similar to the top level, displaying the following message:

 
 [ Break (level <number>) ]

telling the depth of the break level just entered. To return to the previous level just type the end-of-file character or call the end_of_file predicate. This predicate is especially useful during debugging.

halt [ISO]

Halts Prolog, and exits to the calling application. In YAP, halt/0 returns the exit code 0.

halt(+ I) [ISO]

Halts Prolog, and exits to the calling application returning the code given by the integer I.

catch(+Goal,+Exception,+Action) [ISO]

The goal 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]

The goal 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

The goal garbage_collect forces a garbage collection.

garbage_collect_atoms

The goal garbage_collect forces a garbage collection of the atoms in the data-base. Currently, only atoms are recovered.

gc

The goal gc enables garbage collection. The same as yap_flag(gc,on).

nogc

The goal nogc disables garbage collection. The same as yap_flag(gc,off).

grow_heap(+Size)

Increase heap size Size kilobytes.

grow_stack(+Size)

Increase stack size Size kilobytes.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.2 Handling Undefined Procedures

A predicate in a module is said to be undefined if there are no clauses defining the predicate, and if the predicate has not been declared to be dynamic. What YAP does when trying to execute undefined predicates can be specified in three different ways:

In more detail:

unknown(-O,+N)

Specifies an handler to be called is a program tries to call an undefined static procedure P.

The arity of N may be zero or one. If the arity is 0, the new action must be one of fail, warning, or error. If the arity is 1, P is an user-defined handler and at run-time, the argument to the handler P will be unified with the undefined goal. Note that N must be defined prior to calling unknown/2, and that the single argument to N must be unbound.

In YAP, the default action is to fail (note that in the ISO Prolog standard the default action is error).

After defining undefined/1 by:

 
undefined(A) :- format('Undefined predicate: ~w~n',[A]), fail.

and executing the goal:

 
unknown(U,undefined(X)).

a call to a predicate for which no clauses were defined will result in the output of a message of the form:

 
Undefined predicate: user:xyz(A1,A2)

followed by the failure of that call.

yap_flag(unknown,+SPEC)

Alternatively, one can use 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)

The user may also define clauses for user:unknown_predicate_handler/3 hook predicate. This user-defined procedure is called before any system processing for the undefined procedure, with the first argument G set to the current goal, and the second M set to the current module. The predicate G will be called from within the user module.

If user:unknown_predicate_handler/3 succeeds, the system will execute NG. If user:unknown_predicate_handler/3 fails, the system will execute default action as specified by unknown/2.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3 Message Handling

The interaction between YAP and the user relies on YAP's ability to portray messages. These messages range from prompts to error information. All message processing is performed through the builtin print_message/2, in two steps:

The first argument to print_message/2 specifies the importance of the message. The options are:

error

error handling

warning

compilation and run-time warnings,

informational

generic informational messages

help

help messages (not currently implemented in YAP)

query

query used in query processing (not currently implemented in YAP)

silent

messages that do not produce output but that can be intercepted by hooks.

The next table shows the main predicates and hooks associated to message handling in YAP:

print_message(+Kind, Term)

The predicate print_message/2 is used to print messages, notably from exceptions in a human-readable format. Kind is one of informational, banner, warning, error, help or silent. A human-readable message is printed to the stream user_error.

If the Prolog flag verbose is silent, messages with Kind informational, or banner are treated as silent.

This predicate first translates the Term into a list of `message lines' (see print_message_lines/3 for details). Next it will call the hook message_hook/3 to allow the user intercepting the message. If message_hook/3 fails it will print the message unless Kind is silent.

If you need to report errors from your own predicates, we advise you to stick to the existing error terms if you can; but should you need to invent new ones, you can define corresponding error messages by asserting clauses for prolog:message/2. You will need to declare the predicate as multifile.

print_message_lines(+Stream, +Prefix, +Lines)

Print a message (see print_message/2) that has been translated to a list of message elements. The elements of this list are:

<Format>-<Args>

Where Format is an atom and Args is a list of format argument. Handed to format/3.

flush

If this appears as the last element, Stream is flushed (see flush_output/1) and no final newline is generated.

at_same_line

If this appears as first element, no prefix is printed for the first line and the line-position is not forced to 0 (see format/1, ~N).

<Format>

Handed to format/3 as format(Stream, Format, []).

nl

A new line is started and if the message is not complete the Prefix is printed too.

user:message_hook(+Term, +Kind, +Lines)

Hook predicate that may be define in the module user to intercept messages from print_message/2. Term and Kind are the same as passed to print_message/2. Lines is a list of format statements as described with print_message_lines/3.

This predicate should be defined dynamic and multifile to allow other modules defining clauses for it too.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4 Predicates on terms

var(T) [ISO]

Succeeds if T is currently a free variable, otherwise fails.

atom(T) [ISO]

Succeeds if and only if T is currently instantiated to an atom.

atomic(T) [ISO]

Checks whether T is an atomic symbol (atom or number).

compound(T) [ISO]

Checks whether T is a compound term.

db_reference(T)

Checks whether T is a database reference.

float(T) [ISO]

Checks whether T is a floating point number.

integer(T) [ISO]

Succeeds if and only if T is currently instantiated to an integer.

nonvar(T) [ISO]

The opposite of var(T).

number(T) [ISO]

Checks whether T is an integer or a float.

primitive(T)

Checks whether T is an atomic term or a database reference.

simple(T)

Checks whether T is unbound, an atom, or a number.

callable(T)

Checks whether T is a callable term, that is, an atom or a compound term.

numbervars(T,+N1,-Nn)

Instantiates each variable in term T to a term of the form: '$VAR'(I), with I increasing from N1 to Nn.

ground(T)

Succeeds if there are no free variables in the term T.

arg(+N,+T,A) [ISO]

Succeeds if the argument N of the term T unifies with A. The arguments are numbered from 1 to the arity of the term.

The current version will generate an error if T or N are unbound, if T is not a compound term, of if N is not a positive integer. Note that previous versions of YAP would fail silently under these errors.

functor(T,F,N) [ISO]

The top functor of term T is named F and has arity 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]

The list L is built with the functor and arguments of the term T. If T is instantiated to a variable, then L must be instantiated either to a list whose head is an atom, or to a list consisting of just a number.

X = Y [ISO]

Tries to unify terms X and Y.

X \= Y [ISO]

Succeeds if terms X and Y are not unifiable.

unify_with_occurs_check(?T1,?T2) [ISO]

Obtain the most general unifier of terms T1 and T2, if there is one.

This predicate implements the full unification algorithm. An example:n

 
unify_with_occurs_check(a(X,b,Z),a(X,A,f(B)).

will succeed with the bindings A = b and Z = f(B). On the other hand:

 
unify_with_occurs_check(a(X,b,Z),a(X,A,f(Z)).

would fail, because Z is not unifiable with f(Z). Note that (=)/2 would succeed for the previous examples, giving the following bindings A = b and Z = f(Z).

copy_term(?TI,-TF) [ISO]

Term TF is a variant of the original term TI, such that for each variable V in the term TI there is a new variable V' in term TF. Notice that:

If you do not want any sharing to occur please use duplicate_term/2.

duplicate_term(?TI,-TF) [ISO]

Term TF is a variant of the original term TI, such that for each variable V in the term TI there is a new variable V' in term TF, and the two terms do not share any structure. All suspended goals and attributes for attributed variables in TI are also duplicated.

Also refer to copy_term/2.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.5 Predicates on Atoms

The following predicates are used to manipulate atoms:

name(A,L)

The predicate holds when at least one of the arguments is ground (otherwise, an error message will be displayed). The argument A will be unified with an atomic symbol and L with the list of the ASCII codes for the characters of the external representation of A.

 
 name(yap,L).

will return:

 
 L = [121,97,112].

and

 
 name(3,L).

will return:

 
 L = [51].
atom_chars(?A,?L) [ISO]

The predicate holds when at least one of the arguments is ground (otherwise, an error message will be displayed). The argument A must be unifiable with an atom, and the argument L with the list of the ASCII codes for the characters of the external representation of A.

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]

The predicate holds when at least one of the arguments is ground (otherwise, an error message will be displayed). The argument A will be unified with an atom and L with the list of the ASCII codes for the characters of the external representation of A.

atom_concat(+As,?A)

The predicate holds when the first argument is a list of atoms, and the second unifies with the atom obtained by concatenating all the atoms in the first list.

atomic_concat(+As,?A)

The predicate holds when the first argument is a list of atoms, and the second unifies with the atom obtained by concatenating all the atomic terms in the first list. The first argument thus may contain atoms or numbers.

atom_length(+A,?I) [ISO]

The predicate holds when the first argument is an atom, and the second unifies with the number of characters forming that atom.

atom_concat(?A1,?A2,?A12) [ISO]

The predicate holds when the third argument unifies with an atom, and the first and second unify with atoms such that their representations concatenated are the representation for A12.

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]

The predicate holds when at least one of the arguments is ground (otherwise, an error message will be displayed). The argument A will be unified with a number and L with the list of the ASCII codes for the characters of the external representation of A.

atom_number(?Atom,?Number)

The predicate holds when at least one of the arguments is ground (otherwise, an error message will be displayed). If the argument Atom is an atom, Number must be the number corresponding to the characters in Atom, otherwise the characters in Atom must encode a number Number.

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.

sub_atom(+A,?Bef, ?Size, ?After, ?At_out) [ISO]

True when A and At_out are atoms such that the name of At_out has size Size and is a sub-string of the name of A, such that Bef is the number of characters before and After the number of characters afterwards.

Note that A must always be known, but At_out can be unbound when calling this built-in. If all the arguments for sub_atom/5 but A are unbound, the built-in will backtrack through all possible sub-strings of A.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.6 Predicates on Characters

The following predicates are used to manipulate characters:

char_code(?A,?I) [ISO]

The built-in succeeds with A bound to character represented as an atom, and I bound to the character code represented as an integer. At least, one of either A or I must be bound before the call.

char_type(?Char, ?Type)

Tests or generates alternative Types or Chars. The character-types are inspired by the standard C <ctype.h> primitives.

alnum

Char is a letter (upper- or lowercase) or digit.

alpha

Char is a letter (upper- or lowercase).

csym

Char is a letter (upper- or lowercase), digit or the underscore (_). These are valid C- and Prolog symbol characters.

csymf

Char is a letter (upper- or lowercase) or the underscore (_). These are valid first characters for C- and Prolog symbols

ascii

Char is a 7-bits ASCII character (0..127).

white

Char is a space or tab. E.i. white space inside a line.

cntrl

Char is an ASCII control-character (0..31).

digit

Char is a digit.

digit(Weigth)

Char is a digit with value Weigth. I.e. char_type(X, digit(6)) yields X = '6'. Useful for parsing numbers.

xdigit(Weigth)

Char is a haxe-decimal digit with value Weigth. I.e. char_type(a, xdigit(X) yields X = '10'. Useful for parsing numbers.

graph

Char produces a visible mark on a page when printed. Note that the space is not included!

lower

Char is a lower-case letter.

lower(Upper)

Char is a lower-case version of Upper. Only true if Char is lowercase and Upper uppercase.

to_lower(Upper)

Char is a lower-case version of Upper. For non-letters, or letter without case, Char and Lower are the same. See also upcase_atom/2 and downcase_atom/2.

upper

Char is an upper-case letter.

upper(Lower)

Char is an upper-case version of Lower. Only true if Char is uppercase and Lower lowercase.

to_upper(Lower)

Char is an upper-case version of Lower. For non-letters, or letter without case, Char and Lower are the same. See also upcase_atom/2 and downcase_atom/2.

punct

Char is a punctuation character. This is a graph character that is not a letter or digit.

space

Char is some form of layout character (tab, vertical-tab, newline, etc.).

end_of_file

Char is -1.

end_of_line

Char ends a line (ASCII: 10..13).

newline

Char is a the newline character (10).

period

Char counts as the end of a sentence (.,!,?).

quote

Char is a quote-character (", ', `).

paren(Close)

Char is an open-parenthesis and Close is the corresponding close-parenthesis.

code_type(?Code, ?Type)

As char_type/2, but uses character-codes rather than one-character atoms. Please note that both predicates are as flexible as possible. They handle either representation if the argument is instantiated and only will instantiate with an integer code or one-character atom depending of the version used. See also the prolog-flag double_quotes and the built-in predicates atom_chars/2 and atom_codes/2.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.7 Comparing Terms

The following predicates are used to compare and order terms, using the standard ordering:

compare(C,X,Y)

As a result of comparing X and Y, C may take one of the following values:

X == Y [ISO]

Succeeds if terms X and Y are strictly identical. The difference between this predicate and =/2 is that, if one of the arguments is a free variable, it only succeeds when they have already been unified.

 
?- X == Y.

fails, but,

 
?- X = Y, X == Y.

succeeds.

 
?- X == 2.

fails, but,

 
?- X = 2, X == 2.

succeeds.

X \== Y [ISO]

Terms X and Y are not strictly identical.

X @< Y [ISO]

Term X precedes term Y in the standard order.

X @=< Y [ISO]

Term X does not follow term Y in the standard order.

X @> Y [ISO]

Term X follows term Y in the standard order.

X @>= Y [ISO]

Term X does not precede term Y in the standard order.

sort(+L,-S)

Unifies S with the list obtained by sorting L and merging identical (in the sense of ==) elements.

keysort(+L,S)

Assuming L is a list of the form 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).

would return:

 
S = [1-b,1-a,1-b,2-c,3-a]
length(?L,?S)

Unify the well-defined list L with its length. The procedure can be used to find the length of a pre-defined list, or to build a list of length S.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.8 Arithmetic

Arithmetic expressions in YAP may use the following operators or evaluable predicates:

+X

The value of X itself.

-X [ISO]

Symmetric value.

X+Y [ISO]

Sum.

X-Y [ISO]

Difference.

X*Y [ISO]

Product.

X/Y [ISO]

Quotient.

X//Y [ISO]

Integer quotient.

X mod Y [ISO]

Integer remainder.

X rem Y

Integer remainder, the same as mod.

exp(X) [ISO]

Natural exponential.

log(X) [ISO]

Natural logarithm.

log10(X)

Decimal logarithm.

sqrt(X) [ISO]

Square root.

sin(X) [ISO]

Sine.

cos(X) [ISO]

Cosine.

tan(X)

Tangent.

asin(X)

Arc sine.

acos(X)

Arc cosine.

atan(X) [ISO]

Arc tangent.

atan2(X)

Four-quadrant arc tangent.

sinh(X)

Hyperbolic sine.

cosh(X)

Hyperbolic cosine.

tanh(X)

Hyperbolic tangent.

asinh(X)

Hyperbolic arc sine.

acosh(X)

Hyperbolic arc cosine.

atanh(X)

Hyperbolic arc tangent.

integer(X)

If X evaluates to a float, the integer between the value of X and 0 closest to the value of X, else if X evaluates to an integer, the value of X.

float(X) [ISO]

If X evaluates to an integer, the corresponding float, else the float itself.

float_fractional_part(X) [ISO]

The fractional part of the floating point number X, or 0.0 if X is an integer. In the iso language mode, X must be an integer.

float_integer_part(X) [ISO]

The float giving the integer part of the floating point number X, or X if X is an integer. In the iso language mode, X must be an integer.

abs(X) [ISO]

The absolute value of X.

ceiling(X) [ISO]

The float that is the smallest integral value not smaller than X.

In iso language mode the argument must be a floating point-number and the result is an integer.

floor(X) [ISO]

The float that is the greatest integral value not greater than X.

In iso language mode the argument must be a floating point-number and the result is an integer.

round(X) [ISO]

The nearest integral value to X. If X is equidistant to two integers, it will be rounded to the closest even integral value.

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]

Return 1 if the X evaluates to a positive integer, 0 it if evaluates to 0, and -1 if it evaluates to a negative integer. If X evaluates to a floating-point number return 1.0 for a positive X, 0.0 for 0.0, and -1.0 otherwise.

truncate(X)

The float that is the integral value between X and 0 closest to X.

max(X,Y)

The greater value of X and Y.

min(X,Y)

The lesser value of X and Y.

X ^ Y

X raised to the power of Y, (from the C-Prolog syntax).

exp(X,Y)

X raised to the power of Y, (from the Quintus Prolog syntax).

X ** Y [ISO]

X raised to the power of Y (from ISO).

X /\ Y [ISO]

Integer bitwise conjunction.

X \/ Y [ISO]

Integer bitwise disjunction.

X # Y [ISO]

Integer bitwise exclusive disjunction.

X << Y

Integer bitwise left logical shift of X by Y places.

X >> Y [ISO]

Integer bitwise right logical shift of X by Y places.

\ X [ISO]

Integer bitwise negation.

gcd(X,Y)

The greatest common divisor of the two integers X and Y.

msb(X)

The most significant bit of the integer X.

[X]

Evaluates to X for expression X. Useful because character strings in Prolog are lists of character codes.

 
X is Y*10+C-"0"

is the same as

 
X is Y*10+C-[48].

which would be evaluated as:

 
X is Y*10+C-48.

Besides numbers and the arithmetic operators described above, certain atoms have a special meaning when present in arithmetic expressions:

pi

The value of pi, the ratio of a circle's circumference to its diameter.

e

The base of the natural logarithms.

inf

Infinity according to the IEEE Floating-Point standard. Note that evaluating this term will generate a domain error in the iso language mode.

nan

Not-a-number according to the IEEE Floating-Point standard. Note that evaluating this term will generate a domain error in the iso language mode.

cputime

CPU time in seconds, since YAP was invoked.

heapused

Heap space used, in bytes.

local

Local stack in use, in bytes.

global

Global stack in use, in bytes.

random

A "random" floating point number between 0 and 1.

The primitive YAP predicates involving arithmetic expressions are:

X is +Y [2]

This predicate succeeds iff the result of evaluating the expression Y unifies with X. This is the predicate normally used to perform evaluation of arithmetic expressions:

 
X is 2+3*4

succeeds with X = 14.

+X < +Y [ISO]

The value of the expression X is less than the value of expression Y.

+X =< +Y [ISO]

The value of the expression X is less than or equal to the value of expression Y.

+X > +Y [ISO]

The value of the expression X is greater than the value of expression Y.

+X >= +Y [ISO]

The value of the expression X is greater than or equal to the value of expression Y.

+X =:= +Y [ISO]

The value of the expression X is equal to the value of expression Y.

+X =\= +Y [ISO]

The value of the expression X is different from the value of expression Y.

srandom(+X)

Use the argument X as a new seed for YAP's random number generator. The argument should be an integer, but floats are acceptable.

Notes:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.9 I/O Predicates

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.9.1 Handling Streams and Files  Handling Streams and Files 6.9.2 Handling Streams and Files  C-Prolog Compatible File Handling 6.9.3 Handling Input/Output of Terms  Input/Output of terms 6.9.4 Handling Input/Output of Characters  Input/Output of Characters 6.9.5 Input/Output Predicates applied to Streams  Input/Output using Streams 6.9.6 Compatible C-Prolog predicates for Terminal I/O  C-Prolog compatible Character I/O to terminal 6.9.7 Controlling Input/Output  Controlling your Input/Output 6.9.8 Using Sockets From YAP  Using Sockets from YAP


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.9.1 Handling Streams and Files

open(+F,+M,-S) [ISO]

Opens the file with name F in mode M ('read', 'write' or 'append'), returning S unified with the stream name.

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]

Opens the file with name F in mode M ('read', 'write' or 'append'), returning S unified with the stream name, and following these options:

type(+T)

Specify whether the stream is a text stream (default), or a binary stream.

reposition(+Bool)

Specify whether it is possible to reposition the stream (true), or not (false). By default, YAP enables repositioning for all files, except terminal files and sockets.

eof_action(+Action)

Specify the action to take if attempting to input characters from a stream where we have previously found an 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)

Specify an alias to the stream. The alias Name must be an atom. The alias can be used instead of the stream descriptor for every operation concerning the stream.

The operation will fail and give an error if the alias name is already in use. YAP allows several aliases for the same file, but only one is returned by stream_property/2

bom(+Bool)

If present and true, a BOM (Byte Order Mark) was detected while opening the file for reading or a BOM was written while opening the stream. See BOM: Byte Order Mark for details.

encoding(+Encoding)

Set the encoding used for text. See Wide Character Support for an overview of wide character and encoding issues.

representation_errors(+Mode)

Change the behaviour when writing characters to the stream that cannot be represented by the encoding. The behaviour is one of error (throw and I/O error exception), prolog (write \u...\ escape code or xml (write &#...; XML character entity). The initial mode is prolog for the user streams and error for all other streams. See also Wide Character Support.

expand_filename(+Mode)

If Mode is true then do filename expansion, then ask Prolog to do file name expansion before actually trying to opening the file: this includes processing ~ characters and processing $ environment variables at the beginning of the file. Otherwise, just try to open the file using the given name.

The default behavior is given by the Prolog flag open_expands_filename.

close(+S) [ISO]

Closes the stream S. If S does not stand for a stream currently opened an error is reported. The streams user_input, user_output, and user_error can never be closed.

close(+S,+O) [ISO]

Closes the stream S, following options O.

The only valid options are force(true) and force(false). YAP currently ignores these options.

time_file(+File,-Time)

Unify the last modification time of File with Time. Time is a floating point number expressing the seconds elapsed since Jan 1, 1970.

absolute_file_name(+Name,+Options, -FullPath)
absolute_file_name(+Name, -FullPath,+Options)

Converts the given file specification into an absolute path. Option is a list of options to guide the conversion:

extensions(+ListOfExtensions)

List of file-extensions to try. Default is ‘''’. For each extension, absolute_file_name/3 will first add the extension and then verify the conditions imposed by the other options. If the condition fails, the next extension of the list is tried. Extensions may be specified both as .ext or plain ext.

relative_to(+FileOrDir)

Resolve the path relative to the given directory or directory the holding the given file. Without this option, paths are resolved relative to the working directory (see working_directory/2) or, if Spec is atomic and absolute_file_name/[2,3] is executed in a directive, it uses the current source-file as reference.

access(+Mode)

Imposes the condition access_file(File, Mode). Mode is on of read, write, append, exist or none. See also access_file/2.

file_type(+Type)

Defines extensions. Current mapping: txt implies [''], prolog implies ['.pl', ''], executable implies ['.so', ''], qlf implies ['.qlf', ''] and directory implies ['']. The file-type source is an alias for prolog for compatibility to SICStus Prolog. See also prolog_file_type/2.

file_errors(fail/error)

If error (default), throw and existence_error exception if the file cannot be found. If fail, stay silent.

solutions(first/all)

If first (default), the predicates leaves no choice-point. Otherwise a choice-point will be left and backtracking may yield more solutions.

Compatibility considerations to common argument-order in ISO as well as SICStus absolute_file_name/3 forced us to be flexible here. If the last argument is a list and the 2nd not, the arguments are swapped, making the call absolute_file_name(+Spec, -Path, +Options) valid as well.

absolute_file_name(+Name,-FullPath)

Give the path a full path FullPath YAP would use to consult a file named Name. Unify FullPath with user if the file name is user.

file_base_name(+Name,-FileName)

Give the path a full path FullPath extract the FileName.

current_stream(F,M,S)

Defines the relation: The stream S is opened on the file F in mode M. It might be used to obtain all open streams (by backtracking) or to access the stream for a file F in mode M, or to find properties for a stream S.

is_stream(S)

Succeeds if S is a currently open stream.

flush_output [ISO]

Send all data in the output buffer to current output stream.

flush_output(+S) [ISO]

Send all data in the output buffer to stream S.

set_input(+S)

Set stream S as the current input stream. Predicates like read/1 and get/1 will start using stream S.

set_output(+S)

Set stream S as the current output stream. Predicates like write/1 and put/1 will start using stream S.

stream_select(+STREAMS,+TIMEOUT,-READSTREAMS)

Given a list of open STREAMS opened in read mode and a TIMEOUT return a list of streams who are now available for reading.

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]

Unify S with the current input stream.

current_output(-S) [ISO]

Unify S with the current output stream.

at_end_of_stream [ISO]

Succeed if the current stream has stream position end-of-stream or past-end-of-stream.

at_end_of_stream(+S) [ISO]

Succeed if the stream S has stream position end-of-stream or past-end-of-stream. Note that S must be a readable stream.

set_stream_position(+S, +POS) [ISO]

Given a stream position POS for a stream S, set the current stream position for S to be POS.

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 recognized:

file_name(P)

An atom giving the file name for the current stream. The file names are user_input, user_output, and user_error for the standard streams.

mode(P)

The mode used to open the file. It may be one of append, read, or write.

input

The stream is readable.

output

The stream is writable.

alias(A)

ISO-Prolog primitive for stream aliases. YAP returns one of the existing aliases for the stream.

position(P)

A term describing the position in the stream.

end_of_stream(E)

Whether the stream is 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)

The action to take when trying to read after reaching the end of stream. The action may be one of error, generate an error, eof_code, return character code -1, or reset the stream.

reposition(B)

Whether the stream can be repositioned or not, that is, whether it is seekable.

type(T)

Whether the stream is a text stream or a binary stream.

bom(+Bool)

If present and true, a BOM (Byte Order Mark) was detected while opening the file for reading or a BOM was written while opening the stream. See BOM: Byte Order Mark for details.

encoding(+Encoding)

Query the encoding used for text. See Wide Character Support for an overview of wide character and encoding issues in YAP.

representation_errors(+Mode)

Behaviour when writing characters to the stream that cannot be represented by the encoding. The behaviour is one of error (throw and I/O error exception), prolog (write \u...\ escape code or xml (write &#...; XML character entity). The initial mode is prolog for the user streams and error for all other streams. See also Wide Character Support and open/4.

current_line_number(-LineNumber)

Unify LineNumber with the line number for the current stream.

current_line_number(+Stream,-LineNumber)

Unify LineNumber with the line number for the Stream.

line_count(+Stream,-LineNumber)

Unify LineNumber with the line number for the Stream.

character_count(+Stream,-CharacterCount)

Unify CharacterCount with the number of characters written to or read to Stream.

line_position(+Stream,-LinePosition)

Unify LinePosition with the position on current text stream Stream.

stream_position(+Stream,-StreamPosition)

Unify StreamPosition with the packaged information of position on current stream Stream. Use stream_position_data/3 to retrieve information on charater or line count.

stream_position_data(+Field,+StreamPsition,-Info)

Given the packaged stream position term StreamPosition, unify Info with Field line_count, byte_count, or char_count.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.9.2 Handling Streams and Files

tell(+S)

If S is a currently opened stream for output, it becomes the current output stream. If S is an atom it is taken to be a filename. If there is no output stream currently associated with it, then it is opened for output, and the new output stream created becomes the current output stream. If it is not possible to open the file, an error occurs. If there is a single opened output stream currently associated with the file, then it becomes the current output stream; if there are more than one in that condition, one of them is chosen.

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)

The current output stream is unified with S.

told

Closes the current output stream, and the user's terminal becomes again the current output stream. It is important to remember to close streams after having finished using them, as the maximum number of simultaneously opened streams is 17.

see(+S)

If S is a currently opened input stream then it is assumed to be the current input stream. If S is an atom it is taken as a filename. If there is no input stream currently associated with it, then it is opened for input, and the new input stream thus created becomes the current input stream. If it is not possible to open the file, an error occurs. If there is a single opened input stream currently associated with the file, it becomes the current input stream; if there are more than one in that condition, then one of them is chosen.

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)

The current input stream is unified with S.

seen

Closes the current input stream (see 6.7.).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.9.3 Handling Input/Output of Terms

read(-T) [ISO]

Reads the next term from the current input stream, and unifies it with T. The term must be followed by a dot ('.') and any blank-character as previously defined. The syntax of the term must match the current declarations for operators (see op). If the end-of-stream is reached, T is unified with the atom end_of_file. Further reads from of the same stream may cause an error failure (see open/3).

read_term(-T,+Options) [ISO]

Reads term T from the current input stream with execution controlled by the following options:

term_position(-Position)

Unify Position with a term describing the position of the stream at the start of parse. Use stream_position_data/3 to obtain extra information.

singletons(-Names)

Unify Names with a list of the form Name=Var, where Name is the name of a non-anonymous singleton variable in the original term, and Var is the variable's representation in YAP.

syntax_errors(+Val)

Control action to be taken after syntax errors. See yap_flag/2 for detailed information.

variable_names(-Names)

Unify Names with a list of the form Name=Var, where Name is the name of a non-anonymous variable in the original term, and Var is the variable's representation in YAP.

variables(-Names)

Unify Names with a list of the variables in term T.

char_conversion(+IN,+OUT) [ISO]

While reading terms convert unquoted occurrences of the character IN to the character OUT. Both IN and OUT must be bound to single characters atoms.

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]

If IN is unbound give all current character translations. Otherwise, give the translation for IN, if one exists.

write(T) [ISO]

The term T is written to the current output stream according to the operator declarations in force.

display(+T)

Displays term T on the current output stream. All Prolog terms are written in standard parenthesized prefix notation.

write_canonical(+T) [ISO]

Displays term T on the current output stream. Atoms are quoted when necessary, and operators are ignored, that is, the term is written in standard parenthesized prefix notation.

write_term(+T, +Opts) [ISO]

Displays term T on the current output stream, according to the following options:

quoted(+Bool)

If true, quote atoms if this would be necessary for the atom to be recognized as an atom by YAP's parser. The default value is false.

ignore_ops(+Bool)

If true, ignore operator declarations when writing the term. The default value is false.

numbervars(+Bool)

If 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)

If true, use portray/1 to portray bound terms. The default value is false.

max_depth(+Depth)

If 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]

Writes the term T, quoting names to make the result acceptable to the predicate 'read' whenever necessary.

print(T)

Prints the term T to the current output stream using 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)

Print formatted output to the current output stream. The arguments in list L are output according to the string or atom T.

A control sequence is introduced by a w. The following control sequences are available in YAP:

'~~'

Print a single tilde.

'~a'

The next argument must be an atom, that will be printed as if by write.

'~Nc'

The next argument must be an integer, that will be printed as a character code. The number N is the number of times to print the character (default 1).

'~Ne'
'~NE'
'~Nf'
'~Ng'
'~NG'

The next argument must be a floating point number. The float F, the number N and the control code 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'

The next argument must be an integer, and N is the number of digits after the decimal point. If N is 0 no decimal points will be printed. The default is N = 0.

 
?- format("~2d, ~d",[15000, 15000]).
150.00, 15000
'~ND'

Identical to '~Nd', except that commas are used to separate groups of three digits.

 
?- format("~2D, ~D",[150000, 150000]).
1,500.00, 150,000
'~i'

Ignore the next argument in the list of arguments:

 
?- format('The ~i met the boregrove',[mimsy]).
The  met the boregrove
'~k'

Print the next argument with write_canonical:

 
?- format("Good night ~k",a+[1,2]).
Good night +(a,[1,2])
'~Nn'

Print N newlines (where N defaults to 1).

'~NN'

Print N newlines if at the beginning of the line (where N defaults to 1).

'~Nr'

The next argument must be an integer, and N is interpreted as a radix, such that 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'

Similar to '~NR'. The next argument must be an integer, and N is interpreted as a radix, such that 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 the next argument with print/1:

 
?- format("Good night ~p",a+[1,2]).
Good night a+[1,2]
'~q'

Print the next argument with writeq/1:

 
?- format("Good night ~q",'Hello'+[1,2]).
Good night 'Hello'+[1,2]
'~Ns'

The next argument must be a list of character codes. The system then outputs their representation as a string, where N is the maximum number of characters for the string (N defaults to the length of the string).

 
?- format("The ~s are ~4s",["woods","lovely"]).
The woods are love
'~w'

Print the next argument with write/1:

 
?- format("Good night ~w",'Hello'+[1,2]).
Good night Hello+[1,2]

The number of arguments, N, may be given as an integer, or it may be given as an extra argument. The next example shows a small procedure to write a variable number of a characters:

 
write_many_as(N) :-
        format("~*c",[N,0'a]).

The format/2 built-in also allows for formatted output. One can specify column boundaries and fill the intermediate space by a padding character:

'~N|'

Set a column boundary at position N, where N defaults to the current position.

'~N+'

Set a column boundary at N characters past the current position, where N defaults to 8.

'~Nt'

Set padding for a column, where N is the fill code (default is <SPC>).

The next example shows how to align columns and padding. We first show left-alignment:

 

   ?- format("~n*Hello~16+*~n",[]).
*Hello          *

Note that we reserve 16 characters for the column.

The following example shows how to do right-alignment:

 

   ?- format("*~tHello~16+*~n",[]).
*          Hello*


The ~t escape sequence forces filling before Hello.

We next show how to do centering:

 

   ?- format("*~tHello~t~16+*~n",[]).
*     Hello     *

The two ~t escape sequence force filling both before and after Hello. Space is then evenly divided between the right and the left sides.

format(+S,+T,+L)

Print formatted output to stream S.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.9.4 Handling Input/Output of Characters

put(+N)

Outputs to the current output stream the character whose ASCII code is N. The character N must be a legal ASCII character code, an expression yielding such a code, or a list in which case only the first element is used.

put_byte(+N) [ISO]

Outputs to the current output stream the character whose code is N. The current output stream must be a binary stream.

put_char(+N) [ISO]

Outputs to the current output stream the character who is used to build the representation of atom A. The current output stream must be a text stream.

put_code(+N) [ISO]

Outputs to the current output stream the character whose ASCII code is N. The current output stream must be a text stream. The character N must be a legal ASCII character code, an expression yielding such a code, or a list in which case only the first element is used.

get(-C)

The next non-blank character from the current input stream is unified with C. Blank characters are the ones whose ASCII codes are not greater than 32. If there are no more non-blank characters in the stream, C is unified with -1. If end_of_stream has already been reached in the previous reading, this call will give an error message.

get0(-C)

The next character from the current input stream is consumed, and then unified with C. There are no restrictions on the possible values of the ASCII code for the character, but the character will be internally converted by YAP.

get_byte(-C) [ISO]

If C is unbound, or is a character code, and the current stream is a binary stream, read the next byte from the current stream and unify its code with C.

get_char(-C) [ISO]

If C is unbound, or is an atom representation of a character, and the current stream is a text stream, read the next character from the current stream and unify its atom representation with C.

get_code(-C) [ISO]

If C is unbound, or is the code for a character, and the current stream is a text stream, read the next character from the current stream and unify its code with C.

peek_byte(-C) [ISO]

If C is unbound, or is a character code, and the current stream is a binary stream, read the next byte from the current stream and unify its code with C, while leaving the current stream position unaltered.

peek_char(-C) [ISO]

If C is unbound, or is an atom representation of a character, and the current stream is a text stream, read the next character from the current stream and unify its atom representation with C, while leaving the current stream position unaltered.

peek_code(-C) [ISO]

If C is unbound, or is the code for a character, and the current stream is a text stream, read the next character from the current stream and unify its code with C, while leaving the current stream position unaltered.

skip(+N)

Skips input characters until the next occurrence of the character with ASCII code N. The argument to this predicate can take the same forms as those for put (see 6.11).

tab(+N)

Outputs N spaces to the current output stream.

nl [ISO]

Outputs a new line to the current output stream.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.9.5 Input/Output Predicates applied to Streams

read(+S,-T) [ISO]

Reads term T from the stream S instead of from the current input stream.

read_term(+S,-T,+Options) [ISO]

Reads term T from stream S with execution controlled by the same options as read_term/2.

write(+S,T) [ISO]

Writes term T to stream S instead of to the current output stream.

write_canonical(+S,+T) [ISO]

Displays term T on the stream S. Atoms are quoted when necessary, and operators are ignored.

write_term(+S, +T, +Opts) [ISO]

Displays term T on the current output stream, according to the same options used by write_term/3.

writeq(+S,T) [ISO]

As writeq/1, but the output is sent to the stream S.

display(+S,T)

Like display/1, but using stream S to display the term.

print(+S,T)

Prints term T to the stream S instead of to the current output stream.

put(+S,+N)

As put(N), but to stream S.

put_byte(+S,+N) [ISO]

As put_byte(N), but to binary stream S.

put_char(+S,+A) [ISO]

As put_char(A), but to text stream S.

put_code(+S,+N) [ISO]

As put_code(N), but to text stream S.

get(+S,-C)

The same as get(C), but from stream S.

get0(+S,-C)

The same as get0(C), but from stream S.

get_byte(+S,-C) [ISO]

If C is unbound, or is a character code, and the stream S is a binary stream, read the next byte from that stream and unify its code with C.

get_char(+S,-C) [ISO]

If C is unbound, or is an atom representation of a character, and the stream S is a text stream, read the next character from that stream and unify its representation as an atom with C.

get_code(+S,-C) [ISO]

If C is unbound, or is a character code, and the stream S is a text stream, read the next character from that stream and unify its code with C.

peek_byte(+S,-C) [ISO]

If C is unbound, or is a character code, and S is a binary stream, read the next byte from the current stream and unify its code with C, while leaving the current stream position unaltered.

peek_char(+S,-C) [ISO]

If C is unbound, or is an atom representation of a character, and the stream S is a text stream, read the next character from that stream and unify its representation as an atom with C, while leaving the current stream position unaltered.

peek_code(+S,-C) [ISO]

If C is unbound, or is an atom representation of a character, and the stream S is a text stream, read the next character from that stream and unify its representation as an atom with C, while leaving the current stream position unaltered.

skip(+S,-C)

Like skip/1, but using stream S instead of the current input stream.

tab(+S,+N)

The same as tab/1, but using stream S.

nl(+S)

Outputs a new line to stream S.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.9.6 Compatible C-Prolog predicates for Terminal I/O

ttyput(+N)

As put(N) but always to user_output.

ttyget(-C)

The same as get(C), but from stream user_input.

ttyget0(-C)

The same as get0(C), but from stream user_input.

ttyskip(-C)

Like skip/1, but always using stream user_input. stream.

ttytab(+N)

The same as tab/1, but using stream user_output.

ttynl

Outputs a new line to stream user_output.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.9.7 Controlling Input/Output

exists(+F)

Checks if file F exists in the current directory.

nofileerrors

Switches off the file_errors flag, so that the predicates 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

Switches on the file_errors flag so that in certain error conditions I/O predicates will produce an appropriated message and abort.

write_depth(T,L,A)

Unifies T with the value of the maximum depth of a term to be written, L with the maximum length of a list to write, and A with the maximum number of arguments of a compound term to write. The setting will be used by write/1 or write/2. The default value for all arguments is 0, meaning unlimited depth and length.

 
?- write_depth(3,5,5).
yes
?- write(a(b(c(d(e(f(g))))))).
a(b(c(....)))
yes
?- write([1,2,3,4,5,6,7,8]).
[1,2,3,4,5,...]
yes
?- write(a(1,2,3,4,5,6,7,8)).
a(1,2,3,4,5,...)
yes
write_depth(T,L)

Same as write_depth(T,L,_). Unifies T with the value of the maximum depth of a term to be written, and L with the maximum length of a list to write. The setting will be used by write/1 or write/2. The default value for all arguments is 0, meaning unlimited depth and length.

 
?- write_depth(3,5,5).
yes
?- write(a(b(c(d(e(f(g))))))).
a(b(c(....)))
yes
?- write([1,2,3,4,5,6,7,8]).
[1,2,3,4,5,...]
yes
always_prompt_user

Force the system to prompt the user even if the 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] [ ? ]

6.9.8 Using Sockets From YAP

YAP includes a SICStus Prolog compatible socket interface. This is a low level interface that provides direct access to the major socket system calls. These calls can be used both to open a new connection in the network or connect to a networked server. Socket connections are described as read/write streams, and standard I/O built-ins can be used to write on or read from sockets. The following calls are available:

socket(+DOMAIN,+TYPE,+PROTOCOL,-SOCKET)

Corresponds to the BSD system call 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_connect (that is, client sockets) should not be closed with socket_close, as they will be automatically closed when the corresponding stream is closed with close/1 or close/2.

socket_bind(+SOCKET, ?PORT)

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)

use file name FILENAME for UNIX or local sockets.

'AF_INET'(?HOST,?PORT)

If HOST is bound to an atom, bind to host HOST, otherwise if unbound bind to local host (HOST remains unbound). If port PORT is bound to an integer, try to bind to the corresponding port. If variable PORT is unbound allow operating systems to choose a port number, which is unified with 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)

connect to socket at file FILENAME.

'AF_INET'(+HOST,+PORT)

Connect to socket at host HOST and port PORT.

socket_listen(+SOCKET, +LENGTH)

Interface to system call 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)

Interface to system call 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)

Accept a connection but do not return client information.

socket_buffering(+SOCKET, -MODE, -OLD, +NEW)

Set buffering for SOCKET in 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)

Interface to system call 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)

Unify HOSTNAME with an atom representing the fully qualified hostname for the current host. Also succeeds if HOSTNAME is bound to the unqualified hostname.

hostname_address(?HOSTNAME,?IP_ADDRESS)

HOSTNAME is an host name and IP_ADDRESS its IP address in number and dots notation.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.10 Using the Clausal Data Base

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

Declares predicate P or list of predicates [P1,...,Pn] as a dynamic predicate. P must be written in form: name/arity.

 
:- 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)

Declares predicate P or list of predicates [P1,...,Pn] as a dynamic predicate following either logical or immediate semantics.

Subnodes of Database 6.10.1 Modification of the Data Base  Asserting and Retracting 6.10.2 Looking at the Data Base  Finding out what is in the Data Base 6.10.3 Using Data Base References  Using Data Base References 6.11 Internal Data Base  YAP's Internal Database 6.12 The Blackboard  Storing and Fetching Terms in the BlackBoard


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.10.1 Modification of the Data Base

These predicates can be used either for static or for dynamic predicates:

assert(+C)

Adds clause C to the program. If the predicate is undefined, declare it as dynamic.

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]

Adds clause C to the beginning of the program. If the predicate is undefined, declare it as dynamic.

assertz(+C) [ISO]

Adds clause C to the end of the program. If the predicate is undefined, declare it as dynamic.

Most Prolog systems only allow asserting clauses for dynamic predicates. This is also as specified in the ISO standard. YAP allows asserting clauses for static predicates. The current version of YAP supports this feature, but this feature is deprecated and support may go away in future versions.

abolish(+PredSpec) [ISO]

Deletes the predicate given by PredSpec from the database. If PredSpec is an unbound variable, delete all predicates for the current module. The specification must include the name and arity, and it may include module information. Under iso language mode this built-in will only abolish dynamic procedures. Under other modes it will abolish any procedures.

abolish(+P,+N)

Deletes the predicate with name P and arity N. It will remove both static and dynamic predicates.

assert_static(:C)

Adds clause C to a static procedure. Asserting a static clause for a predicate while choice-points for the predicate are available has undefined results.

asserta_static(:C)

Adds clause C to the beginning of a static procedure.

assertz_static(:C)

Adds clause C to the end of a static procedure. Asserting a static clause for a predicate while choice-points for the predicate are available has undefined results.

The following predicates can be used for dynamic predicates and for static predicates, if source mode was on when they were compiled:

clause(+H,B) [ISO]

A clause whose head matches H is searched for in the program. Its head and body are respectively unified with H and B. If the clause is a unit clause, B is unified with true.

This predicate is applicable to static procedures compiled with source active, and to all dynamic procedures.

clause(+H,B,-R)

The same as clause/2, plus R is unified with the reference to the clause in the database. You can use instance/2 to access the reference's value. Note that you may not use erase/1 on the reference on static procedures.

nth_clause(+H,I,-R)

Find the Ith clause in the predicate defining H, and give a reference to the clause. Alternatively, if the reference R is given the head H is unified with a description of the predicate and I is bound to its position.

The following predicates can only be used for dynamic predicates:

retract(+C) [ISO]

Erases the first clause in the program that matches C. This predicate may also be used for the static predicates that have been compiled when the source mode was on. For more information on source/0 (see section Changing the Compiler's Behavior).

retractall(+G)

Retract all the clauses whose head matches the goal G. Goal G must be a call to a dynamic predicate.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.10.2 Looking at the Data Base

listing

Lists in the current output stream all the clauses for which source code is available (these include all clauses for dynamic predicates and clauses for static predicates compiled when source mode was on).

listing(+P)

Lists predicate P if its source code is available.

portray_clause(+C)

Write clause C as if written by listing/0.

portray_clause(+S,+C)

Write clause C on stream S as if written by listing/0.

current_atom(A)

Checks whether A is a currently defined atom. It is used to find all currently defined atoms by backtracking.

current_predicate(F) [ISO]

F is the predicate indicator for a currently defined user or library predicate. F is of the form Na/Ar, where the atom Na is the name of the predicate, and Ar its arity.

current_predicate(A,P)

Defines the relation: P is a currently defined predicate whose name is the atom A.

system_predicate(A,P)

Defines the relation: P is a built-in predicate whose name is the atom A.

predicate_property(P,Prop)

For the predicates obeying the specification P unify Prop with a property of P. These properties may be:

built_in

true for built-in predicates,

dynamic

true if the predicate is dynamic

static

true if the predicate is static

meta_predicate(M)

true if the predicate has a meta_predicate declaration M.

multifile

true if the predicate was declared to be multifile

imported_from(Mod)

true if the predicate was imported from module Mod.

exported

true if the predicate is exported in the current module.

public

true if the predicate is public; note that all dynamic predicates are public.

tabled

true if the predicate is tabled; note that only static predicates can be tabled in YAP.

source

true if source for the predicate is available.

number_of_clauses(ClauseCount)

Number of clauses in the predicate definition. Always one if external or built-in.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.10.3 Using Data Base References

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)

The same as assert(C) (see section 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)

The same as 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)

The same as 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)

Erases from the program the clause C whose database reference is R. The predicate must be dynamic.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.11 Internal Data Base

Some programs need global information for, e.g. counting or collecting data obtained by backtracking. As a rule, to keep this information, the internal data base should be used instead of asserting and retracting clauses (as most novice programmers do), . In YAP (as in some other Prolog systems) the internal data base (i.d.b. for short) is faster, needs less space and provides a better insulation of program and data than using asserted/retracted clauses. The i.d.b. is implemented as a set of terms, accessed by keys that unlikely what happens in (non-Prolog) data bases are not part of the term. Under each key a list of terms is kept. References are provided so that terms can be identified: each term in the i.d.b. has a unique reference (references are also available for clauses of dynamic predicates).

recorda(+K,T,-R)

Makes term T the first record under key K and unifies R with its reference.

recordz(+K,T,-R)

Makes term T the last record under key K and unifies R with its reference.

recorda_at(+R0,T,-R)

Makes term T the record preceding record with reference R0, and unifies R with its reference.

recordz_at(+R0,T,-R)

Makes term T the record following record with reference R0, and unifies R with its reference.

recordaifnot(+K,T,-R)

If a term equal to T up to variable renaming is stored under key K fail. Otherwise, make term T the first record under key K and unify R with its reference.

recordzifnot(+K,T,-R)

If a term equal to T up to variable renaming is stored under key K fail. Otherwise, make term T the first record under key K and unify R with its reference.

recorded(+K,T,R)

Searches in the internal database under the key K, a term that unifies with T and whose reference matches R. This built-in may be used in one of two ways:

nth_instance(?K,?Index,T,?R)

Fetches the Indexnth entry in the internal database under the key K. Entries are numbered from one. If the key K are the Index are bound, a reference is unified with R. Otherwise, the reference R must be given, and the term the system will find the matching key and index.

erase(+R)

The term referred to by R is erased from the internal database. If reference R does not exist in the database, erase just fails.

erased(+R)

Succeeds if the object whose database reference is R has been erased.

instance(+R,-T)

If R refers to a clause or a recorded term, T is unified with its most general instance. If R refers to an unit clause C, then T is unified with C :- true. When R is not a reference to an existing clause or to a recorded term, this goal fails.

eraseall(+K)

All terms belonging to the key K are erased from the internal database. The predicate always succeeds.

current_key(?A,?K)

Defines the relation: K is a currently defined database key whose name is the atom A. It can be used to generate all the keys for the internal data-base.

key_statistics(+K,-Entries,-Size,-IndexSize)

Returns several statistics for a key K. Currently, it says how many entries we have for that key, Entries, what is the total size spent on entries, Size, and what is the amount of space spent in indices.

key_statistics(+K,-Entries,-TotalSize)

Returns several statistics for a key K. Currently, it says how many entries we have for that key, Entries, what is the total size spent on this key.

get_value(+A,-V)

In YAP, atoms can be associated with constants. If one such association exists for atom A, unify the second argument with the constant. Otherwise, unify V with [].

This predicate is YAP specific.

set_value(+A,+C)

Associate atom A with constant C.

The set_value and get_value built-ins give a fast alternative to the internal data-base. This is a simple form of implementing a global counter.

 
       read_and_increment_counter(Value) :-
                get_value(counter, Value),
                Value1 is Value+1,
                set_value(counter, Value1).

This predicate is YAP specific.

recordzifnot(+K,T,-R)

If a variant of T is stored under key K fail. Otherwise, make term T the last record under key K and unify R with its reference.

This predicate is YAP specific.

recordaifnot(+K,T,-R)

If a variant of T is stored under key K fail. Otherwise, make term T the first record under key K and unify R with its reference.

This predicate is YAP specific.

There is a strong analogy between the i.d.b. and the way dynamic predicates are stored. In fact, the main i.d.b. predicates might be implemented using dynamic predicates:

 
recorda(X,T,R) :- asserta(idb(X,T),R).
recordz(X,T,R) :- assertz(idb(X,T),R).
recorded(X,T,R) :- clause(idb(X,T),R).

We can take advantage of this, the other way around, as it is quite easy to write a simple Prolog interpreter, using the i.d.b.:

 
asserta(G) :- recorda(interpreter,G,_).
assertz(G) :- recordz(interpreter,G,_).
retract(G) :- recorded(interpreter,G,R), !, erase(R).
call(V) :- var(V), !, fail.
call((H :- B)) :- !, recorded(interpreter,(H :- B),_), call(B).
call(G) :- recorded(interpreter,G,_).

In YAP, much attention has been given to the implementation of the i.d.b., especially to the problem of accelerating the access to terms kept in a large list under the same key. Besides using the key, YAP uses an internal lookup function, transparent to the user, to find only the terms that might unify. For instance, in a data base containing the terms

 
b
b(a)
c(d)
e(g)
b(X)
e(h)

stored under the key k/1, when executing the query

 
:- recorded(k(_),c(_),R).

recorded would proceed directly to the third term, spending almost the time as if a(X) or b(X) was being searched. The lookup function uses the functor of the term, and its first three arguments (when they exist). So, recorded(k(_),e(h),_) would go directly to the last term, while recorded(k(_),e(_),_) would find first the fourth term, and then, after backtracking, the last one.

This mechanism may be useful to implement a sort of hierarchy, where the functors of the terms (and eventually the first arguments) work as secondary keys.

In the YAP's i.d.b. an optimized representation is used for terms without free variables. This results in a faster retrieval of terms and better space usage. Whenever possible, avoid variables in terms in terms stored in the i.d.b.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.12 The Blackboard

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)

Store term table Term in the blackboard under key Key. If a previous term was stored under key Key it is simply forgotten.

bb_get(+Key,?Term)

Unify Term with a term stored in the blackboard under key Key, or fail silently if no such term exists.

bb_delete(+Key,?Term)

Delete any term stored in the blackboard under key Key and unify it with Term. Fail silently if no such term exists.

bb_update(+Key,?Term,?New)

Atomically unify a term stored in the blackboard under key Key with Term, and if the unification succeeds replace it by New. Fail silently if no such term exists or if unification fails.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.13 Collecting Solutions to a Goal

When there are several solutions to a goal, if the user wants to collect all the solutions he may be led to use the data base, because backtracking will forget previous solutions.

YAP allows the programmer to choose from several system predicates instead of writing his own routines. findall/3 gives you the fastest, but crudest solution. The other built-in predicates post-process the result of the query in several different ways:

findall(T,+G,-L) [ISO]

Unifies L with a list that contains all the instantiations of the term T satisfying the goal G.

With the following program:

 
a(2,1).
a(1,1).
a(2,2).

the answer to the query

 
findall(X,a(X,Y),L).

would be:

 
X = _32
Y = _33
L = [2,1,2];
no
findall(T,+G,+L,-L0)

Similar to findall/3, but appends all answers to list L0.

all(T,+G,-L)

Similar to findall(T,G,L) but eliminate repeated elements. Thus, assuming the same clauses as in the above example, the reply to the query

 
all(X,a(X,Y),L).

would be:

 
X = _32
Y = _33
L = [2,1];
no

Note that all/3 will fail if no answers are found.

bagof(T,+G,-L) [ISO]

For each set of possible instances of the free variables occurring in G but not in T, generates the list L of the instances of T satisfying G. Again, assuming the same clauses as in the examples above, the reply to the query

 
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]

Similar to bagof(T,G,L) but sorting list L and keeping only one copy of each element. Again, assuming the same clauses as in the examples above, the reply to the query

 
setof(X,a(X,Y),L).

would be:

 
X = _32
Y = 1
L = [1,2];
X = _32
Y = 2
L = [2];
no

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.14 Grammar Rules

Grammar rules in Prolog are both a convenient way to express definite clause grammars and an extension of the well known context-free grammars.

A grammar rule is of the form:

 
 head --> body 

where both head and body are sequences of one or more items linked by the standard conjunction operator ','.

Items can be:

Grammar related built-in predicates:

expand_term(T,-X)

This predicate is used by YAP for preprocessing each top level term read when consulting a file and before asserting or executing it. It rewrites a term T to a term X according to the following rules: first try to use the user defined predicate 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)

YAP now supports 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)

This predicate succeeds when the difference list L-R is a phrase of type P.

phrase(+P,L)

This predicate succeeds when L is a phrase of type P. The same as 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)

This predicate is used by the grammar rules compiler and is defined as 'C'([H|T],H,T).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.15 Access to Operating System Functionality

The following built-in predicates allow access to underlying Operating System functionality:

cd(+D)

Changes the current directory (on UNIX environments).

environ(+E,-S)

Given an environment variable E this predicate unifies the second argument S with its value.

getcwd(-D)

Unify the current directory, represented as an atom, with the argument D.

putenv(+E,+S)

Set environment variable E to the value S. If the environment variable E does not exist, create a new one. Both the environment variable and the value must be atoms.

rename(+F,+G)

Renames file F to G.

sh

Creates a new shell interaction.

system(+S)

Passes command S to the Bourne shell (on UNIX environments) or the current command interpreter in WIN32 environments.

unix(+S)

Access to Unix-like functionality:

argv/1

Return a list of arguments to the program. These are the arguments that follow a --, as in the usual Unix convention.

cd/0

Change to home directory.

cd/1

Change to given directory. Acceptable directory names are strings or atoms.

environ/2

If the first argument is an atom, unify the second argument with the value of the corresponding environment variable.

getcwd/1

Unify the first argument with an atom representing the current directory.

putenv/2

Set environment variable E to the value S. If the environment variable E does not exist, create a new one. Both the environment variable and the value must be atoms.

shell/1

Execute command under current shell. Acceptable commands are strings or atoms.

system/1

Execute command with /bin/sh. Acceptable commands are strings or atoms.

shell/0

Execute a new shell.

alarm(+Seconds,+Callable,+OldAlarm)

Arranges for YAP to be interrupted in Seconds seconds, or in Seconds.MicroSeconds. When interrupted, YAP will execute Callable and then return to the previous execution. If Seconds is 0, no new alarm is scheduled. In any event, any previously set alarm is canceled.

The variable OldAlarm unifies with the number of seconds remaining until any previously scheduled alarm was due to be delivered, or with 0 if there was no previously scheduled alarm.

Note that execution of Callable will wait if YAP is executing built-in predicates, such as Input/Output operations.

The next example shows how alarm/3 can be used to implement a simple clock:

 
loop :- loop.

ticker :- write('.'), flush_output,
          get_value(tick, yes),
          alarm(1,ticker,_).

:- set_value(tick, yes), alarm(1,ticker,_), loop.

The clock, ticker, writes a dot and then checks the flag tick to see whether it can continue ticking. If so, it calls itself again. Note that there is no guarantee that the each dot corresponds a second: for instance, if the YAP is waiting for user input, ticker will wait until the user types the entry in.

The next example shows how alarm/3 can be used to guarantee that a certain procedure does not take longer than a certain amount of time:

 
loop :- loop.

:-   catch((alarm(10, throw(ball), _),loop),
        ball,
        format('Quota exhausted.~n',[])).

In this case after 10 seconds our loop is interrupted, ball is thrown, and the handler writes Quota exhausted. Execution then continues from the handler.

Note that in this case loop/0 always executes until the alarm is sent. Often, the code you are executing succeeds or fails before the alarm is actually delivered. In this case, you probably want to disable the alarm when you leave the procedure. The next procedure does exactly so:

 
once_with_alarm(Time,Goal,DoOnAlarm) :-
   catch(execute_once_with_alarm(Time, Goal), alarm, DoOnAlarm).

execute_once_with_alarm(Time, Goal) :-
        alarm(Time, alarm, _),
        ( call(Goal) -> alarm(0, alarm, _) ; alarm(0, alarm, _), fail).

The procedure 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)

Set the interrupt handler for soft interrupt Signal to be Callable. OldAction is unified with the previous handler.

Only a subset of the software interrupts (signals) can have their handlers manipulated through on_signal/3. Their POSIX names, YAP names and default behavior is given below. The "YAP name" of the signal is the atom that is associated with each signal, and should be used as the first argument to on_signal/3. It is chosen so that it matches the signal's POSIX name.

on_signal/3 succeeds, unless when called with an invalid signal name or one that is not supported on this platform. No checks are made on the handler provided by the user.

sig_up (Hangup)

SIGHUP in Unix/Linux; Reconsult the initialization files ~/.yaprc, ~/.prologrc and ~/prolog.ini.

sig_usr1 and sig_usr2 (User signals)

SIGUSR1 and SIGUSR2 in Unix/Linux; Print a message and halt.

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] [ ? ]

6.16 Term Modification

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)

Set the value of the Ith argument of term S to term T.

create_mutable(+D,-M)

Create new mutable variable M with initial value D.

get_mutable(?D,+M)

Unify the current value of mutable term M with term D.

is_mutable(?D)

Holds if D is a mutable term.

get_mutable(?D,+M)

Unify the current value of mutable term M with term D.

update_mutable(+D,+M)

Set the current value of mutable term M to term D.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.17 Global Variables

Global variables are associations between names (atoms) and terms. They differ in various ways from storing information using assert/1 or recorda/3.

Currently global variables are scoped globally. We may consider module scoping in future versions. Both b_setval/2 and nb_setval/2 implicitly create a variable if the referenced name does not already refer to a variable.

Global variables may be initialised from directives to make them available during the program lifetime, but some considerations are necessary for saved-states and threads. Saved-states to not store global variables, which implies they have to be declared with initialization/1 to recreate them after loading the saved state. Each thread has its own set of global variables, starting with an empty set. Using thread_initialization/1 to define a global variable it will be defined, restored after reloading a saved state and created in all threads that are created after the registration. Finally, global variables can be initialised using the exception hook called exception/3. The latter technique is used by CHR.

b_setval(+Name, +Value)

Associate the term Value with the atom Name or replaces the currently associated value with Value. If Name does not refer to an existing global variable a variable with initial value [] is created (the empty list). On backtracking the assignment is reversed.

b_getval(+Name, -Value)

Get the value associated with the global variable Name and unify it with Value. Note that this unification may further instantiate the value of the global variable. If this is undesirable the normal precautions (double negation or copy_term/2) must be taken. The b_getval/2 predicate generates errors if Name is not an atom or the requested variable does not exist.

nb_setval(+Name, +Value)

Associates a copy of Value created with duplicate_term/2 with the atom Name. Note that this can be used to set an initial value other than [] prior to backtrackable assignment.

nb_getval(+Name, -Value)

The nb_getval/2 predicate is a synonym for b_getval/2, introduced for compatibility and symmetry. As most scenarios will use a particular global variable either using non-backtracable or backtrackable assignment, using nb_getval/2 can be used to document that the variable is used non-backtracable.

nb_linkval(+Name, +Value)

Associates the term Value with the atom Name without copying it. This is a fast special-purpose variation of nb_setval/2 intended for expert users only because the semantics on backtracking to a point before creating the link are poorly defined for compound terms. The principal term is always left untouched, but backtracking behaviour on arguments is undone if the original assignment was trailed and left alone otherwise, which implies that the history that created the term affects the behaviour on backtracking. Please consider the following example:

 
demo_nb_linkval :-
        T = nice(N),
        (   N = world,
            nb_linkval(myvar, T),
            fail
        ;   nb_getval(myvar, V),
            writeln(V)
        ).
nb_set_shared_val(+Name, +Value)

Associates the term Value with the atom Name, but sharing non-backtrackable terms. This may be useful if you want to rewrite a global variable so that the new copy will survive backtracking, but you want to share structure with the previous term.

The next example shows the differences between the three built-ins:

 
?- nb_setval(a,a(_)),nb_getval(a,A),nb_setval(b,t(C,A)),nb_getval(b,B).
A = a(_A),
B = t(_B,a(_C)) ? 

?- nb_setval(a,a(_)),nb_getval(a,A),nb_set_shared_val(b,t(C,A)),nb_getval(b,B).

?- nb_setval(a,a(_)),nb_getval(a,A),nb_linkval(b,t(C,A)),nb_getval(b,B).
A = a(_A),
B = t(C,a(_A)) ?
nb_setarg(+{Arg], +Term, +Value)

Assigns the Arg-th argument of the compound term Term with the given Value as setarg/3, but on backtracking the assignment is not reversed. If Term is not atomic, it is duplicated using duplicate_term/2. This predicate uses the same technique as nb_setval/2. We therefore refer to the description of nb_setval/2 for details on non-backtrackable assignment of terms. This predicate is compatible to GNU-Prolog setarg(A,T,V,false), removing the type-restriction on Value. See also nb_linkarg/3. Below is an example for counting the number of solutions of a goal. Note that this implementation is thread-safe, reentrant and capable of handling exceptions. Realising these features with a traditional implementation based on assert/retract or flag/3 is much more complicated.

 
    succeeds_n_times(Goal, Times) :-
            Counter = counter(0),
            (   Goal,
                arg(1, Counter, N0),
                N is N0 + 1,
                nb_setarg(1, Counter, N),
                fail
            ;   arg(1, Counter, Times)
            ).
nb_set_shared_arg(+Arg, +Term, +Value)

As nb_setarg/3, but like nb_linkval/2 it does not duplicate the global sub-terms in Value. Use with extreme care and consult the documentation of nb_linkval/2 before use.

nb_linkarg(+Arg, +Term, +Value)

As nb_setarg/3, but like nb_linkval/2 it does not duplicate Value. Use with extreme care and consult the documentation of nb_linkval/2 before use.

nb_current(?Name, ?Value)

Enumerate all defined variables with their value. The order of enumeration is undefined.

nb_delete(+Name)

Delete the named global variable.

Global variables have been introduced by various Prolog implementations recently. We follow the implementation of them in SWI-Prolog, itself based on hProlog by Bart Demoen.

GNU-Prolog provides a rich set of global variables, including arrays. Arrays can be implemented easily in YAP and SWI-Prolog using functor/3 and setarg/3 due to the unrestricted arity of compound terms.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

>>>>>>> 1.222

6.18 Profiling Prolog Programs

YAP includes two profilers. The count profiler keeps information on the number of times a predicate was called. This information can be used to detect what are the most commonly called predicates in the program. The count profiler can be compiled by setting YAP's flag profiling to on. The time-profiler is a gprof profiler, and counts how many ticks are being spent on specific predicates, or on other system functions such as internal data-base accesses or garbage collects.

The YAP profiling sub-system is currently under development. Functionality for this sub-system will increase with newer implementation.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.18.1 The Count Profiler

Notes:

The count profiler works by incrementing counters at procedure entry or backtracking. It provides exact information:

These are the current predicates to access and clear profiling data:

profile_data(?Na/Ar, ?Parameter, -Data)

Give current profile data on Parameter for a predicate described by the predicate indicator Na/Ar. If any of Na/Ar or Parameter are unbound, backtrack through all profiled predicates or stored parameters. Current parameters are:

calls

Number of times a procedure was called.

retries

Number of times a call to the procedure was backtracked to and retried.

profile_reset

Reset all profiling information.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.18.2 Tick Profiler

The tick profiler works by interrupting the Prolog code every so often and checking at each point the code was. The profiler must be able to retrace the state of the abstract machine at every moment. The major advantage of this approach is that it gives the actual amount of time being spent per procedure, or whether garbage collection dominates execution time. The major drawback is that tracking down the state of the abstract machine may take significant time, and in the worst case may slow down the whole execution.

The following procedures are available:

profinit

Initialise the data-structures for the profiler. Unnecessary for dynamic profiler.

profon

Start profiling.

profoff

Stop profiling.

showprofres

Show profiling info.

showprofres(N)

Show profiling info for the top-most N predicates.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.19 Counting Calls

Predicates compiled with YAP's flag call_counting set to on update counters on the numbers of calls and of retries. Counters are actually decreasing counters, so that they can be used as timers. Three counters are available:

These counters can be used to find out how many calls a certain goal takes to execute. They can also be used as timers.

The code for the call counters piggybacks on the profiling code. Therefore, activating the call counters also activates the profiling counters.

These are the predicates that access and manipulate the call counters:

call_count_data(-Calls, -Retries, -CallsAndRetries)

Give current call count data. The first argument gives the current value for the Calls counter, next the Retries counter, and last the CallsAndRetries counter.

call_count_reset

Reset call count counters. All timers are also reset.

call_count(?CallsMax, ?RetriesMax, ?CallsAndRetriesMax)

Set call count counter as timers. YAP will generate an exception if one of the instantiated call counters decreases to 0. YAP will ignore unbound arguments:

Next, we show a simple example of how to use call counters:

 
   ?- yap_flag(call_counting,on), [-user]. l :- l. end_of_file. yap_flag(call_counting,off).

yes

yes
   ?- catch((call_count(10000,_,_),l),call_counter,format("limit_exceeded.~n",[])).

limit_exceeded.

yes

Notice that we first compile the looping predicate l/0 with call_counting on. Next, we catch/3 to handle an exception when l/0 performs more than 10000 reductions.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.20 Arrays

The YAP system includes experimental support for arrays. The support is enabled with the option YAP_ARRAYS.

There are two very distinct forms of arrays in YAP. The dynamic arrays are a different way to access compound terms created during the execution. Like any other terms, any bindings to these terms and eventually the terms themselves will be destroyed during backtracking. Our goal in supporting dynamic arrays is twofold. First, they provide an alternative to the standard arg/3 built-in. Second, because dynamic arrays may have name that are globally visible, a dynamic array can be visible from any point in the program. In more detail, the clause

 
g(X) :- array_element(a,2,X).

will succeed as long as the programmer has used the built-in array/2 to create an array term with at least 3 elements in the current environment, and the array was associated with the name a. The element X is a Prolog term, so one can bind it and any such bindings will be undone when backtracking. Note that dynamic arrays do not have a type: each element may be any Prolog term.

The static arrays are an extension of the database. They provide a compact way for manipulating data-structures formed by characters, integers, or floats imperatively. They can also be used to provide two-way communication between YAP and external programs through shared memory.

In order to efficiently manage space elements in a static array must have a type. Currently, elements of static arrays in YAP should have one of the following predefined types:

Arrays may be named or anonymous. Most arrays will be named, that is associated with an atom that will be used to find the array. Anonymous arrays do not have a name, and they are only of interest if the TERM_EXTENSIONS compilation flag is enabled. In this case, the unification and parser are extended to replace occurrences of Prolog terms of the form X[I] by run-time calls to array_element/3, so that one can use array references instead of extra calls to arg/3. As an example:

 
g(X,Y,Z,I,J) :- X[I] is Y[J]+Z[I].

should give the same results as:

 
G(X,Y,Z,I,J) :-
        array_element(X,I,E1),
        array_element(Y,J,E2),  
        array_element(Z,I,E3),  
        E1 is E2+E3.

Note that the only limitation on array size are the stack size for dynamic arrays; and, the heap size for static (not memory mapped) arrays. Memory mapped arrays are limited by available space in the file system and in the virtual memory space.

The following predicates manipulate arrays:

array(+Name, +Size)

Creates a new dynamic array. The Size must evaluate to an integer. The Name may be either an atom (named array) or an unbound variable (anonymous array).

Dynamic arrays work as standard compound terms, hence space for the array is recovered automatically on backtracking.

static_array(+Name, +Size, +Type)

Create a new static array with name Name. Note that the Name must be an atom (named array). The Size must evaluate to an integer. The Type must be bound to one of types mentioned previously.

reset_static_array(+Name)

Reset static array with name Name to its initial value.

static_array_location(+Name, -Ptr)

Give the location for a static array with name Name.

static_array_properties(?Name, ?Size, ?Type)

Show the properties size and type of a static array with name Name. Can also be used to enumerate all current static arrays.

This built-in will silently fail if the there is no static array with that name.

static_array_to_term(?Name, ?Term)

Convert a static array with name Name to a compound term of name Name.

This built-in will silently fail if the there is no static array with that name.

mmapped_array(+Name, +Size, +Type, +File)

Similar to static_array/3, but the array is memory mapped to file File. This means that the array is initialized from the file, and that any changes to the array will also be stored in the file.

This built-in is only available in operating systems that support the system call mmap. Moreover, mmapped arrays do not store generic terms (type term).

close_static_array(+Name)

Close an existing static array of name Name. The Name must be an atom (named array). Space for the array will be recovered and further accesses to the array will return an error.

resize_static_array(+Name, -OldSize, +NewSize)

Expand or reduce a static array, The Size must evaluate to an integer. The Name must be an atom (named array). The Type must be bound to one of 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)

Unify Element with Name[Index]. It works for both static and dynamic arrays, but it is read-only for static arrays, while it can be used to unify with an element of a dynamic array.

update_array(+Name, +Index, ?Value)

Attribute value Value to Name[Index]. Type restrictions must be respected for static arrays. This operation is available for dynamic arrays if MULTI_ASSIGNMENT_VARIABLES is enabled (true by default). Backtracking undoes update_array/3 for dynamic arrays, but not for static arrays.

Note that update_array/3 actually uses setarg/3 to update elements of dynamic arrays, and setarg/3 spends an extra cell for every update. For intensive operations we suggest it may be less expensive to unify each element of the array with a mutable terms and to use the operations on mutable terms.

add_to_array_element(+Name, +Index, , +Number, ?NewValue)

Add Number Name[Index] and unify NewValue with the incremented value. Observe that Name[Index] must be an number. If Name is a static array the type of the array must be int or float. If the type of the array is int you only may add integers, if it is float you may add integers or floats. If Name corresponds to a dynamic array the array element must have been previously bound to a number and Number can be any kind of number.

The add_to_array_element/3 built-in actually uses setarg/3 to update elements of dynamic arrays. For intensive operations we suggest it may be less expensive to unify each element of the array with a mutable terms and to use the operations on mutable terms.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.21 Predicate Information

Built-ins that return information on the current predicates and modules:

current_module(M)

Succeeds if M are defined modules. A module is defined as soon as some predicate defined in the module is loaded, as soon as a goal in the module is called, or as soon as it becomes the current type-in module.

current_module(M,F)

Succeeds if M are current modules associated to the file F.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.22 Miscellaneous

statistics/0

Send to the current user error stream general information on space used and time spent by the system.

 
?- statistics.
memory (total)        4784124 bytes
   program space      3055616 bytes:    1392224 in use,      1663392 free
                                                             2228132  max
   stack space        1531904 bytes:        464 in use,      1531440 free
     global stack:                           96 in use,       616684  max
      local stack:                          368 in use,       546208  max
   trail stack         196604 bytes:          8 in use,       196596 free

       0.010 sec. for 5 code, 2 stack, and 1 trail space overflows
       0.130 sec. for 3 garbage collections which collected 421000 bytes
       0.000 sec. for 0 atom garbage collections which collected 0 bytes
       0.880 sec. runtime
       1.020 sec. cputime
      25.055 sec. elapsed time

The example shows how much memory the system spends. Memory is divided into Program Space, Stack Space and Trail. In the example we have 3MB allocated for program spaces, with less than half being actually used. YAP also shows the maximum amount of heap space having been used which was over 2MB.

The stack space is divided into two stacks which grow against each other. We are in the top level so very little stack is being used. On the other hand, the system did use a lot of global and local stack during the previous execution (we refer the reader to a WAM tutorial in order to understand what are the global and local stacks).

YAP also shows information on how many memory overflows and garbage collections the system executed, and statistics on total execution time. Cputime includes all running time, runtime excludes garbage collection and stack overflow time.

statistics(?Param,-Info)

Gives statistical information on the system parameter given by first argument:

cputime

[Time since Boot,Time From Last Call to Cputime]
This gives the total cputime in milliseconds spent executing Prolog code, garbage collection and stack shifts time included.

garbage_collection

[Number of GCs,Total Global Recovered,Total Time Spent]
Number of garbage collections, amount of space recovered in kbytes, and total time spent doing garbage collection in milliseconds. More detailed information is available using yap_flag(gc_trace,verbose).

global_stack

[Global Stack Used,Execution Stack Free]
Space in kbytes currently used in the global stack, and space available for expansion by the local and global stacks.

local_stack

[Local Stack Used,Execution Stack Free]
Space in kbytes currently used in the local stack, and space available for expansion by the local and global stacks.

heap

[Heap Used,Heap Free]
Total space in kbytes not recoverable in backtracking. It includes the program code, internal data base, and, atom symbol table.

program

[Program Space Used,Program Space Free]
Equivalent to heap.

runtime

[Time since Boot,Time From Last Call to Runtime]
This gives the total cputime in milliseconds spent executing Prolog code, not including garbage collections and stack shifts. Note that until YAP4.1.2 the 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]
Number of times YAP had to expand the heap, the stacks, or the trail. More detailed information is available using yap_flag(gc_trace,verbose).

trail

[Trail Used,Trail Free]
Space in kbytes currently being used and still available for the trail.

walltime

[Time since Boot,Time From Last Call to Walltime]
This gives the clock time in milliseconds since starting Prolog.

time(:Goal)

Prints the CPU time and the wall time for the execution of Goal. Possible choice-points of Goal are removed. Based on the SWI-Prolog definition (minus reporting the number of inferences, which YAP currently does not support).

yap_flag(?Param,?Value)

Set or read system properties for Param:

argv

Read-only flag. It unifies with a list of atoms that gives the arguments to YAP after --.

bounded [ISO]

Read-only flag telling whether integers are bounded. The value depends on whether YAP uses the GMP library or not.

profiling

If off (default) do not compile call counting information for procedures. If on compile predicates so that they calls and retries to the predicate may be counted. Profiling data can be read through the call_count_data/3 built-in.

char_conversion [ISO]

Writable flag telling whether a character conversion table is used when reading terms. The default value for this flag is off except in sicstus and iso language modes, where it is on.

character_escapes [ISO]

Writable flag telling whether a character escapes are enables, on, or disabled, off. The default value for this flag is on.

debug [ISO]

If Value is unbound, tell whether debugging is on or off. If Value is bound to on enable debugging, and if it is bound to off disable debugging.

+

debugger_print_options

If bound, set the argument to the write_term/3 options the debugger uses to write terms. If unbound, show the current options.

dialect

Read-only flag that always returns yap.

discontiguous_warnings

If Value is unbound, tell whether warnings for discontiguous predicates are 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

If off (default) consider the character '$' a control character, if on consider '$' a lower case character.

double_quotes [ISO]

If Value is unbound, tell whether a double quoted list of characters token is converted to a list of atoms, chars, to a list of integers, codes, or to a single atom, atom. If Value is bound, set to the corresponding behavior. The default value is codes.

fast

If on allow fast machine code, if off (default) disable it. Only available in experimental implementations.

fileerrors

If on fileerrors is on, if off (default) fileerrors is disabled.

float_format

C-library printf() format specification used by write/1 and friends to determine how floating point numbers are printed. The default is %.15g. The specified value is passed to printf() without further checking. For example, if you want less digits printed, %g will print all floats using 6 digits instead of the default 15.

gc

If on allow garbage collection (default), if off disable it.

gc_margin

Set or show the minimum free stack before starting garbage collection. The default depends on total stack size.

gc_trace

If off (default) do not show information on garbage collection and stack shifts, if on inform when a garbage collection or stack shift happened, if verbose give detailed information on garbage collection and stack shifts. Last, if very_verbose give detailed information on data-structures found during the garbage collection process, namely, on choice-points.

generate_debugging_info

If true (default) generate debugging information for procedures, including source mode. If false predicates no information is generated, although debugging is still possible, and source mode is disabled.

host_type

Return configure system information, including the machine-id for which YAP was compiled and Operating System information.

index

If on allow indexing (default), if off disable it.

informational_messages

If 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]

Read-only flag telling the rounding function used for integers. Takes the value down for the current version of YAP.

language

Choose whether YAP is closer to C-Prolog, 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]

Read-only flag telling the maximum arity of a functor. Takes the value unbounded for the current version of YAP.

max_integer [ISO]

Read-only flag telling the maximum integer in the implementation. Depends on machine and Operating System architecture, and on whether YAP uses the GMP multi-precision library. If bounded is false, requests for max_integer will fail.

max_tagged_integer

Read-only flag telling the maximum integer we can store as a single word. Depends on machine and Operating System architecture. It can be used to find the word size of the current machine.

min_integer [ISO]

Read-only flag telling the minimum integer in the implementation. Depends on machine and Operating System architecture, and on whether YAP uses the GMP multi-precision library. If bounded is false, requests for min_integer will fail.

min_tagged_integer

Read-only flag telling the minimum integer we can store as a single word. Depends on machine and Operating System architecture.

n_of_integer_keys_in_bb

Read or set the size of the hash table that is used for looking up the blackboard when the key is an integer.

n_of_integer_keys_in_db

Read or set the size of the hash table that is used for looking up the internal data-base when the key is an integer.

open_expands_filename

If true the open/3 builtin performs filename-expansion before opening a file (SICStus Prolog like). If false it does not (SWI-Prolog like).

profiling

If 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

If Value is unbound, tell whether warnings for procedures defined in several different files are on or off. If Value is bound to on enable these warnings, and if it is bound to off disable them. The default for YAP is off, unless we are in sicstus or iso mode.

shared_object_search_path

Name of the environment variable used by the system to search for shared objects.

single_var_warnings

If Value is unbound, tell whether warnings for singleton variables are 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

If Value is unbound, tell whether strict ISO compatibility mode is 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 programs compliant with this mode will work the same way in every Prolog and in every platform. We thus believe this mode is mostly useful when investigating how a program depends on a Prolog's platform specific features.

stack_dump_on_error

If on show a stack dump when YAP finds an error. The default is off.

syntax_errors

Control action to be taken after syntax errors while executing read/1, read/2, or read_term/3:

dec10

Report the syntax error and retry reading the term.

fail

Report the syntax error and fail (default).

error

Report the syntax error and generate an error.

quiet

Just fail

system_options

This read only flag tells which options were used to compile YAP. Currently it informs whether the system supports big_numbers, coroutining, depth_limit, low_level_tracer, or-parallelism, rational_trees, readline, tabling, threads, or the wam_profiler.

tabling_mode

Sets or reads the tabling mode for all tabled predicates. Please see section Tabling for the list of options.

to_chars_mode

Define whether YAP should follow 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

+If bound, set the argument to a goal to be executed before entering the top-level. If unbound show the current goal or true if none is presented. Only the first solution is considered and the goal is not backtracked into.

+

toplevel_print_options

+If bound, set the argument to the write_term/3 options used to write terms from the top-level. If unbound, show the current options.

typein_module

If bound, set the current working or type-in module to the argument, which must be an atom. If unbound, unify the argument with the current working module.

unix

Read-only boolean flag that unifies with tr true if YAP is running on an Unix system. Defined if the C-compiler used to compile this version of YAP either defines __unix__ or unix.

unknown [ISO]

Corresponds to calling the unknown/2 built-in.

update_semantics

Define whether YAP should follow 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

If the second argument is bound to a stream, set user_error to this stream. If the second argument is unbound, unify the argument with the current user_error stream.

By default, the user_error stream is set to a stream corresponding to the Unix stderr stream.

The next example shows how to use this flag:

 
   ?- open( '/dev/null', append, Error,
           [alias(mauri_tripa)] ).

Error = '$stream'(3) ? ;

no
   ?- set_prolog_flag(user_error, mauri_tripa).

close(mauri_tripa).

yes
   ?- 

We execute three commands. First, we open a stream in write mode and give it an alias, in this case mauri_tripa. Next, we set user_error to the stream via the alias. Note that after we did so prompts from the system were redirected to the stream mauri_tripa. Last, we close the stream. At this point, YAP automatically redirects the user_error alias to the original stderr.

user_input

If the second argument is bound to a stream, set 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

If the second argument is bound to a stream, set user_output to this stream. If the second argument is unbound, unify the argument with the current user_output stream.

By default, the user_output stream is set to a stream corresponding to the Unix stdout stream.

verbose

If normal allow printing of informational and banner messages, such as the ones that are printed when consulting. If silent disable printing these messages. It is normal by default except if YAP is booted with the -q or -L flag.

verbose_load

If true allow printing of informational messages when consulting files. If false disable printing these messages. It is normal by default except if YAP is booted with the -L flag.

version

Read-only flag that returns an atom with the current version of YAP.

version_data

Read-only flag that reads a term of the form yap(Major,Minor,Patch,Undefined), where Major is the major version, Minor is the minor version, and Patch is the patch number.

windows

Read-only boolean flag that unifies with tr true if YAP is running on an Windows machine.

write_strings

Writable flag telling whether the system should write lists of integers that are writable character codes using the list notation. It is on if enables or off if disabled. The default value for this flag is off.

max_workers

Read-only flag telling the maximum number of parallel processes.

max_threads

Read-only flag telling the maximum number of Prolog threads that can be created.

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]

Defines the operator A or the list of operators A with type T (which must be one of xfx, xfy,yfx, xf, yf, fx or fy) and precedence P (see appendix iv for a list of predefined operators).

Note that if there is a preexisting operator with the same name and type, this operator will be discarded. Also, ',' may not be defined as an operator, and it is not allowed to have the same for an infix and a postfix operator.

current_op(P,T,F) [ISO]

Defines the relation: P is a currently defined operator of type T and precedence P.

prompt(-A,+B)

Changes YAP input prompt from A to B.

initialization

Execute the goals defined by initialization/1. Only the first answer is considered.

prolog_initialization(G)

Add a goal to be executed on system initialization. This is compatible with SICStus Prolog's initialization/1.

version

Write YAP's boot message.

version(-Message)

Add a message to be written when yap boots or after aborting. It is not possible to remove messages.

prolog_load_context(?Key, ?Value)

Obtain information on what is going on in the compilation process. The following keys are available:

directory

Full name for the directory where YAP is currently consulting the file.

file

Full name for the file currently being consulted. Notice that included filed are ignored.

module

Current source module.

source

Full name for the file currently being read in, which may be consulted, reconsulted, or included.

stream

Stream currently being read in.

term_position

Stream position at the stream currently being read in.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7. Library Predicates

Library files reside in the library_directory path (set by the LIBDIR variable in the Makefile for YAP). Currently, most files in the library are from the Edinburgh Prolog library.

Library, Extensions, Built-ins, Top 7.1 Apply Macros  SWI-Compatible Apply library. 7.2 Apply Macros  Apply a Predicate to a list or to sub-terms. 7.3 Association Lists  Binary Tree Implementation of Association Lists. 7.4 AVL Trees  Predicates to add and lookup balanced binary trees. 7.22 Call Cleanup  Call With registered Cleanup Calls 7.26 Directed Graphs  Directed Graphs Implemented With Red-Black Trees 7.5 Heaps  Labelled binary tree where the key of each node is less than or equal to the keys of its children. 7.28 LAM  LAM MPI 7.6 List Manipulation  List Manipulation 7.7 Matrix Library  Matrix Objects 7.8 MATLAB Package Interface  Matlab Interface 7.9 Non-Backtrackable Data Structures  Queues, Heaps, and Beams. 7.10 Ordered Sets  Ordered Set Manipulation 7.11 Pseudo Random Number Integer Generator  Pseudo Random Numbers 7.12 Queues  Queue Manipulation 7.13 Random Number Generator  Random Numbers 7.14 Read Utilities  SWI inspired utilities for fast stream scanning. 7.15 Red-Black Trees  Predicates to add, lookup and delete in red-black binary trees. 7.16 Regular Expressions  Regular Expression Manipulation 7.17 Splay Trees  Splay Trees 7.18 Reading From and Writing To Strings  Writing To and Reading From Strings 7.19 Calling The Operating System from YAP  System Utilities 7.20 Utilities On Terms  Utilities on Terms 7.23 Calls With Timeout  Call With Timeout 7.24 Updatable Binary Trees  Updatable Binary Trees 7.21 Trie DataStructure  Trie Data Structure 7.25 Unweighted Graphs  Unweighted Graphs 7.27 Undirected Graphs  Undirected Graphs Using DGraphs


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.1 Apply Macros

This library provides a SWI-compatible set of utilities for applying a predicate to all elements of a list. The library just forwards definitions from the apply_macros library.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.2 Apply Macros

This library provides a set of utilities for applying a predicate to all elements of a list or to all sub-terms of a term. They allow to easily perform the most common do-loop constructs in Prolog. To avoid performance degradation due to apply/2, each call creates an equivalent Prolog program, without meta-calls, which is executed by the Prolog engine instead. Note that if the equivalent Prolog program already exists, it will be simply used. The library is based on code by Joachim Schimpf.

The following routines are available once included with the use_module(library(apply_macros)) command.

maplist(+Pred, ?ListIn, ?ListOut)

Creates ListOut by applying the predicate Pred to all elements of ListIn.

checklist(+Pred, +List)

Succeeds if the predicate Pred succeeds on all elements of List.

selectlist(+Pred, +ListIn, ?ListOut)

Creates ListOut of all list elements of ListIn that pass a given test

convlist(+Pred, +ListIn, ?ListOut)

A combination of maplist and selectlist: creates ListOut by applying the predicate Pred to all list elements on which Pred succeeds

sumlist(+Pred, +List, ?AccIn, ?AccOut)

Calls Pred on all elements of List and collects a result in Accumulator.

mapargs(+Pred, ?TermIn, ?TermOut)

Creates TermOut by applying the predicate Pred to all arguments of TermIn

sumargs(+Pred, +Term, ?AccIn, ?AccOut)

Calls the predicate Pred on all arguments of Term and collects a result in Accumulator

mapnodes(+Pred, +TermIn, ?TermOut)

Creates TermOut by applying the predicate Pred to all sub-terms of TermIn (depth-first and left-to-right order)

checknodes(+Pred, +Term)

Succeeds if the predicate Pred succeeds on all sub-terms of Term (depth-first and left-to-right order)

sumnodes(+Pred, +Term, ?AccIn, ?AccOut)

Calls the predicate Pred on all sub-terms of Term and collect a result in Accumulator (depth-first and left-to-right order)

include(+Pred, +ListIn, ?ListOut)

Same as selectlist/3.

exclude(+Goal, +List1, ?List2)

Filter elements for which Goal fails. True if List2 contains those elements Xi of List1 for which call(Goal, Xi) fails.

partition(+Pred, +List1, ?Included, ?Excluded)

Filter elements of List according to Pred. True if Included contains all elements for which call(Pred, X) succeeds and Excluded contains the remaining elements.

partition(+Pred, +List1, ?Lesser, ?Equal, ?Greater)

Filter list according to Pred in three sets. For each element Xi of List, its destination is determined by call(Pred, Xi, Place), where Place must be unified to one of <, = or >. Pred must be deterministic.

Examples:

 
%given
plus(X,Y,Z) :- Z is X + Y.
plus_if_pos(X,Y,Z) :- Y > 0, Z is X + Y.
vars(X, Y, [X|Y]) :- var(X), !.
vars(_, Y, Y).
trans(TermIn, TermOut) :-
  (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] [ ? ]

7.3 Association Lists

The following association list manipulation predicates are available once included with the use_module(library(assoc)) command. The original library used Richard O'Keefe's implementation, on top of unbalanced binary trees. The current code utilises code from the red-black trees library and emulates the SICStus Prolog interface.

assoc_to_list(+Assoc,?List)

Given an association list Assoc unify List with a list of the form Key-Val, where the elements Key are in ascending order.

del_assoc(+Key, +Assoc, ?Val, ?NewAssoc)

Succeeds if NewAssoc is an association list, obtained by removing the element with Key and Val from the list Assoc.

del_max_assoc(+Assoc, ?Key, ?Val, ?NewAssoc)

Succeeds if NewAssoc is an association list, obtained by removing the largest element of the list, with Key and Val from the list Assoc.

del_min_assoc(+Assoc, ?Key, ?Val, ?NewAssoc)

Succeeds if NewAssoc is an association list, obtained by removing the smallest element of the list, with Key and Val from the list Assoc.

empty_assoc(+Assoc)

Succeeds if association list Assoc is empty.

gen_assoc(+Assoc,?Key,?Value)

Given the association list Assoc, unify Key and Value with two associated elements. It can be used to enumerate all elements in the association list.

get_assoc(+Key,+Assoc,?Value)

If Key is one of the elements in the association list Assoc, return the associated value.

get_assoc(+Key,+Assoc,?Value,+NAssoc,?NValue)

If Key is one of the elements in the association list Assoc, return the associated value Value and a new association list NAssoc where Key is associated with NValue.

get_prev_assoc(+Key,+Assoc,?Next,?Value)

If Key is one of the elements in the association list Assoc, return the previous key, Next, and its value, Value.

get_next_assoc(+Key,+Assoc,?Next,?Value)

If Key is one of the elements in the association list Assoc, return the next key, Next, and its value, Value.

is_assoc(+Assoc)

Succeeds if Assoc is an association list, that is, if it is a red-black tree.

list_to_assoc(+List,?Assoc)

Given a list List such that each element of List is of the form Key-Val, and all the Keys are unique, Assoc is the corresponding association list.

map_assoc(+Pred,+Assoc)

Succeeds if the unary predicate name Pred(Val) holds for every element in the association list.

map_assoc(+Pred,+Assoc,?New)

Given the binary predicate name Pred and the association list Assoc, New in an association list with keys in Assoc, and such that if Key-Val is in Assoc, and Key-Ans is in New, then Pred(Val,Ans) holds.

max_assoc(+Assoc,-Key,?Value)

Given the association list Assoc, Key in the largest key in the list, and Value the associated value.

min_assoc(+Assoc,-Key,?Value)

Given the association list Assoc, Key in the smallest key in the list, and Value the associated value.

ord_list_to_assoc(+List,?Assoc)

Given an ordered list List such that each element of List is of the form Key-Val, and all the Keys are unique, Assoc is the corresponding association list.

put_assoc(+Key,+Assoc,+Val,+New)

The association list New includes and element of association key with Val, and all elements of Assoc that did not have key Key.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.4 AVL Trees

AVL trees are balanced search binary trees. They are named after their inventors, Adelson-Velskii and Landis, and they were the first dynamically balanced trees to be proposed. The YAP AVL tree manipulation predicates library uses code originally written by Martin van Emdem and published in the Logic Programming Newsletter, Autumn 1981. A bug in this code was fixed by Philip Vasey, in the Logic Programming Newsletter, Summer 1982. The library currently only includes routines to insert and lookup elements in the tree. Please try red-black trees if you need deletion.

avl_new(+T)

Create a new tree.

avl_insert(+Key,?Value,+T0,-TF)

Add an element with key Key and Value to the AVL tree T0 creating a new AVL tree TF. Duplicated elements are allowed.

avl_lookup(+Key,-Value,+T)

Lookup an element with key Key in the AVL tree T, returning the value Value.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.5 Heaps

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)

Inserts the new Key-Datum pair into the heap. The insertion is not stable, that is, if you insert several pairs with the same Key it is not defined which of them will come out first, and it is possible for any of them to come out first depending on the history of the heap.

empty_heap(?Heap)

Succeeds if Heap is an empty heap.

get_from_heap(+Heap,-key,-Datum,-Heap)

Returns the Key-Datum pair in OldHeap with the smallest Key, and also a Heap which is the OldHeap with that pair deleted.

heap_size(+Heap, -Size)

Reports the number of elements currently in the heap.

heap_to_list(+Heap, -List)

Returns the current set of Key-Datum pairs in the Heap as a List, sorted into ascending order of Keys.

list_to_heap(+List, -Heap)

Takes a list of Key-Datum pairs (such as keysort could be used to sort) and forms them into a heap.

min_of_heap(+Heap, -Key, -Datum)

Returns the Key-Datum pair at the top of the heap (which is of course the pair with the smallest Key), but does not remove it from the heap.

min_of_heap(+Heap, -Key1, -Datum1,

-Key2, -Datum2) Returns the smallest (Key1) and second smallest (Key2) pairs in the heap, without deleting them.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.6 List Manipulation

The following list manipulation routines are available once included with the use_module(library(lists)) command.

append(?Prefix,?Suffix,?Combined)

True when all three arguments are lists, and the members of Combined are the members of Prefix followed by the members of Suffix. It may be used to form Combined from a given Prefix, Suffix or to take a given Combined apart.

append(?Lists,?Combined)

Holds if the lists of Lists can be concatenated as a Combined list.

delete(+List, ?Element, ?Residue)

True when List is a list, in which Element may or may not occur, and Residue is a copy of List with all elements identical to Element deleted.

flatten(+List, ?FlattenedList)

Flatten a list of lists List into a single list FlattenedList.

 
?- flatten([[1],[2,3],[4,[5,6],7,8]],L).

L = [1,2,3,4,5,6,7,8] ? ;

no
is_list(+List)

True when List is a proper list. That is, List is bound to the empty list (nil) or a term with functor '.' and arity 2.

last(+List,?Last)

True when List is a list and Last is identical to its last element.

list_concat(+Lists,?List)

True when Lists is a list of lists and List is the concatenation of Lists.

member(?Element, ?Set)

True when Set is a list, and Element occurs in it. It may be used to test for an element or to enumerate all the elements by backtracking.

memberchk(+Element, +Set)

As 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)

True when Elem is the Nth member of List, counting the first as element 0. (That is, throw away the first N elements and unify Elem with the next.) It can only be used to select a particular element given the list and index. For that task it is more efficient than member/2

nth(?N, ?List, ?Elem)

The same as nth0/3, except that it counts from 1, that is nth(1, [H|_], H).

nth0(?N, ?List, ?Elem, ?Rest)

Unifies Elem with the Nth element of List, counting from 0, and Rest with the other elements. It can be used to select the Nth element of List (yielding Elem and Rest), or to insert Elem before the Nth (counting from 1) element of Rest, when it yields List, e.g. 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)

Unifies Elem with the Nth element of List, counting from 1, and Rest with the other elements. It can be used to select the Nth element of List (yielding Elem and Rest), or to insert Elem before the Nth (counting from 1) element of Rest, when it yields List, e.g. 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)

True when List and Perm are permutations of each other.

remove_duplicates(+List, ?Pruned)

Removes duplicated elements from List. Beware: if the List has non-ground elements, the result may surprise you.

reverse(+List, ?Reversed)

True when List and Reversed are lists with the same elements but in opposite orders.

same_length(?List1, ?List2)

True when List1 and List2 are both lists and have the same number of elements. No relation between the values of their elements is implied. Modes 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)

True when Set is a list, Element occurs in Set, and Residue is everything in Set except Element (things stay in the same order).

sublist(?Sublist, ?List)

True when both append(_,Sublist,S) and append(S,_,List) hold.

suffix(?Suffix, ?List)

Holds when append(_,Suffix,List) holds.

sum_list(?Numbers, ?Total)

True when Numbers is a list of numbers, and Total is their sum.

sumlist(?Numbers, ?Total)

True when Numbers is a list of integers, and Total is their sum. The same as sum_list/2, please do use sum_list/2 instead.

max_list(?Numbers, ?Max)

True when Numbers is a list of numbers, and Max is the maximum.

min_list(?Numbers, ?Min)

True when Numbers is a list of numbers, and Min is the minimum.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.7 Matrix Library

This package provides a fast implementation of multi-dimensional matrices of integers and floats. In contrast to dynamic arrays, these matrices are multi-dimensional and compact. In contrast to static arrays. these arrays are allocated in the stack. Matrices are available by loading the library library(matrix).

Notice that the functionality in this library is only partial. Please contact the YAP maintainers if you need for extra functionality.

matrix_new(+Type,+Dims,-Matrix)

Create a new matrix Matrix of type Type, which may be one of ints or floats, and with a list of dimensions Dims. The matrix will be initialised to zeros.

 
?- matrix_new(ints,[2,3],Matrix).

Matrix = 0

Notice that currently YAP will always write a matrix as 0.

matrix_new(+Type,+Dims,+List,-Matrix)

Create a new matrix Matrix of type Type, which may be one of ints or floats, with dimensions Dims, and initialised from list List.

matrix_new_set(?Dims,+OldMatrix,+Value,-NewMatrix)

Create a new matrix NewMatrix of type Type, with dimensions Dims. The elements of NewMatrix are set to Value.

matrix_dims(+Matrix,-Dims)

Unify Dims with a list of dimensions for Matrix.

matrix_ndims(+Matrix,-Dims)

Unify NDims with the number of dimensions for Matrix.

matrix_size(+Matrix,-NElems)

Unify NElems with the number of elements for Matrix.

matrix_type(+Matrix,-Type)

Unify NElems with the type of the elements in Matrix.

matrix_to_list(+Matrix,-Elems)

Unify Elems with the list including all the elements in Matrix.

matrix_get(+Matrix,+Position,-Elem)

Unify Elem with the element of Matrix at position Position.

matrix_set(+Matrix,+Position,+Elem)

Set the element of Matrix at position Position to Elem.

matrix_set_all(+Matrix,+Elem)

Set all element of Matrix to Elem.

matrix_add(+Matrix,+Position,+Operand)

Add Operand to the element of Matrix at position Position.

matrix_inc(+Matrix,+Position)

Increment the element of Matrix at position Position.

matrix_inc(+Matrix,+Position,-Element)

Increment the element of Matrix at position Position and unify with Element.

matrix_dec(+Matrix,+Position)

Decrement the element of Matrix at position Position.

matrix_dec(+Matrix,+Position,-Element)

Decrement the element of Matrix at position Position and unify with Element.

matrix_arg_to_offset(+Matrix,+Position,-Offset)

Given matrix Matrix return what is the numerical Offset of the element at Position.

matrix_offset_to_arg(+Matrix,-Offset,+Position)

Given a position Position for matrix Matrix return the corresponding numerical Offset from the beginning of the matrix.

matrix_max(+Matrix,+Max)

Unify Max with the maximum in matrix Matrix.

matrix_maxarg(+Matrix,+Maxarg)

Unify Max with the position of the maximum in matrix Matrix.

matrix_min(+Matrix,+Min)

Unify Min with the minimum in matrix Matrix.

matrix_minarg(+Matrix,+Minarg)

Unify Min with the position of the minimum in matrix Matrix.

matrix_sum(+Matrix,+Sum)

Unify Sum with the sum of all elements in matrix Matrix.

matrix_agg_lines(+Matrix,+Aggregate)

If Matrix is a n-dimensional matrix, unify Aggregate with the n-1 dimensional matrix where each element is obtained by adding all Matrix elements with same last n-1 index.

matrix_agg_cols(+Matrix,+Aggregate)

If Matrix is a n-dimensional matrix, unify Aggregate with the one dimensional matrix where each element is obtained by adding all Matrix elements with same first index.

matrix_op(+Matrix1,+Matrix2,+Op,-Result)

Result is the result of applying Op to matrix Matrix1 and Matrix2. Currently, only addition (+) is supported.

matrix_op_to_all(+Matrix1,+Op,+Operand,-Result)

Result is the result of applying Op to all elements of Matrix1, with Operand as the second argument. Currently, only addition (+), multiplication (+), and division (/) are supported.

matrix_op_to_lines(+Matrix1,+Lines,+Op,-Result)

Result is the result of applying Op to all elements of Matrix1, with the corresponding element in Lines as the second argument. Currently, only division (/) is supported.

matrix_op_to_cols(+Matrix1,+Cols,+Op,-Result)

Result is the result of applying Op to all elements of Matrix1, with the corresponding element in Cols as the second argument. Currently, only addition (+) is supported. Notice that Cols will have n-1 dimensions.

matrix_shuffle(+Matrix,+NewOrder,-Shuffle)

Shuffle the dimensions of matrix Matrix according to NewOrder. The list NewOrder must have all the dimensions of Matrix, starting from 0.

matrix_transpose(+Matrix,-Transpose)

Transpose matrix Matrix to Transpose. Equivalent to:

 
matrix_transpose(Matrix,Transpose) :-
        matrix_shuffle(Matrix,[1,0],Transpose).
matrix_expand(+Matrix,+NewDimensions,-New)

Expand Matrix to occupy new dimensions. The elements in NewDimensions are either 0, for an existing dimension, or a positive integer with the size of the new dimension.

matrix_select(+Matrix,+Dimension,+Index,-New)

Select from Matrix the elements who have Index at Dimension.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.8 MATLAB Package Interface

The MathWorks MATLAB is a widely used package for array processing. YAP now includes a straightforward interface to MATLAB. To actually use it, you need to install YAP calling configure with the --with-matlab=DIR option, and you need to call use_module(library(lists)) command.

start_matlab(+Options)

Start a matlab session. The argument Options may either be the empty string/atom or the command to call matlab. The command may fail.

close_matlab

Stop the current matlab session.

matlab_on

Holds if a matlab session is on.

matlab_eval_string(+Command)

Holds if matlab evaluated successfully the command Command.

matlab_eval_string(+Command, -Answer)

MATLAB will evaluate the command Command and unify Answer with a string reporting the result.

matlab_cells(+Size, ?Array)

MATLAB will create an empty vector of cells of size Size, and if Array is bound to an atom, store the array in the matlab variable with name Array. Corresponds to the MATLAB command cells.

matlab_cells(+SizeX, +SizeY, ?Array)

MATLAB will create an empty array of cells of size SizeX and SizeY, and if Array is bound to an atom, store the array in the matlab variable with name Array. Corresponds to the MATLAB command cells.

matlab_initialized_cells(+SizeX, +SizeY, +List, ?Array)

MATLAB will create an array of cells of size SizeX and SizeY, initialized from the list List, and if Array is bound to an atom, store the array in the matlab variable with name Array.

matlab_matrix(+SizeX, +SizeY, +List, ?Array)

MATLAB will create an array of floats of size SizeX and SizeY, initialized from the list List, and if Array is bound to an atom, store the array in the matlab variable with name Array.

matlab_set(+MatVar, +X, +Y, +Value)

Call MATLAB to set element MatVar(X, Y) to Value. Notice that this command uses the MATLAB array access convention.

matlab_get_variable(+MatVar, -List)

Unify MATLAB variable MatVar with the List List.

matlab_item(+MatVar, +X, ?Val)

Read or set MATLAB MatVar(X) from/to Val. Use C notation for matrix access (ie, starting from 0).

matlab_item(+MatVar, +X, +Y, ?Val)

Read or set MATLAB MatVar(X,Y) from/to Val. Use C notation for matrix access (ie, starting from 0).

matlab_item1(+MatVar, +X, ?Val)

Read or set MATLAB MatVar(X) from/to Val. Use MATLAB notation for matrix access (ie, starting from 1).

matlab_item1(+MatVar, +X, +Y, ?Val)

Read or set MATLAB MatVar(X,Y) from/to Val. Use MATLAB notation for matrix access (ie, starting from 1).

matlab_sequence(+Min, +Max, ?Array)

MATLAB will create a sequence going from Min to Max, and if Array is bound to an atom, store the sequence in the matlab variable with name Array.

matlab_vector(+Size, +List, ?Array)

MATLAB will create a vector of floats of size Size, initialized from the list List, and if Array is bound to an atom, store the array in the matlab variable with name Array.

matlab_zeros(+Size, ?Array)

MATLAB will create a vector of zeros of size Size, and if Array is bound to an atom, store the array in the matlab variable with name Array. Corresponds to the MATLAB command zeros.

matlab_zeros(+SizeX, +SizeY, ?Array)

MATLAB will create an array of zeros of size SizeX and SizeY, and if Array is bound to an atom, store the array in the matlab variable with name Array. Corresponds to the MATLAB command zeros.

matlab_zeros(+SizeX, +SizeY, +SizeZ, ?Array)

MATLAB will create an array of zeros of size SizeX, SizeY, and SizeZ. If Array is bound to an atom, store the array in the matlab variable with name Array. Corresponds to the MATLAB command zeros.

matlab_zeros(+SizeX, +SizeY, +SizeZ, ?Array)

MATLAB will create an array of zeros of size SizeX, SizeY, and SizeZ. If Array is bound to an atom, store the array in the matlab variable with name Array. Corresponds to the MATLAB command zeros.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.9 Non-Backtrackable Data Structures

The following routines implement well-known data-structures using global non-backtrackable variables (implemented on the Prolog stack). The data-structures currently supported are Queues, Heaps, and Beam for Beam search. They are allowed through library(nb).

nb_queue(-Queue)

Create a Queue.

nb_queue_close(+Queue, -Head, ?Tail)

Unify the queue Queue with a difference list Head-Tail. The queue will now be empty and no further elements can be added.

nb_queue_queue(+Queue, +Element)

Add Element to the front of the queue Queue.

nb_queue_dequeue(+Queue, -Element)

Remove Element from the front of the queue Queue. Fail if the queue is empty.

nb_queue_peek(+Queue, -Element)

Element is the front of the queue Queue. Fail if the queue is empty.

nb_queue_size(+Queue, -Size)

Unify Size with the number of elements in the queue Queue.

nb_queue_empty(+Queue)

Succeeds if Queue is empty.

nb_heap(+DefaultSize,-Heap)

Create a Heap with default size DefaultSize. Note that size will expand as needed.

nb_heap_close(+Heap)

Close the heap Heap: no further elements can be added.

nb_heap_add(+Heap, +Key, +Value)

Add Key-Value to the heap Heap. The key is sorted on Key only.

nb_heap_del(+Heap, -Key, -Value)

Remove element Key-Value with smallest Value in heap Heap. Fail if the heap is empty.

nb_heap_peek(+Heap, -Key, -Value))

Key-Value is the element with smallest Key in the heap Heap. Fail if the heap is empty.

nb_heap_size(+Heap, -Size)

Unify Size with the number of elements in the heap Heap.

nb_heap_empty(+Heap)

Succeeds if Heap is empty.

nb_beam(+DefaultSize,-Beam)

Create a Beam with default size DefaultSize. Note that size is fixed throughout.

nb_beam_close(+Beam)

Close the beam Beam: no further elements can be added.

nb_beam_add(+Beam, +Key, +Value)

Add Key-Value to the beam Beam. The key is sorted on Key only.

nb_beam_del(+Beam, -Key, -Value)

Remove element Key-Value with smallest Value in beam Beam. Fail if the beam is empty.

nb_beam_peek(+Beam, -Key, -Value))

Key-Value is the element with smallest Key in the beam Beam. Fail if the beam is empty.

nb_beam_size(+Beam, -Size)

Unify Size with the number of elements in the beam Beam.

nb_beam_empty(+Beam)

Succeeds if Beam is empty.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.10 Ordered Sets

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)

Holds when Set is the ordered representation of the set represented by the unordered representation List.

merge(+List1, +List2, -Merged)

Holds when Merged is the stable merge of the two given lists.

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)

Inserting Element in Set1 returns Set2. It should give exactly the same result as merge(Set1, [Element], Set2), but a bit faster, and certainly more clearly. The same as ord_insert/3.

ord_del_element(+Set1, +Element, ?Set2)

Removing Element from Set1 returns Set2.

ord_disjoint(+Set1, +Set2)

Holds when the two ordered sets have no element in common.

ord_member(+Element, +Set)

Holds when Element is a member of Set.

ord_insert(+Set1, +Element, ?Set2)

Inserting Element in Set1 returns Set2. It should give exactly the same result as merge(Set1, [Element], Set2), but a bit faster, and certainly more clearly. The same as ord_add_element/3.

ord_intersect(+Set1, +Set2)

Holds when the two ordered sets have at least one element in common.

ord_intersection(+Set1, +Set2, ?Intersection)

Holds when Intersection is the ordered representation of Set1 and Set2.

ord_intersection(+Set1, +Set2, ?Intersection, ?Diff)

Holds when Intersection is the ordered representation of Set1 and Set2. Diff is the difference between Set2 and Set1.

ord_seteq(+Set1, +Set2)

Holds when the two arguments represent the same set.

ord_setproduct(+Set1, +Set2, -Set)

If Set1 and Set2 are ordered sets, Product will be an ordered set of x1-x2 pairs.

ord_subset(+Set1, +Set2)

Holds when every element of the ordered set Set1 appears in the ordered set Set2.

ord_subtract(+Set1, +Set2, ?Difference)

Holds when Difference contains all and only the elements of Set1 which are not also in Set2.

ord_symdiff(+Set1, +Set2, ?Difference)

Holds when Difference is the symmetric difference of Set1 and Set2.

ord_union(+Sets, ?Union)

Holds when Union is the union of the lists Sets.

ord_union(+Set1, +Set2, ?Union)

Holds when Union is the union of Set1 and Set2.

ord_union(+Set1, +Set2, ?Union, ?Diff)

Holds when Union is the union of Set1 and Set2 and Diff is the difference.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11 Pseudo Random Number Integer Generator

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)

Produces a random non-negative integer I whose low bits are not all that random, so it should be scaled to a smaller range in general. The integer I is in the range 0 .. 2^(w-1) - 1. You can use:

 
rannum(X) :- yap_flag(max_integer,MI), rannum(R), X is R/MI.

to obtain a floating point number uniformly distributed between 0 and 1.

ranstart

Initialize the random number generator using a built-in seed. The ranstart/0 built-in is always called by the system when loading the package.

ranstart(+Seed)

Initialize the random number generator with user-defined Seed. The same Seed always produces the same sequence of numbers.

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] [ ? ]

7.12 Queues

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)

Creates a new empty queue. It should only be used to create a new queue.

join_queue(+Element, +OldQueue, -NewQueue)

Adds the new element at the end of the queue.

list_join_queue(+List, +OldQueue, -NewQueue)

Ads the new elements at the end of the queue.

jump_queue(+Element, +OldQueue, -NewQueue)

Adds the new element at the front of the list.

list_jump_queue(+List, +OldQueue, +NewQueue)

Adds all the elements of List at the front of the queue.

head_queue(+Queue, ?Head)

Unifies Head with the first element of the queue.

serve_queue(+OldQueue, +Head, -NewQueue)

Removes the first element of the queue for service.

empty_queue(+Queue)

Tests whether the queue is empty.

length_queue(+Queue, -Length)

Counts the number of elements currently in the queue.

list_to_queue(+List, -Queue)

Creates a new queue with the same elements as List.

queue_to_list(+Queue, -List)

Creates a new list with the same elements as Queue.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.13 Random Number Generator

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)

Unify Key with a term of the form rand(X,Y,Z) describing the current state of the random number generator.

random(-Number)

Unify Number with a floating-point number in the range [0...1).

random(+LOW, +HIGH, -NUMBER)

Unify Number with a number in the range [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)

Unify Numbers with a list of LENGTH unique random integers in the range [1 ...MAX).

randset(+LENGTH, +MAX, -Numbers)

Unify Numbers with an ordered list of LENGTH unique random integers in the range [1 ...MAX).

setrand(+Key)

Use a term of the form 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] [ ? ]

7.14 Read Utilities

The readutil library contains primitives to read lines, files, multiple terms, etc.

read_line_to_codes(+Stream, -Codes)

Read the next line of input from Stream and unify the result with Codes after the line has been read. A line is ended by a newline character or end-of-file. Unlike read_line_to_codes/3, this predicate removes trailing newline character.

On end-of-file the atom end_of_file is returned. See also at_end_of_stream/[0,1].

read_line_to_codes(+Stream, -Codes, ?Tail)

Diference-list version to read an input line to a list of character codes. Reading stops at the newline or end-of-file character, but unlike read_line_to_codes/2, the newline is retained in the output. This predicate is especially useful for readine a block of lines upto some delimiter. The following example reads an HTTP header ended by a blank line:

 
read_header_data(Stream, Header) :-
	read_line_to_codes(Stream, Header, Tail),
	read_header_data(Header, Stream, Tail).

read_header_data("\r\n", _, _) :- !.
read_header_data("\n", _, _) :- !.
read_header_data("", _, _) :- !.
read_header_data(_, Stream, Tail) :-
	read_line_to_codes(Stream, Tail, NewTail),
	read_header_data(Tail, Stream, NewTail).
read_stream_to_codes(+Stream, -Codes)

Read all input until end-of-file and unify the result to Codes.

read_stream_to_codes(+Stream, -Codes, ?Tail)

Difference-list version of read_stream_to_codes/2.

read_file_to_codes(+Spec, -Codes, +Options)

Read a file to a list of character codes. Currently ignores Options.

read_file_to_terms(+Spec, -Terms, +Options)

Read a file to a list of prolog terms (see read/1).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.15 Red-Black Trees

Red-Black trees are balanced search binary trees. They are named because nodes can be classified as either red or black. The code we include is based on "Introduction to Algorithms", second edition, by Cormen, Leiserson, Rivest and Stein. The library includes routines to insert, lookup and delete elements in the tree.

rb_new(?T)

Create a new tree.

rb_empty(?T)

Succeeds if tree T is empty.

is_rbtree(+T)

Check whether T is a valid red-black tree.

rb_insert(+T0,+Key,?Value,+TF)

Add an element with key Key and Value to the tree T0 creating a new red-black tree TF. Duplicated elements are not allowed.

Add a new element with key Key and Value to the tree T0 creating a new red-black tree TF. Fails is an element with Key exists in the tree.

rb_lookup(+Key,-Value,+T)

Backtrack through all elements with key Key in the red-black tree T, returning for each the value Value.

rb_lookupall(+Key,-Value,+T)

Lookup all elements with key Key in the red-black tree T, returning the value Value.

rb_delete(+T,+Key,-TN)

Delete element with key Key from the tree T, returning a new tree TN.

rb_delete(+T,+Key,-Val,-TN)

Delete element with key Key from the tree T, returning the value Val associated with the key and a new tree TN.

rb_del_min(+T,-Key,-Val,-TN)

Delete the least element from the tree T, returning the key Key, the value Val associated with the key and a new tree TN.

rb_del_max(+T,-Key,-Val,-TN)

Delete the largest element from the tree T, returning the key Key, the value Val associated with the key and a new tree TN.

rb_update(+T,+Key,+NewVal,-TN)

Tree TN is tree T, but with value for Key associated with NewVal. Fails if it cannot find Key in T.

rb_apply(+T,+Key,+G,-TN)

If the value associated with key Key is Val0 in T, and if call(G,Val0,ValF) holds, then TN differs from T only in that Key is associated with value ValF in tree TN. Fails if it cannot find Key in T, or if call(G,Val0,ValF) is not satisfiable.

rb_visit(+T,-Pairs)

Pairs is an infix visit of tree T, where each element of Pairs is of the form K-Val.

rb_size(+T,-Size)

Size is the number of elements in T.

rb_keys(+T,+Keys)

Keys is an infix visit with all keys in tree T. Keys will be sorted, but may be duplicate.

rb_map(+T,+G,-TN)

For all nodes Key in the tree T, if the value associated with key Key is Val0 in tree T, and if call(G,Val0,ValF) holds, then the value associated with Key in TN is ValF. Fails if or if call(G,Val0,ValF) is not satisfiable for all Var0.

rb_partial_map(+T,+Keys,+G,-TN)

For all nodes Key in Keys, if the value associated with key Key is Val0 in tree T, and if call(G,Val0,ValF) holds, then the value associated with Key in TN is ValF. Fails if or if call(G,Val0,ValF) is not satisfiable for all Var0. Assumes keys are not repeated.

rb_clone(+T,+NT,+Nodes)

“Clone” the red-back tree into a new tree with the same keys as the original but with all values set to unbound values. Nodes is a list containing all new nodes as pairs K-V.

rb_min(+T,-Key,-Value)

Key is the minimum key in T, and is associated with Val.

rb_max(+T,-Key,-Value)

Key is the maximal key in T, and is associated with Val.

rb_next(+T, +Key,-Next,-Value)

Next is the next element after Key in T, and is associated with Val.

rb_previous(+T, +Key,-Previous,-Value)

Previous is the previous element after Key in T, and is associated with Val.

list_to_rbtree(+L, -T)

T is the red-black tree corresponding to the mapping in list L.

ord_list_to_rbtree(+L, -T)

T is the red-black tree corresponding to the mapping in ordered list L.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.16 Regular Expressions

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:

regexp(+RegExp,+String,+Opts,?SubMatchVars)

Match regular expression RegExp to input string String according to options Opts. The variable SubMatchVars should be originally unbound or a list of unbound variables all will contain a sequence of matches, that is, the head of SubMatch