YAP Prolog User’s Manual

Table of Contents


Up: (dir)   [Contents][Index]

YAP Prolog

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

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


Next: , Up: Top   [Contents][Index]

Introduction

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

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

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

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

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

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

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

On-line documentation is available for YAP at:

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

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

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

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

The packages are, in alphabetical order:


Next: , Previous: , 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 Configuration Options 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.


Next: , Up: Install   [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.


Previous: , Up: Install   [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.


Next: , Up: Machine Options   [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.


Next: , Previous: , Up: Machine Options   [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.yss').
    ^Z
    

    That’s it, you’ve got YAP and the saved state!

The $YAPSRC\VC directory has the make files to build YAP4.3.17 under VC++ 6.0.


Previous: , Up: Machine Options   [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 --...

Next: , Previous: , Up: Top   [Contents][Index]

2 Running YAP

We next describe how to invoke YAP in Unix systems.


Previous: , Up: Run   [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.

-sSize

allocate Size K bytes for local and global stacks. The user may specify M bytes.

-hSize

allocate Size K bytes for heap and auxiliary stacks

-tSize

allocate Size K bytes for the trail stack

-LSize

SWI-compatible option to allocate Size K bytes for local and global stacks, the local stack cannot be expanded. To avoid confusion with the load option, Size must immediately follow the letter L.

-GSize

SWI-compatible option to allocate Size K bytes for local and global stacks; the global stack cannot be expanded

-TSize

SWI-compatible option to allocate Size K bytes for the trail stack; the trail cannot be expanded.

-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.yss’ from the current directory or from the YAP library.


Next: , Up: Run   [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 (do not forget that the shell comments are very important):

#!/usr/local/bin/yap -L --
#
# Hello World script file using YAP
#
# put a dot because of syntax errors .

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

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

A slightly more sophisticated example is:

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

:- initialization(main).

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

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

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

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

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

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

If you this run this script with the arguments:

./dump_args -s 10000

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

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

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

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

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

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

./dump_args test

will write test on the standard output.


Next: , Previous: , 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.


Next: , Up: Syntax   [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:


Next: , Previous: , Up: Syntax   [Contents][Index]

3.2 Prolog Tokens

Prolog tokens are grouped into the following categories:


Next: , Up: Tokens   [Contents][Index]

3.2.1 Numbers

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


Next: , Up: Numbers   [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 6.2.2) supports integers that can fit the word size of the machine. This is 32 bits in most current machines, but 64 in some others, such as the Alpha running Linux or Digital Unix. The scanner will read larger or smaller integers erroneously.


Previous: , Up: Numbers   [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.


Next: , Previous: , Up: Tokens   [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).

Next: , Previous: , Up: Tokens   [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.


Next: , Previous: , Up: Tokens   [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.


Next: , Previous: , Up: Tokens   [Contents][Index]

3.2.5 Punctuation Tokens

Punctuation tokens consist of one of the following characters:

( ) , [ ] { } |

These characters are used to group terms.


Previous: , Up: Tokens   [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.


Previous: , Up: Syntax   [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.


Previous: , Up: Encoding   [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.


Next: , Up: Encoding   [Contents][Index]

3.3.2 BOM: Byte Order Mark

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

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

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


Next: , Previous: , Up: Top   [Contents][Index]

4 Loading Programs


Next: , Up: Loading Programs   [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 Encoding 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 compact clauses are compiled and no source code is stored; if it is source clauses are compiled and source code is stored; if it is assert_all clauses are asserted into the data-base.

ensure_loaded(+F) [ISO]

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.

make

SWI-Prolog built-in to consult all source files that have been changed since they were consulted. It checks all loaded source files. make/0 can be combined with the compiler to speed up the development of large packages. In this case compile the package using

    sun% pl -g make -o my_program -c file ...

If ‘my_program’ is started it will first reconsult all source files that have changed since the compilation.

include(+F) [ISO]

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


Next: , Previous: , Up: Loading Programs   [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.

initialization(+Goal,+When)

Similar to initialization/1, but allows for specifying when Goal is executed while loading the program-text:

now

Execute Goal immediately.

after_load

Execute Goal after loading program-text. This is the same as initialization/1.

restore

Do not execute Goal while loading the program, but only when restoring a state (not implemented yet).

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.

prolog_to_os_filename(+PrologPath,-OsPath)

This is an SWI-Prolog built-in. Converts between the internal Prolog pathname conventions and the operating-system pathname conventions. The internal conventions are Unix and this predicates is equivalent to =/2 (unify) on Unix systems. On DOS systems it will change the directory-separator, limit the filename length map dots, except for the last one, onto underscores.

expand_file_name(+WildCard,-List)

This is an SWI-Prolog built-in. Unify List with a sorted list of files or directories matching WildCard. The normal Unix wildcard constructs ?, *, [ ... ] and {...} are recognised. The interpretation of {...} is interpreted slightly different from the C shell (csh(1)). The comma separated argument can be arbitrary patterns, including {...} patterns. The empty pattern is legal as well: {.pl,} matches either .pl or the empty string.

If the pattern contains wildcard characters, only existing files and directories are returned. Expanding a pattern’ without wildcard characters returns the argument, regardless on whether or not it exists.

Before expanding wildcards, the construct $var is expanded to the value of the environment variable var and a possible leading ~ character is expanded to the user’s home directory. In Windows, the home directory is determined as follows: if the environment variable HOME exists, this is used. If the variables HOMEDRIVE and HOMEPATH exist (Windows-NT), these are used. At initialisation, the system will set the environment variable HOME to point to the YAP home directory if neither HOME nor HOMEPATH and HOMEDRIVE are defined.

public P [ISO extension]

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.


Next: , Previous: , Up: Loading Programs   [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.

Previous: , Up: Loading Programs   [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.


Next: , Previous: , 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 a hierarchy of modules. Modules can automatically import other modules, though. For compatibility with other module systems the YAP module system is non-strict, meaning both that there is a way to access predicates private to a module and that it is possible to declare predicates for a module from some other module.

YAP allows one to ignore the module system if one does not want to use it. Last note that using the module system does not introduce any significant overheads.


Next: , Up: Modules   [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 in, say:

nasa:launch(apollo,13).

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

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


Next: , Previous: , Up: Modules   [Contents][Index]

5.2 Defining a New Module

A new module is defined by a module declaration:

module(+M,+L)

This directive 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 directives use_module/1, use_module/2, ensure_loaded/1 and the predicates consult/1 or reconsult/1. The non-public predicates of a module file are not visible by other files; they can, however, be accessed by prefixing the module name with the :/2 operator.

The built-in module/1 sets the current source module:

module(+M,+L, +Options)

Similar to module/2, this directive defines the file where it appears in as a module file; it must be the first declaration in the file. M must be an atom specifying the module name; L must be a list containing the module’s public predicates specification, in the form [predicate_name/arity,...].

The last argument Options must be a list of options, which can be:

filename

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 bound 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.


Next: , Previous: , Up: Modules   [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.


Next: , Previous: , Up: Modules   [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, consider a file example.pl:

:- module(example,[a/1]).

a(G) :- call(G)

We import this module with use_module(example) into module user. The expected behavior for a goal a(p) is to execute goal p within the module user. However, a/1 will call p within module example.

The meta_predicate/1 declaration informs the system that some arguments of a predicate are goals, clauses, clauses heads or other terms related to a module, and that these arguments must be prefixed with the current source module:

meta_predicate G1,....,Gn

Each Gi is a mode specification.

If the argument is :, it does not refer directly to a predicate but must be module expanded. If the argument is an integer, the argument is a goal or a closure and must be expanded. Otherwise, the argument is not expanded. Note that the system already includes declarations for all built-ins.

For example, the declaration for call/1 and setof/3 are:

:- meta_predicate call(0), setof(?,0,?).

The previous example is expanded to the following code which explains, why the goal a(p) calls p in example and not in user. The goal call(G) is expanded because of the meta-predicate declaration for call/1.

:- module(example,[a/1]).

a(G) :- call(example:G)

By adding a meta-predicate declaration for a/1, the goal a(p) in module user will be expanded to a(user:p) thereby preserving the module information.

:- module(example,[a/1]).

:- meta_predicate a(:).
a(G) :- call(G)

An alternate mechanism is the directive module_transparent/1 offered for compatibility with SWI-Prolog.

module_transparent +Preds

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


Previous: , Up: Modules   [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:


Next: , Previous: , Up: Top   [Contents][Index]

6 Built-In Predicates


Next: , 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.

+Condition *-> +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(+Closure,...,?Ai,...)

Meta-call where Closure is a closure that is converted into a goal by appending the Ai additional arguments. The number of arguments varies between 0 and 10.

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. New code should use call/N for better portability.

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

call(p(X1,...,Xm), Y1,...,Yn) :- p(X1,...,Xm,Y1,...,Yn).
+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.


Next: , Previous: , 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.

exception(+Exception, +Context, -Action)

Dynamic predicate, normally not defined. Called by the Prolog system on run-time exceptions that can be repaired ‘just-in-time’. The values for Exception are described below. See also catch/3 and throw/1. If this hook predicate succeeds it must instantiate the Action argument to the atom fail to make the operation fail silently, retry to tell Prolog to retry the operation or error to make the system generate an exception. The action retry only makes sense if this hook modified the environment such that the operation can now succeed without error.

undefined_predicate

Context is instantiated to a predicate-indicator (Module:Name/Arity). If the predicate fails Prolog will generate an existence_error exception. The hook is intended to implement alternatives to the SWI built-in autoloader, such as autoloading code from a database. Do not use this hook to suppress existence errors on predicates. See also unknown.

undefined_global_variable

Context is instantiated to the name of the missing global variable. The hook must call nb_setval/2 or b_setval/2 before returning with the action retry.


Next: , Previous: , 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.

message_to_string(+Term, -String)

Translates a message-term into a string object. Primarily intended for SWI-Prolog emulation.


Next: , Previous: , 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.

rational(T)

Checks whether T is a rational 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, rational 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)

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.

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.

?Term1 =@= ?Term2

Same as variant/2, succeeds if Term1 and Term2 are variant terms.

subsumes_term(?Subsumer, ?Subsumed)

Succeed if Submuser subsumes Subsuned but does not bind any variable in Subsumer.

acyclic_term(?Term)

Succeed if the argument Term is an acyclic term.


Next: , Previous: , 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 characters of A.

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 atomic terms, 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.

atomic_list_concat(+As,?A)

The predicate holds when the first argument is a list of atomic terms, 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.

atomic_list_concat(?As,+Separator,?A)

Creates an atom just like atomic_list_concat/2, but inserts Separator between each pair of atoms. For example:

?- atomic_list_concat([gnu, gnat], ', ', A).

A = 'gnu, gnat'

YAP emulates the SWI-Prolog version of this predicate that can also be used to split atoms by instantiating Separator and Atom as shown below.

?- atomic_list_concat(L, -, 'gnu-gnat').

L = [gnu, gnat]
atom_length(+A,?I) [ISO]

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) [ISO]

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 characters of the external representation of I.

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.


Next: , Previous: , 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(Weight)

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

xdigit(Weight)

Char is a hexa-decimal digit with value Weight. 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.


Next: , Previous: , 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]
predsort(+Pred, +List, -Sorted)

Sorts similar to sort/2, but determines the order of two terms by calling Pred(-Delta, +E1, +E2) . This call must unify Delta with one of <, > or =. If built-in predicate compare/3 is used, the result is the same as sort/2.

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.


Next: , Previous: , Up: Top   [Contents][Index]

6.8 Arithmetic

YAP now supports several different numeric types:

integers

When YAP is built using the GNU multiple precision arithmetic library (GMP), integer arithmetic is unbounded, which means that the size of integers is limited by available memory only. Without GMP, SWI-Prolog integers have the same size as an address. The type of integer support can be detected using the Prolog flags bounded, min_integer and max_integer. As the use of GMP is default, most of the following descriptions assume unbounded integer arithmetic.

Internally, SWI-Prolog has three integer representations. Small integers (defined by the Prolog flag max_tagged_integer) are encoded directly. Larger integers are represented as cell values on the global stack. Integers that do not fit in 64-bit are represented as serialised GNU MPZ structures on the global stack.

number

Rational numbers (Q) are quotients of two integers. Rational arithmetic is only provided if GMP is used (see above). Rational numbers that are returned from is/2 are canonical, which means M is positive and N and M have no common divisors. Rational numbers are introduced in the computation using the rational/1, rationalize/1 or the rdiv/2 (rational division) function.

float

Floating point numbers are represented using the C-type double. On most today platforms these are 64-bit IEEE floating point numbers.

Arithmetic functions that require integer arguments accept, in addition to integers, rational numbers with denominator ‘1’ and floating point numbers that can be accurately converted to integers. If the required argument is a float the argument is converted to float. Note that conversion of integers to floating point numbers may raise an overflow exception. In all other cases, arguments are converted to the same type using the order integer to rational number to floating point number.

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

+X

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 module operator, always positive.

X rem Y [ISO]

Integer remainder, similar to mod but always has the same sign X.

X div Y [ISO]

Integer division, as if defined by (X - X mod Y) // Y.

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.

atan(X,Y)

Four-quadrant arc tangent. Also available as atan2/2.

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.

lgamma(X)

Logarithm of gamma function.

erf(X)

Gaussian error function.

erfc(X)

Complementary gaussian error function.

random(X) [ISO]

An integer random number between 0 and X.

In iso language mode the argument must be a floating point-number, the result is an integer and it the float is equidistant it is rounded up, that is, to the least integer greater than X.

integer(X)

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 integer 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 integer 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) [ISO]

The integral value between X and 0 closest to X.

rational(X)

Convert the expression X to a rational number or integer. The function returns the input on integers and rational numbers. For floating point numbers, the returned rational number exactly represents the float. As floats cannot exactly represent all decimal numbers the results may be surprising. In the examples below, doubles can represent 0.25 and the result is as expected, in contrast to the result of rational(0.1). The function rationalize/1 gives a more intuitive result.

?- A is rational(0.25).

A is 1 rdiv 4
?- A is rational(0.1).
A = 3602879701896397 rdiv 36028797018963968
rationalize(X)

Convert the Expr to a rational number or integer. The function is similar to rational/1, but the result is only accurate within the rounding error of floating point numbers, generally producing a much smaller denominator.

?- A is rationalize(0.25).

A = 1 rdiv 4
?- A is rationalize(0.1).

A = 1 rdiv 10
max(X,Y)

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
X >< Y
xor(X , Y)

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 non-negative integer X.

lsb(X)

The least significant bit of the non-negative integer X.

popcount(X)

The number of bits set to 1 in the binary representation of the non-negative 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.

epsilon

The difference between the float 1.0 and the first larger floating point number.

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:

The following predicates provide counting:

between(+Low, +High, ?Value)

Low and High are integers, High >=Low. If Value is an integer, Low =<Value =<High. When Value is a variable it is successively bound to all integers between Low and High. If High is inf or infinite between/3 is true iff Value >= Low, a feature that is particularly interesting for generating integers from a certain value.

succ(?Int1, ?Int2)

True if Int2 = Int1 + 1 and Int1 >= 0. At least one of the arguments must be instantiated to a natural number. This predicate raises the domain-error not_less_than_zero if called with a negative integer. E.g. succ(X, 0) fails silently and succ(X, -1) raises a domain-error. The behaviour to deal with natural numbers only was defined by Richard O’Keefe to support the common count-down-to-zero in a natural way.

plus(?Int1, ?Int2, ?Int3)

True if Int3 = Int1 + Int2. At least two of the three arguments must be instantiated to integers.


Next: , Previous: , 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.


Next: , Up: I/O   [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) [ISO]

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

reposition(+Bool) [ISO]

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) [ISO]

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) [ISO]

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 for details.

encoding(+Encoding)

Set the encoding used for text. See Encoding 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 Encoding.

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 relat