home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-387-Vol-3of3.iso / p / plbin.zip / pl / library / MANUAL < prev    next >
Text File  |  1992-06-04  |  213KB  |  5,571 lines

  1.                  University of Amsterdam
  2.  
  3.                     Dept.  of Social
  4.                    Science Informatics
  5.                          (SWI)
  6.                   Herengracht 196, 1016
  7.                      BS   Amsterdam
  8.                      The Netherlands
  9.                   Tel.  (+31) 20 5252073
  10.  
  11.                        SWI-Prolog 1.6
  12.  
  13.                       Reference Manual
  14.  
  15.                        Jan Wielemaker
  16.  
  17.                      jan@swi.psy.uva.nl
  18.  
  19. SWI-Prolog is a WAM (Warren Abstract Machine, ) based
  20. implementation of Prolog.  SWI-Prolog has been designed and
  21. implemented such that it can easily be modified for experiments
  22. with logic programming and the relation between logic
  23. programming and other programming paradigms (such as the object
  24. oriented PCE environment, ).  SWI-Prolog has a rich set of
  25. built-in predicates and reasonable performance, which makes it
  26. possible to develop substantial applications in it.  The current
  27. version offers a module system, garbage collection and an
  28. interface to the C language.
  29.  
  30. This document gives an overview of the features, system limits
  31. and built-in predicates.
  32.  
  33. Copyright (C) 1990 Jan Wielemaker
  34.  
  35.  
  36. Chapter  1
  37.  
  38. Introduction
  39.  
  40. SWI-Prolog has been designed and implemented to get a Prolog
  41. implementation which can be used for experiments with logic programming
  42. and the relation to other programming paradigms.  The intention was to
  43. build a Prolog environment which offers enough power and flexibility to
  44. write substantial applications, but is straightforward enough to be
  45. modified for experiments with debugging, optimisation or the introduction
  46. of non-standard data types.  Performance optimisation is limited due to
  47. the main objectives:  portability (SWI-Prolog is entirely written in C and
  48. Prolog) and modifiability.
  49.  
  50. SWI-Prolog is based on a very restricted form of the WAM (Warren Abstract
  51. Machine) described in  which defines only 7 instructions.  Prolog can
  52. easily be compiled into this language and the abstract machine code is
  53. easily decompiled back into Prolog.  As it is also possible to wire a
  54. standard 4-port debugger in the WAM interpreter there is no need for a
  55. distinction between compiled and interpreted code.  Besides simplifying
  56. the design of the Prolog system itself this approach has advantages for
  57. program development:  the compiler is simple and fast, the user does not
  58. have to decide in advance whether debugging is required and the system
  59. only runs slightly slower when in debug mode.  The price we have to pay is
  60. some performance degradation (taking out the debugger from the WAM
  61. interpreter improves performance by about 20%) and somewhat additional
  62. memory usage to help the decompiler and debugger.
  63.  
  64. SWI-Prolog extends the minimal set of instructions described in  to
  65. improve performance.  While extending this set care has been taken to
  66. maintain the advantages of decompilation and tracing of compiled code.
  67. The extensions include specialised instructions for unification, predicate
  68. invocation, some frequently used built-in predicates, arithmetic, or (;/2,
  69. |/2), if-then (->/2) and not (\+/1).
  70.  
  71. This manual does not describe the full syntax and semantics of SWI-Prolog,
  72. nor how one should write a program in Prolog.  These subjects have been
  73. described extensively in the literature.  See ,  and .  For more advanced
  74. Prolog material see .  Syntax and standard operator declarations confirm
  75. to the `Edinburgh standard'.  Most built in predicates are compatible with
  76. those described in .  SWI-Prolog also offers a number of primitive
  77. predicates compatible with Quintus Prolog,  and BIM_Prolog .
  78.  
  79.                                  1
  80.  
  81.  
  82. 1.1 Status
  83.  
  84. This manual describes version 1.6.0 of SWI-Prolog.  SWI-Prolog has been
  85. used now for some years.  The application range includes Prolog course
  86. material, meta-interpreters, simulation of parallel Prolog, learning
  87. systems and a large workbench for knowledge engineering.  Although we
  88. experienced rather obvious and critical bugs can remain unnoticed for a
  89. remarkable long period, we can assume the basic Prolog system to be fairly
  90. stable.  Bugs can be expected in unfrequently used builtin predicates.
  91.  
  92. Some bugs are known to the author.  They are described as footnotes in
  93. this manual.
  94.  
  95.  
  96. 1.2 Should you be Using SWI-Prolog?
  97.  
  98. There are a number of reasons why you better choose a commercial Prolog
  99. system, or another academic product:
  100.  
  101.     SWI-Prolog is not supported
  102.     Although I usually fix bugs shortly after a bug report arrives, I
  103.     cannot promise anything.  Now that the sources are provided, you can
  104.     always dig into them yourself.
  105.  
  106.     Memory requirements and performance are your first concerns
  107.     A number of commercial compilers are more keen on memory and
  108.     performance than SWI-Prolog.  I do not wish to offer some of the nice
  109.     features of the system, nor its portability to compete on raw
  110.     performance.
  111.  
  112.     You need features not offered by SWI-Prolog
  113.     In this case you may wish to give me suggestions for extensions.  If
  114.     you have great plans, please contact me (you might have to implement
  115.     them yourself however).
  116.  
  117. On the other hand, SWI-Prolog offers some nice facilities:
  118.  
  119.     Nice environment
  120.     This includes `Do What I Mean', automatic completion of atom names,
  121.     history mechanism and a tracer that operates on single key-strokes.
  122.     Interfaces to standard Unix editors are provided, as well as a
  123.     facility to maintain programs (see make/0).
  124.  
  125.     Very fast compiler
  126.     The compiler handles about 5K bytes per second per MIPS (i.e.  35K
  127.     bytes per second on SUN-4/110).
  128.  
  129.     Transparent compiled code
  130.     SWI-Prolog compiled code can be treated just as interpreted code:
  131.     you can list it, trace it, assert from or retract to it, etc.  This
  132.     implies you do not have to decide beforehand whether a module should
  133.     be loaded for debugging or not.  Also, performance is much better
  134.     than the performance of most interpreters.
  135.  
  136.     Profiling
  137.     SWI-Prolog offers tools for performance analysis, which can be very
  138.     useful to optimise programs.  Unless you are very familiar with
  139.     Prolog and Prolog performance considerations this might be more
  140.     helpful than a better compiler without these facilities.
  141.  
  142.     Flexibility
  143.     SWI-Prolog allows for easy and flexible integration with C, both
  144.     Prolog calling C functions as C calling Prolog predicates.
  145.     SWI-Prolog is provided in source form, which implies SWI-Prolog can
  146.     be linked in with another package.  Command line options and
  147.     predicates to obtain information from the system and feedback into
  148.     the system are provided.
  149.  
  150.     Integration with PCE
  151.     SWI-Prolog offers a tight integration to the Object Oriented Package
  152.     for User Interface Development, called PCE ().  PCE is now also
  153.     available for X-windows.
  154.  
  155.  
  156. 1.3 Version 1.5 Release Notes
  157.  
  158. There are not many changes between version 1.4 and 1.5.  The C-sources
  159. have been cleaned and comments have been updated.  The stack memory
  160. management based on using the MMU has been changed to run on a number of
  161. system-V Unix systems offering shared memory.  Handling dates has been
  162. changed.  All functions handling dates now return a floating point number,
  163. expressing the time in seconds since january 1, 1970.  A predicate
  164. convert_time/8 is available to get the year, month, etc.  The predicate
  165. time/6 has been deleted.  get_time/1 and convert_time/8 together do the
  166. same.
  167.  
  168. From version 1.5, the system is distributed in source form, rather than in
  169. object form as used with previous releases.  This allows users to port
  170. SWI-Prolog to new machines, extend and improve the system.  If you want
  171. your changes to be incorporated in the next release, please indicate all
  172. changes using a C-preprocessor flag and send complete source files back to
  173. me.  Difference listings are of no use, as I generally won't have exactly
  174. the same version around.
  175.  
  176.  
  177. 1.4 Version 1.6 Release Notes
  178.  
  179. Version 1.6 is completely compatible with version 1.5.  Some new features
  180. have been added, the system has been ported to various new platforms and
  181. there is a provisional interface to GNU-Emacs.  This interface will be
  182. improved and documented later.
  183.  
  184. The WAM virtual-machine interpreter has been modified to use GCC-2's
  185. support for threated code.
  186.  
  187. From version 1.6, the sources are now versioned using the CVS version
  188. control system.
  189.  
  190.  
  191. 1.5 Portability
  192.  
  193. The table below shows which machine dependent features have been ported to
  194. which architectures.  Some of the minus signs could be taken away by
  195. spending more effort to the port, others are due to fundamental omisions
  196. or bugs in the operating system.  Note that the column `C-interface'
  197. implies object code can be linked dynamically from a running Prolog
  198. environment.  For systems that have a minus here C-code can still be added
  199. by relinking SWI-Prolog itself together with the C-extensions to form an
  200. extended version of SWI-Prolog.
  201.  
  202.  Machine         OS          Dynamic      C        Saved   Profile
  203.                              Stacks    Interface  States
  204.  SUN-3 and 4     SunOs 4        +         +         +         +
  205.  HP 9000s300     HP-UX 8.0     --         +         +         +
  206.  DEC MIPS        Ultrix 3.1    --         --        +         +
  207.  Gould PN        UTX-2.1        +         --        --        +
  208.  IBM PS2         AIX 2.0       --         --        +         +
  209.  IBM RISC-6000   AIX 3.1       --         +         +         +
  210.  VAX             Ultrix        --         +         +         +
  211.  ATARI           TOS 1.3       --         --        --       --
  212.  PC              LINUX         --         --        --       --
  213.  
  214.  
  215. 1.6 Acknowledgements
  216.  
  217. Some small parts of the Prolog code of SWI-Prolog are modified versions of
  218. the corresponding Edinburgh C-Prolog code:  grammar rule compilation and
  219. writef/2.  Also some of the C-code originates from C-Prolog:  finding the
  220. path of the currently running executable and the code underlying
  221. absolute_file_name/2.  Ideas on programming style and techniques originate
  222. from C-Prolog and Richard O'Keefe's thief editor.  An important source of
  223. inspiration are the programming techniques introduced by Anjo Anjewierden
  224. in PCE version 1 and 2.
  225.  
  226. I also would like to thank those who had the fade of using the early
  227. versions of this system, suggested extensions or reported bugs.  Among
  228. them are Anjo Anjewierden, Huub Knops, Bob Wielinga, Wouter Jansweijer,
  229. Luc Peerdeman, Eric Nombden, Frank van Harmelen, Bert Rengel.
  230.  
  231.  
  232. Chapter  2
  233.  
  234. Overview
  235.  
  236.                                  8
  237.  
  238.  
  239. 2.1 Starting SWI-Prolog from the Unix Shell
  240.  
  241. It is advised to install SWI-Prolog as `pl' in the local binary directory.
  242. SWI-Prolog can then be started from the Unix shell by typing `pl'.  The
  243. system will boot from the system's default boot file, perform the
  244. necessary initialisations and then enter the interactive top level.
  245.  
  246. After the necessary system initialisation the system consults (see
  247. consult/1) the user's initialisation file.  This initialisation file
  248. should be named `.plrc' and reside either in the current directory or in
  249. the user's home directory.  If both exist the initialisation file from the
  250. current directory is loaded.  The name of the initialisation file can be
  251. changed with the `-f file' option.  After loading the initialisation file
  252. SWI-Prolog executes a user initialisation goal.  The default goal is a
  253. system predicate that prints the banner message.  The default can be
  254. modified with the `-g goal' option.  Next the toplevel goal is started.
  255. Default is the interactive Prolog loop (see prolog/0).  The user can
  256. overwrite this default with the `-t toplevel' option.
  257.  
  258.  
  259. 2.1.1 Command Line Options
  260.  
  261. The full set of command line options is given below:
  262.  
  263.     -Lsize
  264.         Give local stack size in K bytes (200 K default).  Note that
  265.         there is no space between the size option and its argument.
  266.         For machines with dynamic stack allocation this flag sets
  267.         the maximum value to which the stack is allowed to grow (2
  268.         Mbytes default).  A maximum is useful to stop buggy programs
  269.         from claiming all memory resources.  -L0 sets the limit to
  270.         the highest possible value.
  271.     -Gsize
  272.         Give global stack size in K bytes (100 K default).  For
  273.         machines with dynamic stack allocation the default is 4
  274.         Mbytes.  See -L for more details.
  275.     -Tsize
  276.         Give trail stack size in K bytes (50 K default).  For
  277.         machines with dynamic stack allocation the default is 4
  278.         Mbytes.  See -L for more details.
  279.     -Asize
  280.         Give argument stack size in K bytes (5 K default).  For
  281.         machines with dynamic stack allocation the default is 1
  282.         Mbytes.  See -L for more details.
  283.     -c file ...
  284.         Compile files into an `intermediate code file'.  See
  285.         section 2.6.
  286.     -o output
  287.         Used in combination with -c or -b to determine output file
  288.         for compilation.
  289.     -O
  290.         Optimised compilation.  See please/3.
  291.     -f file
  292.         Use file as initialisation file instead of `.plrc'.
  293.         `-f none' stops SWI-Prolog from searching for an
  294.         initialisation file.
  295.     -g goal
  296.         Goal is executed just before entering the top level.
  297.         Default is a predicate which prints the welcome message.
  298.         The welcome message can thus be suppressed by giving
  299.         -g true.  goal can be a complex term.  In this case quotes
  300.         are normally needed to protect it from being expanded by the
  301.         Unix shell.
  302.     -t goal
  303.         Use goal as interactive toplevel instead of the default goal
  304.         prolog/0.  goal can be a complex term.  If the toplevel goal
  305.         succeeds SWI-Prolog exits with status 0.  If it fails the
  306.         exit status is 1.  This flag also determines the goal
  307.         started by break/0 and abort/0.  If you want to stop the
  308.         user from entering interactive mode start the application
  309.         with `-g goal' and give `halt' as toplevel.
  310.     +/-tty
  311.         Switches tty control (using ioctl(2)) on (+tty) or off
  312.         (-tty).  Normally tty control is switched on.  This default
  313.         depends on the installation.  You may wish to switch tty
  314.         control off if Prolog is used from an editor such as GNU
  315.         EMACS. If switched off get_single_char/1 and the tracer will
  316.         wait for a return.
  317.     -x bootfile
  318.         Boot from bootfile instead of the system's default boot
  319.         file.  A bootfile is a file resulting from a Prolog
  320.         compilation using the -b or -c option.
  321.  
  322. The following options are for system maintenance.  They are given for
  323. reference only.
  324.  
  325.     -b initfile ...  -c file ...
  326.         Boot compilation.  initfile ...are compiled by the
  327.         C-written bootstrap compiler, file ...by the normal Prolog
  328.         compiler.  System maintenance only.
  329.     -d level
  330.         Set debug level to level.  System maintenance only.
  331.  
  332.  
  333. 2.2 GNU Emacs Interface
  334.  
  335. A provisional interface to GNU-Emacs is delivered with version 1.6 of
  336. SWI-Prolog.  The interface is based on the freely distributed interface
  337. delivered with Quintus Prolog.  When running Prolog as an inferior process
  338. under GNU-Emacs, there is support for finding predicate definitions,
  339. completing atoms, finding the locations of compilation-warnings and many
  340. more.  For details, see the files pl/lisp/README and
  341. pl/lisp/swi-prolog.el.
  342.  
  343.  
  344. 2.3 Online Help
  345.  
  346. Online help provides a fast lookup and browsing facility to this manual.
  347. The online manual can show predicate definitions as well as entire
  348. sections of the manual.
  349.  
  350.  
  351. help
  352.     Equivalent to help(help/1).
  353.  
  354.  
  355. help(+What)
  356.     Show specified part of the manual.  What is one of:
  357.  
  358.          Name/Arity   give help on specified predicate
  359.  
  360.          Name         give help on named predicate with any arity
  361.                       or C interface function with that name
  362.          Section      display specified section.  section numbers
  363.                       are dash-separated numbers:  2-3 refers to
  364.                       section 2.3 of the manual.  Section numbers
  365.                       are obtained using apropos/1.
  366.  
  367.     Examples
  368.  
  369.       ?- help(assert).     give help on predicate assert
  370.  
  371.       ?- help(3-4).        display section 3.4 of the manual
  372.  
  373.       ?- help('PL_retry'). give help on interface function PL_retry()
  374.  
  375.  
  376. apropos(+Pattern)
  377.     Display all predicates, functions and sections that have Pattern in
  378.     their name or summary description.  Lowercase letters in Pattern also
  379.     match a corresponding uppercase letter.  Example:
  380.  
  381.       ?- apropos(file).  Display predicates, functions and sections
  382.                          that have `file' (or `File', etc.)  in their
  383.                          summary description.
  384.  
  385.  
  386. 2.4 Query Substitutions
  387.  
  388. SWI-Prolog offers a query substitution mechanism similar to that of Unix
  389. csh (csh(1)), called `history'.  It allows the user to compose new queries
  390. from those typed before and remembered by the system.  It also allows to
  391. correct queries and syntax errors.  SWI-Prolog does not offer the Unix csh
  392. capabilities to include arguments.  This is omitted as it is unclear how
  393. the first, second, etc. argument should be defined.
  394.  
  395. The available history commands are shown in table 2.1.  Figure 2.1 gives
  396. some examples.
  397.  
  398.        !!.             Repeat last query
  399.        !nr.            Repeat query numbered <nr>
  400.        !str.           Repeat last query starting with <str>
  401.        !?str.          Repeat last query holding <str>
  402.        ^old^new.       Substitute <old> into <new> of last query
  403.        !nr^old^new.    Substitute in query numbered <nr>
  404.        !str^old^new.   Substitute in query starting with <str>
  405.        !?str^old^new.  Substitute in query holding <str>
  406.        h.              Show history list
  407.        !h.             Show this list
  408.  
  409.                     Table 2.1:  History commands
  410.  
  411.     /u4/staff/jan/.plrc consulted, 0.066667 seconds, 591 bytes
  412.     Welcome to SWI-Prolog (version 1.5.0, August 1990)
  413.     Copyright (c) 1990, University of Amsterdam. All rights reserved.
  414.  
  415.     1 ?- append("Hello ", "World", L).
  416.  
  417.     L = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
  418.  
  419.     Yes
  420.     2 ?- !!, writef('L = %s\n', [L]).
  421.     append("Hello ", "World", L), writef('L = %s\n', [L]).
  422.     L = Hello World
  423.  
  424.     L = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
  425.  
  426.     Yes
  427.     3 ?- sublist(integer, [3, f, 3.4], L).
  428.  
  429.     L = [3]
  430.  
  431.     Yes
  432.     4 ?- ^integer^number.
  433.     sublist(number, [3, f, 3.4], L).
  434.  
  435.     L = [3, 3.400000]
  436.  
  437.     Yes
  438.     5 ?- h.
  439.         1   append("Hello ", "World", L).
  440.         2   append("Hello ", "World", L), writef('L = %s\n', [L]).
  441.         3   sublist(integer, [3, f, 3.4], L).
  442.         4   sublist(number, [3, f, 3.4], L).
  443.  
  444.     5 ?- !2^World^Universe.
  445.     append("Hello ", "Universe", L), writef('L = %s\n', [L]).
  446.     L = Hello Universe
  447.  
  448.     L = [72, 101, 108, 108, 111, 32, 85, 110, 105, 118, 101, 114, 115,
  449.     101]
  450.  
  451.     Yes
  452.     6 ?- halt.
  453.  
  454.            Figure 2.1:  Some examples of the history facility
  455.  
  456.  
  457. 2.4.1 Limitations of the History System
  458.  
  459. When in top level SWI-Prolog reads the user's queries using history_read/6
  460. rather than read/1.  This predicate first reads the current input stream
  461. up to a full stop.  While doing so it maps all contiguous blank space onto
  462. a single space and deletes /* ... */ and % ... <cr> comments.  Parts
  463. between double quotes (") or single quotes (') are left unaltered.  Note
  464. that a Prolog full stop consists of a `non-symbol' character, followed by
  465. a period (.), followed by a blank character.  `Symbol' characters are:
  466. #$&*+-./:<=>?@^`~.  A single quote immediately preceded by a digit (0-9)
  467. considered part of the <digit>'<digit>... (e.g.  2'101; binary number 101)
  468. sequence.
  469.  
  470. After this initial parsing the result is first checked for the special
  471. ^old^new. construction.  If this fails the string is checked for all
  472. occurrences of the !, followed by a !, ?, a digit, a letter or an
  473. underscore.  These special sequences are analysed and the appropriate
  474. substitution from the history list is made.
  475.  
  476. From the above it follows that it is hard or impossible to correct
  477. quotation with single or double quotes, comment delimiters and spacing.
  478.  
  479.  
  480. 2.5 Overview of the Debugger
  481.  
  482. SWI-Prolog has a standard 4-port tracer  with an optional fifth port.
  483. This fifth port, called unify allows the user to inspect the result after
  484. unification of the head.  The ports are called call, exit, redo, fail and
  485. unify.  The tracer is started by the trace/0 command, when a spy point is
  486. reached and the system is in debugging mode (see spy/1 and debug/1) or
  487. when an error is detected at run time.  Note that in the interactive
  488. toplevel goal trace/0 means ``trace the next query''.  The tracer shows
  489. the port, displaying the port name, the current depth of the recursion and
  490. the goal.  The goal is printed using the Prolog predicate print/1
  491. (default), write/1 or display/1.  An example using all five ports is shown
  492. in figure 2.2.
  493.  
  494.     Yes
  495.     2 ?- visible(+all), leash(-exit).
  496.  
  497.     Yes
  498.     3 ?- trace, min([3, 2], X).
  499.       Call:  ( 3) min([3, 2], G235) ? creep
  500.       Unify: ( 3) min([3, 2], G235)
  501.       Call:  ( 4) min([2], G244) ? creep
  502.       Unify: ( 4) min([2], 2)
  503.       Exit:  ( 4) min([2], 2)
  504.       Call:  ( 4) min(3, 2, G235) ? creep
  505.       Unify: ( 4) min(3, 2, G235)
  506.       Call:  ( 5) 3 < 2 ? creep
  507.       Fail:  ( 5) 3 < 2 ? creep
  508.       Redo:  ( 4) min(3, 2, G235) ? creep
  509.       Exit:  ( 4) min(3, 2, 2)
  510.       Exit:  ( 3) min([3, 2], 2)
  511.  
  512.                      Figure 2.2:  Example trace
  513.  
  514. On leashed ports (set with the predicate leash/1, default are call, exit,
  515. redo and fail) the user is prompted for an action.  All actions are single
  516. character commands which are executed without waiting for a return (Unix
  517. `cbreak' mode), unless the command line option -tty is active.  Tracer
  518. options:
  519.  
  520. +   Spy                all
  521.     Set a spy point (see spy/1) on the current predicate.
  522.  
  523.     No spy             all
  524.     Remove the spy point (see nospy/1) from the current predicate.
  525.  
  526. /   Find               all
  527.     Search for a port.  After the `/', the user can enter a line to
  528.     specify the port to search for.  This line consists of a set of
  529.     letters indicating the port type, followed by an optional term, that
  530.     should unify with the goal run by the port.  If no term is specified
  531.     it is taken as a variable, searching for any port of the specified
  532.     type.  If an atom is given, any goal whose functor has a name equal
  533.     to that atom matches.  Examples:
  534.  
  535.           /f               Search for any fail port
  536.  
  537.           /fe solve        Search for a fail or exit port of any
  538.                            goal with name solve
  539.  
  540.           /c solve(a, _)   Search for a call to solve/2 whose
  541.                            first argument is a variable or the
  542.                            atom a
  543.           /a member(_, _)  Search for any port on member/2.
  544.                            This is equivalent to setting a spy
  545.                            point on member/2.
  546.  
  547. .   Repeat find        all
  548.     Repeat the last find command (see `/')
  549.  
  550. A   Alternatives       all
  551.     Show all goals that have alternatives.
  552.  
  553. C   Context            all
  554.     Toggle `Show Context'.  If on the context module of the goal is
  555.     displayed between square brackets (see section 4).  Default is off.
  556.  
  557. L   Listing            all
  558.     List the current predicate with listing/1.
  559.  
  560. a   Abort              all
  561.     Abort Prolog execution (see abort/0).
  562.  
  563. b   Break              all
  564.     Enter a Prolog break environment (see break/0).
  565.  
  566. c   Creep              all
  567.     Continue execution, stop at next port.  (Also return, space).
  568.  
  569. d   Display            all
  570.     Write goals using the Prolog predicate display/1.
  571.  
  572. e   Exit               all
  573.     Terminate Prolog (see halt/0).
  574.  
  575. f   Fail         call, redo, exit
  576.     Force failure of the current goal
  577.  
  578. g   Goals              all
  579.     Show the list of parent goals (the execution stack).  Note that due
  580.     to tail recursion optimization a number of parent goals might not
  581.     exist any more.
  582.  
  583. h   Help               all
  584.     Show available options (also `?').
  585.  
  586. i   Ignore       call, redo, fail
  587.     Ignore the current goal, pretending it succeeded.
  588.  
  589. l   Leap               all
  590.     Continue execution, stop at next spy point.
  591.  
  592. n   No debug           all
  593.     Continue execution in `no debug' mode.
  594.  
  595. p   Print              all
  596.     Write goals using the Prolog predicate print/1 (default).
  597.  
  598. r   Retry        redo, exit, fail
  599.     Undo all actions (except for database and i/o actions) back to the
  600.     call port of the current goal and resume execution at the call port.
  601.  
  602. s   Skip            call, redo
  603.     Continue execution, stop at the next port of this goal (thus skipping
  604.     all calls to children of this goal).
  605.  
  606. u   Up                 all
  607.     Continue execution, stop at the next port of the parent goal (thus
  608.     skipping this goal and all calls to children of this goal).  This
  609.     option is useful to stop tracing a failure driven loop.
  610.  
  611. w   Write              all
  612.     Write goals using the Prolog predicate write/1.
  613.  
  614. The ideal 4 port model as described in many Prolog books  is not visible
  615. in many Prolog implementations because code optimisation removes part of
  616. the choice- and exit points.  Backtrack points are not shown if either the
  617. goal succeeded deterministically or its alternatives were removed using
  618. the cut.  When running in debug mode (debug/0) choice points are only
  619. destroyed when removed by the cut.  In debug mode tail recursion
  620. optimisation is switched off.
  621.  
  622.  
  623. 2.6 Compilation
  624.  
  625. Collections of SWI-Prolog source files can be compiled into an
  626. intermediate code file.  An intermediate code file is a data file from
  627. which SWI-Prolog can be started.  The command to compile a bundle of
  628. source files is:
  629.  
  630.     pl [options] [-o output] -c file ...
  631.  
  632. The individual source files may include other files using the standard
  633. list notation, consult/1, ensure_loaded/1 and use_module/[1,2].  When the
  634. -o fileoption is omitted a file named a.out is created that holds the
  635. intermediate code file.
  636.  
  637. Intermediate code files start with the BSD Unix magic code #! and are
  638. executable.  This implies they can be started as a command:
  639.  
  640.     sun% pl -o my_program -c ...
  641.     ...
  642.     sun% my_program [options]
  643.  
  644. Alternatively, my_program can be started with
  645.  
  646.     sun% pl -x my_program [options]
  647.  
  648. The following restrictions apply to source files that are to be compiled
  649. with `-c':
  650.  
  651.     term_expansion/2 should not use assert/1 and or retract/1 other than
  652.     for local computational purposes.
  653.  
  654.     Files can only be included by the standard include directives:
  655.     [...], consult/1, ensure_loaded/1 and use_module/[1,2].  User defined
  656.     loading predicate invocations will not be compiled.
  657.  
  658. Directives are executed both when compiling the program and when loading
  659. the intermediate code file.
  660.  
  661.  
  662. 2.7 Environment Control
  663.  
  664.  
  665. please(+Key, -Old, +New)
  666.     The predicate please/3 is a solution to avoid large numbers of
  667.     environment control predicates.  Later versions will support other
  668.     environment control as now provided via the predicates style_check/2,
  669.     leash/1, unknown/2, the tracer predicates, etc.  These predicates are
  670.     then moved into a library for backwards compatibility.  The currently
  671.     available options are:
  672.  
  673.     optimise on/off (default:  off)
  674.         Switch optimise mode for the compiler on or off (see also the
  675.         command line option -O).  Currently optimised compilation only
  676.         implies compilation of arithmetic, making it fast, but invisible
  677.         to the tracer.  Later versions might imply various other
  678.         optimisations such as incorporating a number of basic predicates
  679.         in the virtual machine (var/1, fail/0, =/2, etc.)  to gain speed
  680.         at the cost of crippling the debugger.  Also source level
  681.         optimisations such as integrating small predicates into their
  682.         callers, eliminating constant expressions and other predictable
  683.         constructs.  Source code optimisation is never applied to
  684.         predicates that are declared dynamic (see dynamic/1).
  685.  
  686.     autoload on/off (default:  on)
  687.         If on autoloading of library functions is enabled.  If off
  688.         autoloading is disabled.  See section 2.9.
  689.  
  690.     verbose_autoload on/off (default:  off)
  691.         If on the normal consult message will be printed if a library is
  692.         autoloaded.  By default this message is suppressed.  Intended to
  693.         be used for debugging purposes (e.g. where does this predicate
  694.         come from?).
  695.  
  696.  
  697. 2.8 Stand Alone Executables (Saved States)
  698.  
  699. The introduction of a foreign language interface raised the problem of
  700. incorporating the compiled foreign code into SWI-Prolog to create a new
  701. stand alone executable.  The current also allows one to create
  702. applications that do not need any of the SWI-Prolog system files.
  703.  
  704.  
  705. save_program(+NewProgram, +ListOfOptions)
  706.     Create a new executable wich will be named NewProgram.  ListOfOptions
  707.     is a list of Key = Valuepairs that specify the default command line
  708.     options that will be saved into the new program.  If a default is not
  709.     specified the default compiled into the currently running Prolog
  710.     executable is used.  The available keys are given in table 2.2
  711.  
  712.     Key         Option     Type    Description
  713.     local         -L     K-bytes   Size (Limit) of local stack
  714.     global        -G     K-bytes   Size (Limit) of global stack
  715.     trail         -T     K-bytes   Size (Limit) of trail stack
  716.     argument      -A     K-bytes   Size (Limit) of argument stack
  717.     goal          -g       atom    Initialisation goal
  718.     toplevel      -t       atom    Prolog toplevel goal
  719.     init_file     -f       atom    Personal initialisation file
  720.     tty         +/--tty   on/off   Use ioctl(2) calls
  721.  
  722.             Table 2.2:  Key = Value pairs for save_program/2
  723.  
  724.     As the entire data image of the current process will be saved on the
  725.     new executable it is desirable to keep this small.  Notably the
  726.     Prolog machine stacks should be kept small.  The best way to do this
  727.     is first to compile the program using the -c option.  If this is not
  728.     possible try to find the smallest possible stack sizes to compile the
  729.     program.  On machines with dynamic stack allocation the stacks are
  730.     not written to file and so their size does not matter.  Figure 2.3
  731.     shows a possible session.  Note the use of `initialise', which is
  732.     supposed to be a predicate of the application doing time consuming
  733.     initialisation.
  734.  
  735.    sun% pl -c load
  736.    foreign file dbase loaded 0.066667 seconds, 1578 bytes.
  737.    setup consulted, 0.500000 seconds, 5091 bytes.
  738.    main consulted, 0.333333 seconds, 3352 bytes.
  739.    load consulted, 1.000000 seconds, 9867 bytes.
  740.    sun% a.out -f none -L10 -G10 -T5
  741.    foreign file dbase loaded 0.066667 seconds, 1578 bytes.
  742.    Welcome to SWI-Prolog (version 1.5.0, August 1990)
  743.    Copyright (c) 1990, University of Amsterdam. All rights reserved.
  744.  
  745.    1 ?- initialise.
  746.  
  747.    Yes
  748.    2 ?- save_program(my_program,
  749.            [ local     = 500
  750.            , goal      = go
  751.            , init_file = none
  752.            ]).
  753.    Running executable: /usr/local/bin/pl
  754.    Saving to my_program; text: 204800 ... data: 357000 ... symbols ...
  755.    done.
  756.    Yes
  757.    2 ?- halt.
  758.    sun%
  759.  
  760.              Figure 2.3:  Create a stand-alone executable
  761.  
  762.     The resulting program can be used for incremental compilation using
  763.     -c or another save_program/2.
  764.  
  765.  
  766. save_program(+NewProgram)
  767.     Equivalent to `save_program(NewProgram, [])'.
  768.  
  769.  
  770. 2.9 Automatic loading of libraries
  771.  
  772. If ---at runtime--- an undefined predicate is trapped the system will
  773. first try to import the predicate from the module's default module.  If
  774. this fails the auto loader is activated.  On first activation an index to
  775. all library files in all library directories is loaded in core (see
  776. library_directory/1).  If the undefined predicate can be located in the
  777. one of the libraries that library file is automatically loaded and the
  778. call to the (previously undefined) predicate is resumed.  By default this
  779. mechanism loads the file silently.  The please/3 option verbose_autoload
  780. is provided to get verbose loading.  The please option autoloadcan be
  781. used to enable/disable the entire auto load system.
  782.  
  783. Autoloading only handles (library) source files that use the module
  784. mechanism described in chapter 4.  The files are loaded with use_module/2
  785. and only the trapped undefined predicate will be imported to the module
  786. where the undefined predicate was called.  Each library directory must
  787. hold a file INDEX.plthat contains an index to all library files in the
  788. directory.  This file consists of lines of the following format:
  789.  
  790.     index(Name, Arity, Module, File).
  791.  
  792. The predicate make/0 scans the autoload libraries and updates the index if
  793. it exists, is writable and out-of-date.  It is adviced to create an empty
  794. file called INDEX.plin a library directory meant for auto loading before
  795. doing anything else.  This index file can then be updated by running the
  796. prolog predicate make/0 (`%' is the Unix prompt):
  797.  
  798.     % mkdir ~/lib/prolog
  799.     % cd !$
  800.     % touch INDEX.pl
  801.     %     <create library files>
  802.     % pl -g true -t make
  803.      index for library . ... ok.
  804.     %
  805.  
  806. If there are more than one library files containing the desired predicate
  807. the following search schema is followed:
  808.  
  809.  1. If a there is a library file that defines the module in which the
  810.     undefined predicate is trapped, this file is used.
  811.  
  812.  2. Otherwise library files are considered in the order they appear in
  813.     the library_directory/1 predicate and within the directory
  814.     alphabetically.
  815.  
  816.  
  817. 2.9.1 Notes on Automatic Loading
  818.  
  819. The autoloader is a new feature to SWI-Prolog.  Its aim is to simplify
  820. program development and program management.  Common lisp has a similar
  821. feature, but here the user has to specify which library is to be loaded if
  822. a specific function is called which is not defined.  The advantage of the
  823. SWI-Prolog schema is that the user does not have to specify this.  The
  824. disadvantage however is that the user might be wondering ``where the hell
  825. this predicate comes from''.  Only experience can learn whether the
  826. functionality of the autoloader is appropriate.  Comments are welcome.
  827.  
  828. The autoloader only works if the unknown flag (see unknown/2) is set to
  829. trace(default).  A more appropriate interaction with this flag will be
  830. considered.
  831.  
  832.  
  833. 2.10 Garbage Collection
  834.  
  835. SWI-Prolog version 1.4 was the first release to support garbage
  836. collection.  Together with tail-recursion optimisation this guaranties
  837. forward chaining programs do not waste indefinite amounts of memory.
  838. Previous releases of this manual stressed on using failure-driven loops in
  839. those cases that no information needed to be passed to the next iteration
  840. via arguments.  This to avoid large amounts of garbage.  This is no longer
  841. stricktly necessary, but it should be noticed that garbage collection is a
  842. time consuming activity.  Failure driven loops tend to be faster for this
  843. reason.
  844.  
  845. BUG: The garbage collector is deactivated when Prolog is called back from
  846. a foreign language predicate.  This implies there is no garbage collection
  847. within a break environment.  More seriously, there is no garbage
  848. collection when handling call-backs from ---for example--- the PCE
  849. package.
  850.  
  851.  
  852. 2.11 Syntax Notes
  853.  
  854. SWI-Prolog uses standard `Edinburgh' syntax.  A description of this syntax
  855. can be found in the Prolog books referenced in the introduction.  Below
  856. are some non-standard or non-common constructs that are accepted by
  857. SWI-Prolog:
  858.  
  859.     0'<char>
  860.     This construct is not accepted by all Prolog systems that claim to
  861.     have Edinburgh compatible syntax.  It describes the ASCII value of
  862.     <char>.  To test whether C is a lower case character one can use
  863.     `between(0'a, 0'z, C)'.
  864.  
  865.     /* ... /* .... */ ... */
  866.     The /* ... */ comment statement can be nested.  This is useful if
  867.     some code with /* ... */ comment statements in it should be commented
  868.     out.
  869.  
  870.  
  871. 2.12 System Limits
  872.  
  873.  
  874. 2.12.1 Limits on Memory Areas
  875.  
  876. SWI-Prolog has a number of memory areas which are not enlarged at run
  877. time, unless you have a version with dynamic stack allocation.  The
  878. default sizes for these areas should suffice for small applications, but
  879. most serious application require larger ones.  They all can be modified by
  880. command line options.  The table below shows these areas.  The first
  881. column gives the option name to modify the size of the area.  This option
  882. character should be followed immediately by a number and expresses the
  883. number of kilo bytes to use for the area.  There are no other limits than
  884. the available memory of the machine to the sizes of the areas.  The areas
  885. are described in table 2.3.
  886.  
  887. The heap is a memory area to store atoms, clauses, records, flags, etc.
  888. This area is dynamically enlarged at runtime on all versions of
  889. SWI-Prolog.
  890.  
  891.  Option    Default    Area name       Description
  892.  
  893.    -L     200K (2M)   local stack     The local stack is used to store the
  894.                                       execution environments of procedure
  895.                                       invocations.  The space for an
  896.                                       environment is reclaimed when it
  897.                                       fails, exits without leaving choice
  898.                                       points, the alternatives are cut of
  899.                                       with the ! predicate or no choice
  900.                                       points have been created since the
  901.                                       invocation and the last subclause is
  902.                                       started (tail recursion
  903.                                       optimisation).
  904.  
  905.    -G     100K (4M)   global stack    The global stack is used to store
  906.                                       terms created during Prolog's
  907.                                       execution.  Terms on this stack will
  908.                                       be reclaimed by backtracking to a
  909.                                       point before the term was created or
  910.                                       by garbage collection (provided the
  911.                                       term is no longer referenced).
  912.  
  913.    -T      50K (4M)   trail stack     The trail stack is used to store
  914.                                       assignments during execution.
  915.                                       Entries on this stack remain alive
  916.                                       until backtracking before the point
  917.                                       of creation or the garbage collector
  918.                                       determines they are nor needed any
  919.                                       longer.
  920.  
  921.    -A      5K (1M)    argument stack  The argument stack is used to store
  922.                                       one of the intermediate code
  923.                                       interpreter's registers.  The amount
  924.                                       of space needed on this stack is
  925.                                       determined entirely by the depth in
  926.                                       which terms are nested in the clauses
  927.                                       that constitute the program.
  928.                                       Overflow is most likely when using
  929.                                       long strings in a clause.
  930.  
  931.                       Table 2.3:  Memory areas
  932.  
  933.  
  934. 2.12.2 Other Limits
  935.  
  936. ClausesCurrently the following limitations apply to clauses.  The arity
  937.     may not be more than 128, the number of links to the `outside world'
  938.     (predicates, atoms, (large) integers, etc) may not exceed 512 and the
  939.     number of variables should be less than 256.
  940.  
  941. Atoms and StringsSWI-Prolog has no limits on the sizes of atoms and
  942.     strings.  read/1 and its derivates however normally limit the number
  943.     of newlines in an atom or string to 5 to improve error detection and
  944.     recovery.  This can be switched off with style_check/1.
  945.  
  946. Address spaceSWI-Prolog uses tagged pointers internally.  This limits the
  947.     number of available bits for addressing memory to 29 (512 Mb).
  948.  
  949. IntegersIntegers are tagged values.  Their value is limited between 226
  950.     and 226 1.
  951.  
  952. FloatsFloating point numbers are C-doubles with a 12 bit reduction of the
  953.     mantisse.  For machines using IEEE floating point format, this
  954.     implies the range is about 10308and the accurracy about 10 digits.
  955.  
  956.  
  957. 2.12.3 Reserved Names
  958.  
  959. The boot compiler (see -b option) does not support the module system
  960. (yet).  As large parts of the system are written in Prolog itself we need
  961. some way to avoid name clashes with the user's predicates, database keys,
  962. etc.  Like Edinburgh C-Prolog  all predicates, database keys, etc. that
  963. should be hidden from the user start with a dollar ($) sign (see
  964. style_check/2).
  965.  
  966. The compiler uses the special functor $VAR$/1 while analysing the clause
  967. to compile.  Using this functor in a program causes unpredictable
  968. behaviour of the compiler and resulting program.
  969.  
  970.  
  971. Chapter  3
  972.  
  973. Built-In  Predicates
  974.  
  975.                                 33
  976.  
  977.  
  978. 3.1 Notation of Predicate Descriptions
  979.  
  980. We have tried to keep the predicate descriptions clear and concise.  First
  981. the predicate name is printed in bold face, followed by the arguments in
  982. italics.  Arguments are preceded by a `+', `--' or `?'  sign.  `+'
  983. indicates the argument is input to the predicate, `--' denotes output and
  984. `?'  denotes `either input or output'.  Constructs like `op/3' refer to
  985. the predicate `op' with arity `3'.
  986.  
  987.  
  988. 3.2 Consulting Prolog Source files
  989.  
  990. SWI-Prolog source files normally have a suffix `.pl'.  Specifying the
  991. suffix is optional.  All predicates that handle source files first check
  992. whether a file with suffix `.pl' exists.  If not the plain file name is
  993. checked for existence.  Library files are specified by embedding the file
  994. name using the functor library/1.  Thus `foo' refers to `foo.pl' or `foo'
  995. in the current directory, `library(foo)' refers to `foo.pl' or `foo' in
  996. one of the library directories specified by the dynamic predicate
  997. library_directory/1.
  998.  
  999. SWI-Prolog recognises grammar rules as defined in .  The user may define
  1000. additional compilation of the source file by defining the dynamic
  1001. predicate term_expansion/2.  Transformations by this predicate overrule
  1002. the systems grammar rule transformations.  It is not allowed to use
  1003. assert/1, retract/1 or any other database predicate in term_expansion/2
  1004. other than for local computational purposes.
  1005.  
  1006. Directives may be placed anywhere in a source file, invoking any
  1007. predicate.  They are executed when encountered.  If the directive fails, a
  1008. warning is printed.  Directives are specified by :-/1 or ?-/1.  There is
  1009. no difference between the two.
  1010.  
  1011. SWI-Prolog does not have a separate reconsult/1 predicate.  Reconsulting
  1012. is implied automatically by the fact that a file is consulted which is
  1013. already loaded.
  1014.  
  1015.  
  1016. consult(+File)
  1017.     Read File as a Prolog source file.  File may be a list of files, in
  1018.     which case all members are consulted in turn.  File may start with
  1019.     the csh(1) special sequences ~, ~<user> and $<var>.  File may also be
  1020.     library(Name), in which case the libraries are searched for a file
  1021.     with the specified name.  See also library_directory/1.  consult/1
  1022.     may be abbreviated by just typing a number of file names in a list.
  1023.     Examples:
  1024.  
  1025.        ?- consult(load).       % consult `load' or `load.pl'
  1026.        ?- [library(quintus)].  % load Quintus compatibility library
  1027.  
  1028.  
  1029. ensure_loaded(+File)
  1030.     Equivalent to consult/1, but the file is consulted only if this was
  1031.     not done before.  This is the recommended way to load files from
  1032.     other files.
  1033.  
  1034.  
  1035. make
  1036.     Consult all source files that have been changed since they were
  1037.     consulted.  It checks all loaded source files:  files loaded into a
  1038.     compiled state using pl -c ...  and files loaded using consult or one
  1039.     of its derivates.  make/0 is normally invoked by the edit/[0,1] and
  1040.     ed/[0,1] predicates.  make/0 can be combined with the compiler to
  1041.     speed up the development of large packages.  In this case compile the
  1042.     package using
  1043.  
  1044.         sun% pl -g make -o my_program -c file ...
  1045.  
  1046.     If `my_program' is started it will first reconsult all source files
  1047.     that have changed since the compilation.
  1048.  
  1049.  
  1050. library_directory(-Atom)
  1051.     Dynamic predicate used to specify library directories.  Default .,
  1052.     ./lib, ~/lib/prolog and the system's library (in this order) are
  1053.     defined.  The user may add library directories using assert/1 or
  1054.     remove system defaults using retract/1.
  1055.  
  1056.  
  1057. source_file(-File)
  1058.     Succeeds if File was loaded using consult/1 or ensure_loaded/1.  File
  1059.     refers to the full path name of the file (see expand_file_name/2).
  1060.     Source_file/1 backtracks over all loaded source files.
  1061.  
  1062.  
  1063. source_file(?Pred, ?File)
  1064.     Is true if the predicate specified by Pred was loaded from file File,
  1065.     where File is an absolute path name (see expand_file_name/2).  Can be
  1066.     used with any instantiation pattern, but the database only maintains
  1067.     the source file for each predicate.  Predicates declared multifile
  1068.     (see multifile/1) cannot be found this way.
  1069.  
  1070.  
  1071. term_expansion(+Term1, -Term2)
  1072.     Dynamic predicate, normally not defined.  When defined by the user
  1073.     all terms read during consulting that are given to this predicate.
  1074.     If the predicate succeeds Prolog will assert Term2 in the database
  1075.     rather then the read term (Term1).  Term2 may be a term of a the form
  1076.     `?- Goal' or `:- Goal'.  Goal is then treated as a directive.  Term2
  1077.     may also be a list, in which case all terms of the list are stored in
  1078.     the database or called (for directives).
  1079.  
  1080.  
  1081. compiling
  1082.     Succeeds if the system is compiling source files with the -c option
  1083.     into an intermediate code file.  Can be used to perform code
  1084.     optimisations in expand_term/2 under this condition.
  1085.  
  1086.  
  1087. preprocessor(-Old, +New)
  1088.     Read the input file via a Unix process that acts as preprocessor.  A
  1089.     preprocessor is specified as an atom.  The first occurrence of the
  1090.     string `%f' is replaced by the name of the file to be loaded.  The
  1091.     resulting atom is called as a Unix command and the standard output of
  1092.     this command is loaded.  To use the Unix C preprocessor one should
  1093.     define:
  1094.  
  1095.         ?- preprocessor(Old, '/lib/cpp -C -P %f'), consult(...).
  1096.  
  1097.         Old = none
  1098.  
  1099.  
  1100. 3.3 Listing Predicates and Editor Interface
  1101.  
  1102. SWI-Prolog offers an interface to the Unix vi editor (vi(1)), Richard
  1103. O'Keefe's top editor  and the GNU-EMACS invocations emacs and emacsclient.
  1104. Which editor is used is determined by the Unix environment variable
  1105. EDITOR, which should hold the full pathname of the editor.  If this
  1106. variable is not defined, vi(1) is used.
  1107.  
  1108. After the user quits the editor make/0 is invoked to reload all modified
  1109. source files using consult/1.  If the editor can be quit such that an exit
  1110. status non-equal to 0 is returned make/0 will not be invoked.  top can do
  1111. this by typing control-C, vi cannot do this.
  1112.  
  1113. A predicate specification is either a term with the same functor and arity
  1114. as the predicate wanted, a term of the form Functor/Arityor a single
  1115. atom.  In the latter case the database is searched for a predicate of this
  1116. name and arbitrary arity (see current_predicate/2).  When more than one
  1117. such predicate exists the system will prompt for confirmation on each of
  1118. the matched predicates.  Predicates specifications are given to the `Do
  1119. What I Mean' system (see dwim_predicate/2) if the requested predicate does
  1120. not exist.
  1121.  
  1122.  
  1123. ed(+Pred)
  1124.     Invoke the user's preferred editor on the source file of Pred,
  1125.     providing a search specification which searches for the predicate at
  1126.     the start of a line.
  1127.  
  1128.  
  1129. ed
  1130.     Invoke ed/1 on the predicate last edited using ed/1.  Asks the user
  1131.     to confirm before starting the editor.
  1132.  
  1133.  
  1134. edit(+File)
  1135.     Invoke the user's preferred editor on File.  File is a file
  1136.     specification as for consult/1 (but not a list).  Note that the file
  1137.     should exist.
  1138.  
  1139.  
  1140. edit
  1141.     Invoke edit/1 on the file last edited using edit/1.  Asks the user to
  1142.     confirm before starting the editor.
  1143.  
  1144.  
  1145. listing(+Pred)
  1146.     List specified predicates (when an atom is given all predicates with
  1147.     this name will be listed).  The listing is produced on the basis of
  1148.     the internal representation, thus loosing user's layout and variable
  1149.     name information.  See also portray_clause/1.
  1150.  
  1151.  
  1152. listing
  1153.     List all predicates of the database using listing/1.
  1154.  
  1155.  
  1156. portray_clause(+Clause)
  1157.     Pretty print a clause as good as we can.  A clause should be
  1158.     specified as a term `Head :- Body' (put brackets around it to avoid
  1159.     operator precedence problems).  Facts are represented as
  1160.     `Head :- true'.
  1161.  
  1162.  
  1163. 3.4 Verify Type of a Term
  1164.  
  1165.  
  1166. var(+Term)
  1167.     Succeeds if Term currently is a free variable.
  1168.  
  1169.  
  1170. nonvar(+Term)
  1171.     Succeeds if Term currently is not a free variable.
  1172.  
  1173.  
  1174. integer(+Term)
  1175.     Succeeds if Term is bound to an integer.
  1176.  
  1177.  
  1178. float(+Term)
  1179.     Succeeds if Term is bound to a floating point number.
  1180.  
  1181.  
  1182. number(+Term)
  1183.     Succeeds if Term is bound to an integer or a floating point number.
  1184.  
  1185.  
  1186. atom(+Term)
  1187.     Succeeds if Term is bound to an atom.
  1188.  
  1189.  
  1190. string(+Term)
  1191.     Succeeds if Term is bound to a string.
  1192.  
  1193.  
  1194. atomic(+Term)
  1195.     Succeeds if Term is bound to an atom, string, integer or floating
  1196.     point number.
  1197.  
  1198.  
  1199. ground(+Term)
  1200.     Succeeds if Term holds no free variables.
  1201.  
  1202.  
  1203. 3.5 Comparison and Unification or Terms
  1204.  
  1205.  
  1206. 3.5.1 Standard Order of Terms
  1207.  
  1208. Comparison and unification of arbitrary terms.  Terms are ordered in the
  1209. so called ``standard order''.  This order is defined as follows:
  1210.  
  1211.  1. Variables< Atoms< Strings< Numbers< Terms
  1212.  
  1213.  2. Old Variable < New Variable
  1214.  
  1215.  3. Atoms are compared alphabetically.
  1216.  
  1217.  4. Strings are compared alphabetically.
  1218.  
  1219.  5. Numbers are compared by value.  Integers and floats are treated
  1220.     identically.
  1221.  
  1222.  6. Terms are first checked on their functor (alphabetically), then on
  1223.     their arity and finally recursively on their arguments, left most
  1224.     argument first.
  1225.  
  1226.  
  1227. +Term1 == +Term2
  1228.     Succeeds if Term1 is equivalent to Term2.  A variable is only
  1229.     identical to a sharing variable.
  1230.  
  1231.  
  1232. +Term1 \== +Term2
  1233.     Equivalent to `\+ Term1 == Term2'.
  1234.  
  1235.  
  1236. +Term1 = +Term2
  1237.     Unify Term1 with Term2.  Succeeds if the unification succeeds.
  1238.  
  1239.  
  1240. +Term1 \= +Term2
  1241.     Equivalent to `\+ Term1 = Term2'.
  1242.  
  1243.  
  1244. +Term1 =@= +Term2
  1245.     Succeeds if Term1 is `structurally equal' to Term2.  Structural
  1246.     equivalence is weaker than equivalence (==/2), but stronger than
  1247.     unification (=/2).  Two terms are structurally equal if their tree
  1248.     representation is identical and they have the same `pattern' of
  1249.     variables.  Examples:
  1250.  
  1251.               a =@=A        false
  1252.               A =@=B         true
  1253.          x(A,A) =@=x(B,C)   false
  1254.          x(A,A) =@=x(B,B)    true
  1255.          x(A,B) =@=x(C,D)    true
  1256.  
  1257.  
  1258. +Term1 \=@= +Term2
  1259.     Equivalent to `\+ Term1 =@= Term2'.
  1260.  
  1261.  
  1262. +Term1 @< +Term2
  1263.     Succeeds if Term1 is before Term2 in the standard order of terms.
  1264.  
  1265.  
  1266. +Term1 @=< +Term2
  1267.     Succeeds if both terms are equal (==) or Term1 is before Term2 in the
  1268.     standard order of terms.
  1269.  
  1270.  
  1271. +Term1 @> +Term2
  1272.     Succeeds if Term1 is after Term2 in the standard order of terms.
  1273.  
  1274.  
  1275. +Term1 @>= +Term2
  1276.     Succeeds if both terms are equal (==) or Term1 is after Term2 in the
  1277.     standard order of terms.
  1278.  
  1279.  
  1280. 3.6 Control Predicates
  1281.  
  1282. The predicates of this section implement control structures.  Normally
  1283. these constructs are translated into virtual machine instructions by the
  1284. compiler.  It is still necessary to implement these constructs as true
  1285. predicates to support meta-calls, as demonstrated in the example below.
  1286. The predicate finds all currently defined atoms of 1 character long.  Note
  1287. that the cut has no effect when called via one of these predicates (see
  1288. !/0).
  1289.  
  1290.     one_character_atoms(As) :-
  1291.            findall(A, (current_atom(A), atom_length(A, 1)), As).
  1292.  
  1293.  
  1294. fail
  1295.     Always fail.
  1296.  
  1297.  
  1298. true
  1299.     Always succeed.
  1300.  
  1301.  
  1302. repeat
  1303.     Always succeed, provide an infinite number of choice points.
  1304.  
  1305.  
  1306. !
  1307.     Cut.  Discard choice points of parent frame and frames created after
  1308.     the parent frame.  Note that the control structures ;/2, |/2 ->/2 and
  1309.     \+/1 are normally handled by the compiler and do not create a frame,
  1310.     which implies the cut operates through these predicates.  Some
  1311.     examples are given below.  Note the difference between t3/1 and t4/1.
  1312.     Also note the effect of call/1 in t5/0.  As the argument of call/1 is
  1313.     evaluated by predicates rather than the compiler the cut has no
  1314.     effect.
  1315.  
  1316.        t1 :- (a, !, fail ; b).      % cuts a/0 and t1/0
  1317.        t2 :- (a -> b, !  ; c).      % cuts b/0 and t2/0
  1318.        t3(G) :- a, G, fail.         % if `G = !'  cuts a/0 and t1/1
  1319.        t4(G) :- a, call(G), fail.   % if `G = !'  cut has no effect
  1320.        t5 :- call((a, !, fail ; b)).% Cut has no effect
  1321.        t6 :- \+ (a, !, fail ; b).   % cuts a/0 and t6/0
  1322.  
  1323.  
  1324. +Goal1 , +Goal2
  1325.     Conjunction.  Succeeds if both `Goal1' and `Goal2' can be proved.  It
  1326.     is defined as (this definition does not lead to a loop as the second
  1327.     comma is handled by the compiler):
  1328.  
  1329.         Goal1, Goal2 :- Goal1, Goal2.
  1330.  
  1331.  
  1332. +Goal1 ; +Goal2
  1333.     The `or' predicate is defined as:
  1334.  
  1335.         Goal1 ; _Goal2 :- Goal1.
  1336.         _Goal1 ; Goal2 :- Goal2.
  1337.  
  1338.  
  1339. +Goal1 | +Goal2
  1340.     Equivalent to ;/2.  Retained for compatibility only.  New code should
  1341.     use ;/2.
  1342.  
  1343.  
  1344. +Condition -> +Action
  1345.     If-then and If-Then-Else.  Implemented as:
  1346.  
  1347.         If -> Then; _Else :- If, !, Then.
  1348.         If -> _Then; Else :- !, Else.
  1349.         If -> Then :- If, !, Then.
  1350.  
  1351.  
  1352. \+ +Goal
  1353.     Succeeds if `Goal' cannot be proven (mnemnonic:  + refers to provable
  1354.     and the backslash is normally used to indicate negation).
  1355.  
  1356.  
  1357. 3.7 Meta-Call Predicates
  1358.  
  1359. Meta call predicates are used to call terms constructed at run time.  The
  1360. basic meta-call mechanism offered by SWI-Prolog is to use variables as a
  1361. subclause (which should of course be bound to a valid goal at runtime).  A
  1362. meta-call is slower than a normal call as it involves actually searching
  1363. the database at runtime for the predicate, while for normal calls this
  1364. search is done at compile time.
  1365.  
  1366.  
  1367. call(+Goal)
  1368.     Invoke Goal as a goal.  Note that clauses may have variables as
  1369.     subclauses, which is identical to call/1, except when the argument is
  1370.     bound to the cut.  See !/0.
  1371.  
  1372.  
  1373. apply(+Term, +List)
  1374.     Append the members of List to the arguments of Term and call the
  1375.     resulting term.  For example:  `apply(plus(1), [2, X])' will call
  1376.     `plus(1, 2, X)'.  Apply/2 is incorporated in the virtual machine of
  1377.     SWI-Prolog.  This implies that the overhead can be compared to the
  1378.     overhead of call/1.
  1379.  
  1380.  
  1381. not +Goal
  1382.     Succeeds when Goal cannot be proven.  Retained for compatibility
  1383.     only.  New code should use \+/1.
  1384.  
  1385.  
  1386. once(+Goal)
  1387.     Defined as:
  1388.  
  1389.         once(Goal) :-
  1390.                Goal, !.
  1391.  
  1392.     Once/1 can in many cases be replaced with ->/2.  The only difference
  1393.     is how the cut behaves (see !/0).  The following two clauses are
  1394.     identical:
  1395.  
  1396.         1) a :- once((b, c)), d.
  1397.         2) a :- b, c -> d.
  1398.  
  1399.  
  1400. ignore(+Goal)
  1401.     Calls Goal as once/1, but succeeds, regardless of whether Goal
  1402.     succeeded or not.  Defined as:
  1403.  
  1404.         ignore(Goal) :-
  1405.                Goal, !.
  1406.         ignore(_).
  1407.  
  1408.  
  1409. 3.8 Database
  1410.  
  1411. SWI-Prolog offers three different database mechanisms.  The first one is
  1412. the common assert/retract mechanism for manipulating the clause database.
  1413. As facts and clauses asserted using assert/1 or one of it's derivates
  1414. become part of the program these predicates compile the term given to
  1415. them.  Retract/1 and retractall/1 have to unify a term and therefore have
  1416. to decompile the program.  For these reasons the assert/retract mechanism
  1417. is expensive.  On the other hand, once compiled, queries to the database
  1418. are faster than querying the recorded database discussed below.  See also
  1419. dynamic/1.
  1420.  
  1421. The second way of storing arbitrary terms in the database is using the
  1422. ``recorded database''.  In this database terms are associated with a key.
  1423. A key can be an atom, integer or term.  In the last case only the functor
  1424. and arity determine the key.  Each key has a chain of terms associated
  1425. with it.  New terms can be added either at the head or at the tail of this
  1426. chain.  This mechanism is considerably faster than the assert/retract
  1427. mechanism as terms are not compiled, but just copied into the heap.
  1428.  
  1429. The third mechanism is a special purpose one.  It associates an integer or
  1430. atom with a key, which is an atom, integer or term.  Each key can only
  1431. have one atom or integer associated with it.  It again is considerably
  1432. faster than the mechanisms described above, but can only be used to store
  1433. simple status information like counters, etc.
  1434.  
  1435.  
  1436. abolish(+Functor, +Arity)
  1437.     Removes all clauses of a predicate with functor Functor and arity
  1438.     Arity from the database.  Unlike version 1.2, all predicate
  1439.     attributes (dynamic, multifile, index, etc.)  are reset to their
  1440.     defaults.  Abolishing an imported predicate only removes the import
  1441.     link; the predicate will keep its old definition in its definition
  1442.     module.  For `cleanup' of the dynamic database, one should use
  1443.     retractall/1 rather than abolish/2.
  1444.  
  1445.  
  1446. retract(+Term)
  1447.     When Term is an atom or a term it is unified with the first unifying
  1448.     fact or clause in the database.  The fact or clause is removed from
  1449.     the database.
  1450.  
  1451.  
  1452. retractall(+Term)
  1453.     All facts or clauses in the database that unify with Term are
  1454.     removed.
  1455.  
  1456.  
  1457. assert(+Term)
  1458.     Assert a fact or clause in the database.  Term is asserted as the
  1459.     last fact or clause of the corresponding predicate.
  1460.  
  1461.  
  1462. asserta(+Term)
  1463.     Equivalent to assert/1, but Term is asserted as first clause or fact
  1464.     of the predicate.
  1465.  
  1466.  
  1467. assertz(+Term)
  1468.     Equivalent to assert/1.
  1469.  
  1470.  
  1471. assert(+Term, -Reference)
  1472.     Equivalent to assert/1, but Reference is unified with a unique
  1473.     reference to the asserted clause.  This key can later be used with
  1474.     clause/3 or erase/1.
  1475.  
  1476.  
  1477. asserta(+Term, -Reference)
  1478.     Equivalent to assert/2, but Term is asserted as first clause or fact
  1479.     of the predicate.
  1480.  
  1481.  
  1482. assertz(+Term, -Reference)
  1483.     Equivalent to assert/2.
  1484.  
  1485.  
  1486. recorda(+Key, +Term, -Reference)
  1487.     Assert Term in the recorded database under key Key.  Key is an
  1488.     integer, atom or term.  Reference is unified with a unique reference
  1489.     to the record (see erase/1).
  1490.  
  1491.  
  1492. recorda(+Key, +Term)
  1493.     Equivalent to recorda(Key, Value, _).
  1494.  
  1495.  
  1496. recordz(+Key, +Term, -Reference)
  1497.     Equivalent to recorda/3, but puts the Term at the tail of the terms
  1498.     recorded under Key.
  1499.  
  1500.  
  1501. recordz(+Key, +Term)
  1502.     Equivalent to recordz(Key, Value, _).
  1503.  
  1504.  
  1505. recorded(+Key, -Value, -Reference)
  1506.     Unify Value with the first term recorded under Key which does unify.
  1507.     Reference is unified with the memory location of the record.
  1508.  
  1509.  
  1510. recorded(+Key, -Value)
  1511.     Equivalent to recorded(Key, Value, _).
  1512.  
  1513.  
  1514. erase(+Reference)
  1515.     Erase a record or clause from the database.  Reference is an integer
  1516.     returned by recorda/3 or recorded/3, clause/3, assert/2, asserta/2 or
  1517.     assertz/2.  Other integers might conflict with the internal
  1518.     consistency of the system.  Erase can only be called once on a record
  1519.     or clause.  A second call also might conflict with the internal
  1520.     consistency of the system.
  1521.  
  1522.     BUG: The system should have a special type for pointers, thus
  1523.     avoiding the Prolog user having to worry about consistency matters.
  1524.     Currently some simple heuristics are used to determine whether a
  1525.     reference is valid.
  1526.  
  1527.  
  1528. flag(+Key, -Old, +New)
  1529.     Key is an atom, integer or term.  Unify Old with the old value
  1530.     associated with Key.  If the key is used for the first time Old is
  1531.     unified with the integer 0.  Then store the value of New, which
  1532.     should be an integer, atom or arithmetic integer expression, under
  1533.     Key.  flag/3 is a very fast mechanism for storing simple facts in the
  1534.     database.  Example:
  1535.  
  1536.         :- module_transparent succeeds_n_times/2.
  1537.  
  1538.         succeeds_n_times(Goal, Times) :-
  1539.                flag(succeeds_n_times, _, 0),
  1540.                Goal,
  1541.                flag(succeeds_n_times, N, N+1),
  1542.                fail ; flag(succeeds_n_times, Times, Times).
  1543.  
  1544.  
  1545. 3.9 Declaring Properties of Predicates
  1546.  
  1547. This section describes directives which manipulate attributes of predicate
  1548. definitions.  The functors dynamic/1, multifile/1 and discontiguous/1 are
  1549. operators of priority 1150 (see op/3), which implies the list of
  1550. predicates they involve can just be a comma separated list:
  1551.  
  1552.     :- dynamic
  1553.            foo/0,
  1554.            baz/2.
  1555.  
  1556. On SWI-Prolog all these directives are just predicates.  This implies they
  1557. can also be called by a program.  Do not rely on this feature if you want
  1558. to maintain portability to other Prolog implementations.
  1559.  
  1560.  
  1561. dynamic +Functor/+Arity, ...
  1562.     Informs the interpreter that the definition of the predicate(s) may
  1563.     change during execution (using assert/1 and/or retract/1).  Currently
  1564.     dynamic/1 only stops the interpreter from complaining about undefined
  1565.     predicates (see unknown/2).  Future releases might prohibit assert/1
  1566.     and retract/1 for not-dynamic declared procedures.
  1567.  
  1568.  
  1569. multifile +Functor/+Arity, ...
  1570.     Informs the system that the specified predicate(s) may be defined
  1571.     over more than one file.  This stops consult/1 from redefining a
  1572.     predicate when a new definition is found.
  1573.  
  1574.  
  1575. discontiguous +Functor/+Arity, ...
  1576.     Informs the system that the clauses of the specified predicate(s)
  1577.     might not be together in the source file.  See also style_check/1.
  1578.  
  1579.  
  1580. index(+Head)
  1581.     Index the clauses of the predicate with the same name and arity as
  1582.     Head on the specified arguments.  Head is a term of which all
  1583.     arguments are either `1' (denoting `index this argument') or `0'
  1584.     (denoting `do not index this argument').  Indexing has no
  1585.     implications for the semantics of a predicate, only on its
  1586.     performance.  If indexing is enabled on a predicate a special purpose
  1587.     algorithm is used to select candidate clauses based on the actual
  1588.     arguments of the goal.  This algorithm checks whether indexed
  1589.     arguments might unify in the clause head.  Only atoms, integers and
  1590.     functors (e.g.  name and arity of a term) are considered.  Indexing
  1591.     is very useful for predicates with many clauses representing facts.
  1592.  
  1593.     Due to the representation technique used at most 4 arguments can be
  1594.     indexed.  All indexed arguments should be in the first 32 arguments
  1595.     of the predicate.  If more than 4 arguments are specified for
  1596.     indexing only the first 4 will be accepted.  Arguments above 32 are
  1597.     ignored for indexing.
  1598.  
  1599.     By default all predicates with arity 1 are indexed on their first
  1600.     argument.  It is possible to redefine indexing on predicates that
  1601.     already have clauses attached to them.  This will initiate a scan
  1602.     through the predicate's clause list to update the index summary
  1603.     information stored with each clause.
  1604.  
  1605.     If --for example-- one wants to represents sub-types using a fact
  1606.     list `sub_type(Sub, Super)'that should be used both to determine
  1607.     sub- and super types one should declare sub_type/2 as follows:
  1608.  
  1609.         :- index(sub_type(1, 1)).
  1610.  
  1611.         sub_type(horse, animal).
  1612.         ...
  1613.         ...
  1614.  
  1615.  
  1616. 3.10 Examining the Program
  1617.  
  1618.  
  1619. current_atom(-Atom)
  1620.     Successively unifies Atom with all atoms known to the system.  Note
  1621.     that current_atom/1 always succeeds if Atom is intantiated to an
  1622.     atom.
  1623.  
  1624.  
  1625. current_functor(?Name, ?Arity)
  1626.     Successively unifies Name with the name and Arity with the arity of
  1627.     functors known to the system.
  1628.  
  1629.  
  1630. current_flag(-FlagKey)
  1631.     Successively unifies FlagKey with all keys used for flags (see
  1632.     flag/3).
  1633.  
  1634.  
  1635. current_key(-Key)
  1636.     Successively unifies Key with all keys used for records (see
  1637.     recorda/3, etc.).
  1638.  
  1639.  
  1640. current_predicate(?Name, ?Head)
  1641.     Successively unifies Name with the name of predicates currently
  1642.     defined and Head with the most general term built from Name and the
  1643.     arity of the predicate.  This predicate succeeds for all predicates
  1644.     defined in the specified module, imported to it, or in one of the
  1645.     modules from which the predicate will be imported if it is called.
  1646.  
  1647.  
  1648. predicate_property(?Head, ?Property)
  1649.     Succeeds if Head refers to a predicate that has property Property.
  1650.     Can be used to test whether a predicate has a certain property,
  1651.     obtain all properties known for Head, find all predicates having
  1652.     property or even obtaining all information available about the
  1653.     current program.  Property is one of:
  1654.  
  1655.     interpreted
  1656.         Is true if the predicate is defined in Prolog.  We return true on
  1657.         this because, although the code is actually compiled, it is
  1658.         completely transparent, just like interpreted code.
  1659.  
  1660.     built_in
  1661.         Is true if the predicate is locked as a built-in predicate.  This
  1662.         implies it cannot be redefined in it's definition module and it
  1663.         can normally not be seen in the tracer.
  1664.  
  1665.     foreign
  1666.         Is true if the predicate is defined in the C language.
  1667.  
  1668.     dynamic
  1669.         Is true if the predicate is declared dynamic using the dynamic/1
  1670.         declaration.
  1671.  
  1672.     multifile
  1673.         Is true if the predicate is declared multifile using the
  1674.         multifile/1 declaration.
  1675.  
  1676.     undefined
  1677.         Is true if a procedure definition block for the predicate exists,
  1678.         but there are no clauses in it and it is not declared dynamic.
  1679.         This is true if the predicate occurs in the body of a loaded
  1680.         predicate, an attempt to call it has been made via one of the
  1681.         meta-call predicates or the predicate had a definition in the
  1682.         past.  See the library package check for example usage.
  1683.  
  1684.     transparent
  1685.         Is true if the predicate is declared transparent using the
  1686.         module_transparent/1 declaration.
  1687.  
  1688.     exported
  1689.         Is true if the predicate is in the public list of the context
  1690.         module.
  1691.  
  1692.     imported_from(Module)
  1693.         Is true if the predicate is imported into the context module from
  1694.         module Module.
  1695.  
  1696.     indexed(Head)
  1697.         Predicate is indexed (see index/1) according to Head.  Head is a
  1698.         term whose name and arity are identical to the predicate.  The
  1699.         arguments are unified with `1' for indexed arguments, `0'
  1700.         otherwise.
  1701.  
  1702.  
  1703. dwim_predicate(+Term, -Dwim)
  1704.     `Do What I Mean' (`dwim') support predicate.  Term is a term, which
  1705.     name and arity are used as a predicate specification.  Dwim is
  1706.     instantiated with the most general term built from Name and the arity
  1707.     of a defined predicate that matches the predicate specified by Term
  1708.     in the `Do What I Mean' sence.  See dwim_match/2 for `Do What I Mean'
  1709.     string matching.  Internal system predicates are not generated,
  1710.     unless style_check(+dollar)is active.  Backtracking provides all
  1711.     alternative matches.
  1712.  
  1713.  
  1714. clause(?Head, ?Body)
  1715.     Succeeds when Head can be unified with a clause head and Body with
  1716.     the corresponding clause body.  Gives alternative clauses on
  1717.     backtracking.  For facts Body is unified with the atom true.
  1718.     Normally clause/2 is used to find clause definitions for a predicate,
  1719.     but it can also be used to find clause heads for some body template.
  1720.  
  1721.  
  1722. clause(?Head, ?Body, ?Reference)
  1723.     Equivalent to clause/2, but unifies Reference with a unique reference
  1724.     to the clause (see also assert/2, erase/1).  If Reference is
  1725.     instantiated to a reference the clause's head and body will be
  1726.     unified with Head and Body.
  1727.  
  1728.  
  1729. 3.11 Input and Output
  1730.  
  1731. SWI-Prolog provides two different packages for input and output.  One
  1732. confirms to the Edinburgh standard.  This package has a notion of
  1733. `current-input' and `current-output'.  The reading and writing predicates
  1734. implicitely refer to these streams.  In the second package, streams are
  1735. opened explicitely and the resulting handle is used as an argument to the
  1736. reading and writing predicate to specify the source or destination.  Both
  1737. packages are fully integrated; the user may switch freely between them.
  1738.  
  1739.  
  1740. 3.11.1 Input and Output Using Implicit Source and Destination
  1741.  
  1742. The package for implicit input and output destination is upwards
  1743. compatible to DEC-10 and C-Prolog.  The reading and writing predicates
  1744. refer to resp.  the current input- and output stream.  Initially these
  1745. streams are connected to the terminal.  The current output stream is
  1746. changed using tell/1 or append/1.  The current input stream is changed
  1747. using see/1.  The stream's current value can be obtained using telling/1
  1748. for output- and seeing/1 for input streams.  The table below shows the
  1749. valid stream specifications.  The reserved names user_input, user_output
  1750. and user_errorare for neat integration with the explicit streams.
  1751.  
  1752.      user                  This reserved name refers to the
  1753.                            terminal
  1754.      user_input            Input from the terminal
  1755.  
  1756.      user_output           Output to the terminal
  1757.  
  1758.      stderr or user_error  Unix error stream (output only)
  1759.  
  1760.      Atom                  Name of a Unix file
  1761.      pipe(Atom)            Name of a Unix command
  1762.  
  1763. Source and destination are either a file, one of the reserved words above,
  1764. or a term `pipe(Command)'.  In the predicate descriptions below we will
  1765. call the source/destination argument `SrcDest'.  Below are some examples
  1766. of source/destination specifications.
  1767.  
  1768.        ?- see(data).       % Start reading from file `data'.
  1769.        ?- tell(stderr).    % Start writing on the error stream.
  1770.        ?- tell(pipe(lpr)). % Start writing to the printer.
  1771.  
  1772. Another example of using the pipe/1 construct is shown on in figure 3.1.
  1773. Note that the pipe/1 construct is not part of Prolog's standard I/O
  1774. reportoire.
  1775.  
  1776.     getwd(Wd) :-
  1777.            seeing(Old), see(pipe(pwd)),
  1778.            collect_wd(String),
  1779.            seen, see(Old),
  1780.            name(Wd, String).
  1781.  
  1782.     collect_wd([C|R]) :-
  1783.            get0(C), C \== -1, !,
  1784.            collect_wd(R).
  1785.     collect_wd([]).
  1786.  
  1787.                 Figure 3.1:  Get the working directory
  1788.  
  1789.  
  1790. see(+SrcDest)
  1791.     Make SrcDest the current input stream.  If SrcDest was already opened
  1792.     for reading with see/1 and has not been closed since, reading will be
  1793.     resumed.  Otherwise SrcDest will be opened and the file pointer is
  1794.     positioned at the start of the file.
  1795.  
  1796.  
  1797. tell(+SrcDest)
  1798.     Make SrcDest the current output stream.  If SrcDest was already
  1799.     opened for writing with tell/1 or append/1 and has not been closed
  1800.     since, writing will be resumed.  Otherwise the file is created or
  1801.     --when existing-- truncated.  See also append/1.
  1802.  
  1803.  
  1804. append(+File)
  1805.     Similar to tell/1, but positions the file pointer at the end of File
  1806.     rather than truncating an existing file.  The pipe construct is not
  1807.     accepted by this predicate.
  1808.  
  1809.  
  1810. seeing(-SrcDest)
  1811.     Unify the name of the current input stream with SrcDest.
  1812.  
  1813.  
  1814. telling(-SrcDest)
  1815.     Unify the name of the current output stream with SrcDest.
  1816.  
  1817.  
  1818. seen
  1819.     Close the current input stream.  The new input stream becomes user.
  1820.  
  1821.  
  1822. told
  1823.     Close the current output stream.  The new output stream becomes user.
  1824.  
  1825.  
  1826. 3.11.2 Explicit Input and Output Streams
  1827.  
  1828. The predicates below are part of the Quintus compatible stream-based I/O
  1829. package.  In this package streams are explicitely created using the
  1830. predicate open/3.  The resulting stream identifier is then passed as a
  1831. parameter to the reading and writing predicates to specify the source or
  1832. destination of the data.
  1833.  
  1834.  
  1835. open(+SrcDest, +Mode, ?Stream)
  1836.     SrcDest is either an atom, specifying a Unix file, or a term
  1837.     `pipe(Command)', just like see/1 and tell/1.  Mode is one of read,
  1838.     writeor append.  Stream is either a variable, in which case it is
  1839.     bound to a small integer identifying the stream, or an atom, in which
  1840.     case this atom will be the stream indentifier.  In the latter case
  1841.     the atom cannot be an already existing stream identifier.  Examples:
  1842.  
  1843.       ?- open(data, read, Stream).       % Open `data' for reading.
  1844.       ?- open(pipe(lpr), write, printer).% `printer' is a stream to `lpr'.
  1845.  
  1846.  
  1847. open_null_stream(?Stream)
  1848.     On Unix systems, this is equivalent to
  1849.     open('/dev/null', write, Stream).  Characters written to this stream
  1850.     are lost, but the stream information (see character_count/2, etc.)
  1851.     is maintained.
  1852.  
  1853.  
  1854. close(+Stream)
  1855.     Close the specified stream.  If Stream is not open an error message
  1856.     is displayed.  If the closed stream is the current input or output
  1857.     stream the terminal is made the current input or output.
  1858.  
  1859.  
  1860. current_stream(?File, ?Mode, ?Stream)
  1861.     Is true if a stream with file specification File, mode Mode and
  1862.     stream identifier Stream is open.  The reserved streams user and
  1863.     user_error are not generated by this predicate.  If a stream has been
  1864.     opened with mode appendthis predicate will generate mode write.
  1865.  
  1866.  
  1867. stream_position(+Stream, -Old, +New)
  1868.     Unify the position parameters of Stream with Old and set them to New.
  1869.     A position is represented by the following term:
  1870.  
  1871.         '$stream_position'(CharNo, LineNo, LinePos).
  1872.  
  1873.     It is only possible to change the position parameters if the stream
  1874.     is connected to a disk file.
  1875.  
  1876.  
  1877. 3.11.3 Switching Between Implicit and Explicit I/O
  1878.  
  1879. The predicates below can be used for switching between the implicit- and
  1880. the explicit stream based I/O predicates.
  1881.  
  1882.  
  1883. set_input(+Stream)
  1884.     Set the current input stream to become Stream.  Thus, open(file,
  1885.     read, Stream), set_input(Stream) is equivalent to see(file).
  1886.  
  1887.  
  1888. set_output(+Stream)
  1889.     Set the current output stream to become Stream.
  1890.  
  1891.  
  1892. current_input(-Stream)
  1893.     Get the current input stream.  Useful to get access to the status
  1894.     predicates associated with streams.
  1895.  
  1896.  
  1897. current_output(-Stream)
  1898.     Get the current output stream.
  1899.  
  1900.  
  1901. 3.12 Status of Input and Output Streams
  1902.  
  1903.  
  1904. wait_for_input(+ListOfStreams, -ReadyList, +TimeOut)
  1905.     Wait for input on one of the streams in ListOfStreams and return a
  1906.     list of streams on which input is available in ReadyList.
  1907.     wait_for_input/3 waits for at most TimeOut seconds.  Timeout may be
  1908.     specified as a floating point number to specify fractions of a
  1909.     second.  If Timeout equals 0, wait_for_input/3 waits indefinetely.
  1910.     This predicate can be used to implement timeout while reading and to
  1911.     handle input from multiple sources.  The following example will wait
  1912.     for input from the user and an explicitely opened second terminal.
  1913.     On return, Inputs may hold user or P4 or both.
  1914.  
  1915.         ?- open('/dev/ttyp4', read, P4),
  1916.           wait_for_input([user, P4], Inputs, 0).
  1917.  
  1918.  
  1919. character_count(+Stream, -Count)
  1920.     Unify Count with the current character index.  For input streams this
  1921.     is the number of characters read since the open, for output streams
  1922.     this is the number of characters written.  Counting starts at 0.
  1923.  
  1924.  
  1925. line_count(+Stream, -Count)
  1926.     Unify Count with the number of lines read or written.  Counting
  1927.     starts at 1.
  1928.  
  1929.  
  1930. line_position(+Stream, -Count)
  1931.     Unify Count with the position on the current line.  Note that this
  1932.     assumes the position is 0 after the open.  Tabs are assumed to be
  1933.     defined on each 8-th character and backspaces are assumed to reduce
  1934.     the count by one, provided it is positive.
  1935.  
  1936.  
  1937. fileerrors(-Old, +New)
  1938.     Define error behaviour on errors when opening a file for reading or
  1939.     writing.  Valid values are the atoms on (default) and off.  First Old
  1940.     is unified with the current value.  Then the new value is set to New.
  1941.  
  1942.  
  1943. tty_fold(-OldColumn, +NewColumn)
  1944.     Fold Prolog output to stream user on column NewColumn.  If Column is
  1945.     0 or less no folding is performed (default).  OldColumn is first
  1946.     unified with the current folding column.  To be used on terminals
  1947.     that do not support line folding.
  1948.  
  1949.  
  1950. 3.13 Primitive Character Input and Output
  1951.  
  1952.  
  1953. nl
  1954.     Write a newline character to the current output stream.  On Unix
  1955.     systems nl/0 is equivalent to put(10).
  1956.  
  1957.  
  1958. nl(+Stream)
  1959.     Write a newline to Stream.
  1960.  
  1961.  
  1962. put(+Char)
  1963.     Write Char to the current output stream, Char is either an
  1964.     integer-expression evaluating to an ASCII value (0  Char 255) or an
  1965.     atom of one character.
  1966.  
  1967.  
  1968. put(+Stream, +Char)
  1969.     Write Char to Stream.
  1970.  
  1971.  
  1972. tab(+Amount)
  1973.     Writes Amount spaces on the current output stream.  Amount should be
  1974.     an expression that evaluates to a positive integer (see
  1975.     section 3.19).
  1976.  
  1977.  
  1978. tab(+Stream, +Amount)
  1979.     Writes Amount spaces to Stream.
  1980.  
  1981.  
  1982. flush
  1983.     Flush pending output on current output stream.  flush/0 is
  1984.     automatically generated by read/1 and derivates if the current input
  1985.     stream is user and the cursor is not at the left margin.
  1986.  
  1987.  
  1988. flush_output(+Stream)
  1989.     Flush output on the specified stream.  The stream must be open for
  1990.     writing.
  1991.  
  1992.  
  1993. ttyflush
  1994.     Flush pending output on stream user.  See also flush/0.
  1995.  
  1996.  
  1997. get0(-Char)
  1998.     Read the current input stream and unify the next character with Char.
  1999.     Char is unified with -1 on end of file.
  2000.  
  2001.  
  2002. get0(+Stream, -Char)
  2003.     Read the next character from Stream.
  2004.  
  2005.  
  2006. get(-Char)
  2007.     Read the current input stream and unify the next non-blank character
  2008.     with Char.  Char is unified with -1 on end of file.
  2009.  
  2010.  
  2011. get(+Stream, -Char)
  2012.     Read the next non-blank character from Stream.
  2013.  
  2014.  
  2015. get_single_char(-Char)
  2016.     Get a single character from input stream `user' (regardless of the
  2017.     current input stream).  Unlike get0/1 this predicate does not wait
  2018.     for a return.  The character is not echoed to the user's terminal.
  2019.     This predicate is meant for keyboard menu selection etc..  If
  2020.     SWI-Prolog was started with the -tty flag this predicate reads an
  2021.     entire line of input and returns the first non-blank character on
  2022.     this line, or the ASCII code of the newline (10) if the entire line
  2023.     consisted of blank characters.
  2024.  
  2025.  
  2026. 3.14 Term Reading and Writing
  2027.  
  2028.  
  2029. display(+Term)
  2030.     Write Term on the current output stream using standard parenthesised
  2031.     prefix notation (i.e.  ignoring operator declarations).  Display is
  2032.     normally used to examine the internal representation for terms
  2033.     holding operators.
  2034.  
  2035.  
  2036. display(+Stream, +Term)
  2037.     Display Term on Stream.
  2038.  
  2039.  
  2040. displayq(+Term)
  2041.     Write Term on the current output stream using standard parenthesised
  2042.     prefix notation (i.e.  ignoring operator declarations).  Atoms that
  2043.     need quotes are quoted.  Terms written with this predicate can always
  2044.     be read back, regardless of current operator declarations.
  2045.  
  2046.  
  2047. displayq(+Stream, +Term)
  2048.     Display Term on Stream.  Equivalent to Quintus write_canonical/2.
  2049.  
  2050.  
  2051. write(+Term)
  2052.     Write Term to the current output, using brackets and operators where
  2053.     appropriate.
  2054.  
  2055.  
  2056. write(+Stream, +Term)
  2057.     Write Term to Stream.
  2058.  
  2059.  
  2060. writeq(+Term)
  2061.     Write Term to the current output, using brackets and operators where
  2062.     appropriate.  Atoms that need quotes are quoted.  Terms written with
  2063.     this predicate can be read back with read/1 provided the currently
  2064.     active operator declarations are identical.
  2065.  
  2066.  
  2067. writeq(+Stream, +Term)
  2068.     Write Term to Stream, inserting quotes.
  2069.  
  2070.  
  2071. print(+Term)
  2072.     Prints Term on the current output stream similar to write/1, but for
  2073.     each (sub)term of Term first the dynamic predicate portray/1 is
  2074.     called.  If this predicate succeeds print assumes the (sub)term has
  2075.     been written.  This allows for user defined term writing.
  2076.  
  2077.  
  2078. print(+Stream, +Term)
  2079.     Print Term to Stream.
  2080.  
  2081.  
  2082. portray(+Term)
  2083.     A dynamic predicate, which can be defined by the user to change the
  2084.     behaviour of print/1 on (sub)terms.  For each subterm encountered
  2085.     that is not a variable print/1 first calls portray/1 using the term
  2086.     as argument.  For lists only the list as a whole is given to
  2087.     portray/1.  If portray succeeds print/1 assumes the term has been
  2088.     written.
  2089.  
  2090.  
  2091. read(-Term)
  2092.     Read the next Prolog term from the current input stream and unify it
  2093.     with Term.  On a syntax error read/1 displays an error message,
  2094.     attempts to skip the erroneous term and fails.  On reaching
  2095.     end-of-file Term is unified with the atom end_of_file.
  2096.  
  2097.  
  2098. read(+Stream, -Term)
  2099.     Read Term from Stream.
  2100.  
  2101.  
  2102. read_clause(-Term)
  2103.     Equivalent to read/1, but warns the user for variables only occurring
  2104.     once in a term (singleton variables) which do not start with an
  2105.     underscore if style_check(singleton)is active (default).  Used to
  2106.     read Prolog source files (see consult/1).
  2107.  
  2108.  
  2109. read_clause(+Stream, -Term)
  2110.     Read a clause from Stream.
  2111.  
  2112.  
  2113. read_variables(-Term, -Bindings)
  2114.     Similar to read/1, but Bindings is unified with a list of
  2115.     `Name= Var' tuples, thus providing access to the actual variable
  2116.     names.
  2117.  
  2118.  
  2119. read_variables(+Stream, -Term, -Bindings)
  2120.     Read, returning term and bindings from Stream.
  2121.  
  2122.  
  2123. read_history(+Show, +Help, +Special, +Prompt, -Term, -Bindings)
  2124.     Similar to read_variables/2, but allows for history substitutions.
  2125.     history_read/6 is used by the top level to read the user's actions.
  2126.     Show is the command the user should type to show the saved events.
  2127.     Help is the command to get an overview of the capabilities.  Special
  2128.     is a list of commands that are not saved in the history.  Prompt is
  2129.     the first prompt given.  Continuation prompts for more lines are
  2130.     determined by prompt/2.  A %w in the prompt is substituted by the
  2131.     event number.  See section 2.4 for available substitutions.
  2132.  
  2133.     SWI-Prolog calls history_read/6 as follows:
  2134.  
  2135.         read_history(h, '!h', [trace], '%w ?- ', Goal, Bindings)
  2136.  
  2137.  
  2138. history_depth(-Int)
  2139.     Dynamic predicate, normally not defined.  The user can define this
  2140.     predicate to set the history depth.  It should unify the argument
  2141.     with a positive integer.  When not defined 15 is used as the default.
  2142.  
  2143.  
  2144. prompt(-Old, +New)
  2145.     Set prompt associated with read/1 and its derivates.  Old is first
  2146.     unified with the current prompt.  On success the prompt will be set
  2147.     to New if this is an atom.  Otherwise an error message is displayed.
  2148.     A prompt is printed if one of the read predicates is called and the
  2149.     cursor is at the left margin.  It is also printed whenever a newline
  2150.     is given and the term has not been terminated.  Prompts are only
  2151.     printed when the current input stream is user.
  2152.  
  2153.  
  2154. 3.15 Analysing and Constructing Terms
  2155.  
  2156.  
  2157. functor(?Term, ?Functor, ?Arity)
  2158.     Succeeds if Term is a term with functor Functor and arity Arity.  If
  2159.     Term is a variable it is unified with a new term holding only
  2160.     variables.  functor/3 silently fails on instantiation faults
  2161.  
  2162.  
  2163. arg(+Arg, +Term, ?Value)
  2164.     Term should be instantiated to a term, Arg to an integer between 1
  2165.     and the arity of Term.  Value is unified with the Arg-th argument of
  2166.     Term.
  2167.  
  2168.  
  2169. ?Term =..  ?List
  2170.     List is a list which head is the functor of Term and the remaining
  2171.     arguments are the arguments of the term.  Each of the arguments may
  2172.     be a variable, but not both.  This predicate is called `Univ'.
  2173.     Examples:
  2174.  
  2175.         ?- foo(hello, X) =.. List.
  2176.  
  2177.         List = [foo, hello, X]
  2178.  
  2179.         ?- Term =.. [baz, foo(1)]
  2180.  
  2181.         Term = baz(foo(1))
  2182.  
  2183.  
  2184. numbervars(+Term, +Functor, +Start, -End)
  2185.     Unify the free variables of Term with a term constructed from the
  2186.     atom Functor with one argument.  The argument is the number of the
  2187.     variable.  Counting starts at Start.  End is unified with the number
  2188.     that should be given to the next variable.  Example:
  2189.  
  2190.         ?- numbervars(foo(A, B, A), this_is_a_variable, 0, End).
  2191.  
  2192.         A = this_is_a_variable(0)
  2193.         B = this_is_a_variable(1)
  2194.         End = 2
  2195.  
  2196.     In Edinburgh Prolog the second argument is missing.  It is fixed to
  2197.     be '$VAR'.
  2198.  
  2199.  
  2200. free_variables(+Term, -List)
  2201.     Unify List with a list of variables, each sharing with a unique
  2202.     variable of Term.  For example:
  2203.  
  2204.         ?- free_variables(a(X, b(Y, X), Z), L).
  2205.  
  2206.         L = [G367, G366, G371]
  2207.         X = G367
  2208.         Y = G366
  2209.         Z = G371
  2210.  
  2211.  
  2212. copy_term(+In, -Out)
  2213.     Make a copy of term In and unify the result with Out.  Ground parts
  2214.     of In are shared by Out.  Provided In and Out have no sharing
  2215.     variables before this call they will have no sharing variables
  2216.     afterwards.  copy_term/2 is semantically equivalent to:
  2217.  
  2218.         copy_term(In, Out) :-
  2219.                recorda(copy_key, In, Ref),
  2220.                recorded(copy_key, Out, Ref),
  2221.                erase(Ref).
  2222.  
  2223.  
  2224. 3.16 Analysing and Constructing Atoms
  2225.  
  2226.  
  2227. name(?Atom, ?String)
  2228.     String is a list of ASCII values describing Atom.  Each of the
  2229.     arguments may be a variable, but not both.  When String is bound to
  2230.     an ASCII value list describing an integer and Atom is a variable Atom
  2231.     will be unified with the integer value described by String (e.g.
  2232.     `name(N, "300"), 400 is N + 100' succeeds).
  2233.  
  2234.  
  2235. int_to_atom(+Int, +Base, -Atom)
  2236.     Convert Int to an ascii representation using base Base and unify the
  2237.     result with Atom.  If Base6= 10 the base will be prepended to Atom.
  2238.     Base= 0 will try to interpret Int as an ASCII value and return 0'c.
  2239.     Otherwise 2  Base 36.  Some examples are given below.
  2240.  
  2241.                 int_to_atom(45, 2, A)     !  A = 20101101
  2242.                 int_to_atom(97, 0, A)     !  A = 00a
  2243.                 int_to_atom(56, 10, A)    !  A = 56
  2244.  
  2245.  
  2246. int_to_atom(+Int, -Atom)
  2247.     Equivalent to int_to_atom(Int, 10, Atom).
  2248.  
  2249.  
  2250. term_to_atom(?Term, ?Atom)
  2251.     Succeeds if Atom describes a term that unifies with Term.  When Atom
  2252.     is instantiated Atom is converted and then unified with Term.
  2253.     Otherwise Term is ``written'' on Atom using write/1.
  2254.  
  2255.  
  2256. atom_to_term(+Atom, -Term, -Bindings)
  2257.     Use Atom as input to read_variables/2 and return the read term in
  2258.     Term and the variable bindings in Bindings.  Bindings is a list of
  2259.     Name= Varcouples, thus providing access to the actual variable
  2260.     names.  See also read_variables/2.
  2261.  
  2262.  
  2263. concat(?Atom1, ?Atom2, ?Atom3)
  2264.     Atom3 forms the concatenation of Atom1 and Atom2.  At least two of
  2265.     the arguments must be instantiated to atoms, intergers or floating
  2266.     point numbers.
  2267.  
  2268.  
  2269. concat_atom(+List, -Atom)
  2270.     List is a list of atoms, integers or floating point numbers.
  2271.     Succeeds if Atom can be unified with the concatenated elements of
  2272.     List.  If List has exactly 2 elements it is equivalent to concat/3,
  2273.     allowing for variables in the list.
  2274.  
  2275.  
  2276. atom_length(+Atom, -Length)
  2277.     Succeeds if Atom is an atom of Length characters long.  This
  2278.     predicate also works for integers and floats, expressing the number
  2279.     of characters output when given to write/1.
  2280.  
  2281.  
  2282. 3.17 Representing Text in Strings
  2283.  
  2284. SWI-Prolog supports the data type string.  Strings are a time and space
  2285. efficient mechanism to handle text in Prolog.  Atoms are under some
  2286. circumstances not suitable because garbage collection on them is next to
  2287. impossible (Although it is possible:  BIM_prolog does it).  Representing
  2288. text as a list of ASCII values is, from the logical point of view, the
  2289. cleanest solution.  It however has two drawbacks:  1) they cannot be
  2290. distinguished from a list of (small) integers; and 2) they consume (in
  2291. SWI-Prolog) 12 bytes for each character stored.
  2292.  
  2293. Within strings each character only requires 1 byte storage.  Strings live
  2294. on the global stack and their storage is thus reclaimed on backtracking.
  2295. Garbage collection can easily deal with strings.
  2296.  
  2297. The ISO standard proposes "..." is transformed into a string object by
  2298. read/1 and derivates.  This poses problems as in the old convention "..."
  2299. is transformed into a list of ascii characters.  For this reason the style
  2300. check option `string' is available (see style_check/2).
  2301.  
  2302. The set of predicates associated with strings is incomplete and tentative.
  2303. Names and definitions might change in the future to confirm to the
  2304. emerging standard.
  2305.  
  2306.  
  2307. string_to_atom(?String, ?Atom)
  2308.     Logical conversion between a string and an atom.  At least one of the
  2309.     two arguments must be instantiated.  Atom can also be an integer or
  2310.     floating point number.
  2311.  
  2312.  
  2313. string_to_list(?String, ?List)
  2314.     Logical conversion between a string and a list of ASCII characters.
  2315.     At least one of the two arguments must be instantiated.
  2316.  
  2317.  
  2318. string_length(+String, -Length)
  2319.     Unify Length with the number of characters in String.  This predicate
  2320.     is functonally equivalent to atom_length/2 and also accepts atoms,
  2321.     integers and floats as its first argument.
  2322.  
  2323.  
  2324. substring(+String, +Start, +Length, -Sub)
  2325.     Create a substring of String that starts at character Start (1 base)
  2326.     and has Length characters.  Unify this substring with Sub.
  2327.  
  2328.  
  2329. 3.18 Operators
  2330.  
  2331.  
  2332. op(+Precedence, +Type, +Name)
  2333.     Declare Name to be an operator of type Type with precedence
  2334.     Precedence.  Name can also be a list of names, in which case all
  2335.     elements of the list are declared to be identical operators.
  2336.     Precedence is an integer between 0 and 1200.  Precedence 0 removes
  2337.     the declaration.  Type is one of:  xf, yf, xfx, xfy, yfx, yfy, fy or
  2338.     fx.  The `f' indicates the position of the functor, while x and y
  2339.     indicate the position of the arguments.  `y' should be interpreted as
  2340.     ``on this position a term with precedence lower or equal to the
  2341.     precedence of the functor should occur''.  For `x' the precedence of
  2342.     the argument must be strictly lower.  The precedence of a term is 0,
  2343.     unless its principal functor is an operator, in which case the
  2344.     precedence is the precedence of this operator.  A term enclosed in
  2345.     brackets ((...)) has precedence 0.
  2346.  
  2347.     The predefined operators are shown in table 3.1.  Note that all
  2348.     operators can be redefined by the user.
  2349.  
  2350.           1200   xfx   -->, :-
  2351.  
  2352.           1200   fx    :-, ?-
  2353.  
  2354.           1150   fx    dynamic, multifile,
  2355.                        module_transparent, discontiguous
  2356.  
  2357.           1100   xfy   ;, |
  2358.  
  2359.           1050   xfy   ->
  2360.           1000   xfy   ,
  2361.  
  2362.           954    xfy   \\
  2363.  
  2364.           900    fy    \+, not
  2365.  
  2366.           700    xfx   <, =, =.., =@=, =:=, =<, ==, =\=, >,
  2367.                        >=, @<, @=<, @>, @>=, \=, \==, is
  2368.  
  2369.           600    xfy   :
  2370.           500    yfx   +, -, /\, \/, xor
  2371.  
  2372.           500    fx    +, -, ?, \
  2373.  
  2374.           400    yfx   *, /, //, <<, >>
  2375.  
  2376.           300    xfx   mod
  2377.           200    xfy   ^
  2378.  
  2379.                     Table 3.1:  System operators
  2380.  
  2381.  
  2382. current_op(?Precedence, ?Type, ?Name)
  2383.     Succeeds when Name is currently defined as an operator of type Type
  2384.     with precedence Precedence.  See also op/3.
  2385.  
  2386.  
  2387. 3.19 Arithmetic
  2388.  
  2389. Arithmetic can be divided into some special purpose integer predicates and
  2390. a series of general predicates for floating point and integer arithmetic
  2391. as appropriate.  The integer predicates are as ``logical'' as possible.
  2392. Their usage is recommended whenever applicable, resulting in faster and
  2393. more ``logical'' programs.
  2394.  
  2395. The general arithmic predicates are optionaly compiled now (see please/3
  2396. and the -O command line option).  Compiled arithmetic reduces global stack
  2397. requirements and improves performance.  Unfortunately compiled arithmetic
  2398. cannot be traced, which is why it is optional.
  2399.  
  2400. The general arithmetic predicates all handle expressions.  An expression
  2401. is either a simple number or a function.  The arguments of a function are
  2402. expressions.  The functions are described in section 3.20.
  2403.  
  2404.  
  2405. between(+Low, +High, ?Value)
  2406.     Low and High are integers, High Low.  If Value is an integer,
  2407.     Low Value High.  When Value is a variable it is successively bound
  2408.     to all integers between Low and High.
  2409.  
  2410.  
  2411. succ(?Int1, ?Int2)
  2412.     Succeeds if Int2= Int1+ 1.  At least one of the arguments must be
  2413.     instantiated to an integer.
  2414.  
  2415.  
  2416. plus(?Int1, ?Int2, ?Int3)
  2417.     Succeeds if Int3= Int1+ Int2.  At least two of the three arguments
  2418.     must be instantiated to integers.
  2419.  
  2420.  
  2421. +Expr1 > +Expr2
  2422.     Succeeds when expression Expr1 evaluates to a larger number than
  2423.     Expr2.
  2424.  
  2425.  
  2426. +Expr1 < +Expr2
  2427.     Succeeds when expression Expr1 evaluates to a smaller number than
  2428.     Expr2.
  2429.  
  2430.  
  2431. +Expr1 =< +Expr2
  2432.     Succeeds when expression Expr1 evaluates to a smaller or equal number
  2433.     to Expr2.
  2434.  
  2435.  
  2436. +Expr1 >= +Expr2
  2437.     Succeeds when expression Expr1 evaluates to a larger or equal number
  2438.     to Expr2.
  2439.  
  2440.  
  2441. +Expr1 =\= +Expr2
  2442.     Succeeds when expression Expr1 evaluates to a number non-equal to
  2443.     Expr2.
  2444.  
  2445.  
  2446. +Expr1 =:= +Expr2
  2447.     Succeeds when expression Expr1 evaluates to a number equal to Expr2.
  2448.  
  2449.  
  2450. -Number is +Expr
  2451.     Succeeds when Number has successfully been unified with the number
  2452.     Expr evaluates to.
  2453.  
  2454.  
  2455. 3.20 Arithmetic Functions
  2456.  
  2457. Arithmetic functions are terms which are evaluated by the arithmetic
  2458. predicates described above.  SWI-Prolog tries to hide the difference
  2459. between integer arithmetic and floating point arithmetic from the Prolog
  2460. user.  Arithmetic is done as integer arithmetic as long as possible and
  2461. converted to floating point arithmetic whenever one of the arguments or
  2462. the combination of them requires it.  If a function returns a floating
  2463. point value which is whole it is automatically transformed into an
  2464. integer.  There are three types of arguments to functions:
  2465.  
  2466.       Expr     Arbitrary expression, returning either a floating
  2467.                point value or an integer.
  2468.  
  2469.       IntExpr  Arbitrary expression that should evaluate into an
  2470.                integer.
  2471.  
  2472.       Int      An integer.
  2473.  
  2474. In case integer addition, subtraction and multiplication would lead to an
  2475. integer overflow the operands are automatically converted to floating
  2476. point numbers.  The floating point functions (sin/1, exp/1, etc.)  form a
  2477. direct interface to the corresponding C library functions used to compile
  2478. SWI-Prolog.  Please refer to the C library documentation for details on
  2479. percision, error handling, etc.
  2480.  
  2481.  
  2482. - +Expr
  2483.     Result= Expr
  2484.  
  2485.  
  2486. +Expr1 + +Expr2
  2487.     Result= Expr1+ Expr2
  2488.  
  2489.  
  2490. +Expr1 - +Expr2
  2491.     Result= Expr1 Expr2
  2492.  
  2493.  
  2494. +Expr1 * +Expr2
  2495.     Result= Expr1Expr2times
  2496.  
  2497.  
  2498. +Expr1 / +Expr2
  2499.     Result= Expr1=Expr2
  2500.  
  2501.  
  2502. +IntExpr1 mod +IntExpr2
  2503.     Result= Expr1mod Expr2 (remainder of division).
  2504.  
  2505.  
  2506. +IntExpr1 // +IntExpr2
  2507.     Result= Expr1div Expr2 (integer division).
  2508.  
  2509.  
  2510. abs(+Expr)
  2511.     Evaluate Expr and return the absolute value of it.
  2512.  
  2513.  
  2514. max(+Expr1, +Expr2)
  2515.     Evaluates to the largest of both Expr1 and Expr2.
  2516.  
  2517.  
  2518. min(+Expr1, +Expr2)
  2519.     Evaluates to the smallest of both Expr1 and Expr2.
  2520.  
  2521.  
  2522. .(+Int, [])
  2523.     A list of one element evaluates to the element.  This implies "a"
  2524.     evaluates to the ASCII value of the letter a (97).  This option is
  2525.     available for compatibility only.  It will not work if
  2526.     `style_check(+string)' is active as "a" will then be tranformed into
  2527.     a string object.  The recommended way to specify the ASCII value of
  2528.     the letter `a' is 0'a.
  2529.  
  2530.  
  2531. random(+Int)
  2532.     Evaluates to a random integer i for which 0  i < Int.  The seed of
  2533.     this random generator is determined by the system clock when
  2534.     SWI-Prolog was started.
  2535.  
  2536.  
  2537. integer(+Expr)
  2538.     Evaluates Expr and rounds the result to the nearest integer.
  2539.  
  2540.  
  2541. floor(+Expr)
  2542.     Evaluates Expr and returns the largest integer smaller or equal to
  2543.     the result of the evaluation.
  2544.  
  2545.  
  2546. ceil(+Expr)
  2547.     Evaluates Expr and returns the smallest integer larger or equal to
  2548.     the result of the evaluation.
  2549.  
  2550.  
  2551. +IntExpr >> +IntExpr
  2552.     Bitwise shift IntExpr1 by IntExpr2 bits to the right.  Note that
  2553.     integers are only 27 bits.
  2554.  
  2555.  
  2556. +IntExpr << +IntExpr
  2557.     Bitwise shift IntExpr1 by IntExpr2 bits to the left.
  2558.  
  2559.  
  2560. +IntExpr \/ +IntExpr
  2561.     Bitwise `or' IntExpr1 and IntExpr2.
  2562.  
  2563.  
  2564. +IntExpr /\ +IntExpr
  2565.     Bitwise `and' IntExpr1 and IntExpr2.
  2566.  
  2567.  
  2568. +IntExpr xor +IntExpr
  2569.     Bitwise `exclusive or' IntExpr1 and IntExpr2.
  2570.  
  2571.  
  2572. \ +IntExpr
  2573.     Bitwise negation.
  2574.  
  2575.  
  2576. sqrt(+Expr)
  2577.     Result= square root of Expr
  2578.  
  2579.  
  2580. sin(+Expr)
  2581.     Result= sine of Expr.  Expr is the angle in radials.
  2582.  
  2583.  
  2584. cos(+Expr)
  2585.     Result= cosine of Expr.  Expr is the angle in radials.
  2586.  
  2587.  
  2588. tan(+Expr)
  2589.     Result= tangus of Expr.  Expr is the angle in radials.
  2590.  
  2591.  
  2592. asin(+Expr)
  2593.     Result= inverse sine of Expr.  Result is the angle in radials.
  2594.  
  2595.  
  2596. acos(+Expr)
  2597.     Result= inverse cosine of Expr.  Result is the angle in radials.
  2598.  
  2599.  
  2600. atan(+Expr)
  2601.     Result= inverse tangus of Expr.  Result is the angle in radials.
  2602.  
  2603.  
  2604. atan(+YExpr, +XExpr)
  2605.     Result= inverse tangus of YExpr / XExpr.  Result is the angle in
  2606.     radials.  The return value is in the range pi:::pi.  Used to convert
  2607.     between rectangular and polar coordinate system.
  2608.  
  2609.  
  2610. log(+Expr)
  2611.     Result= natural logarithm of Expr
  2612.  
  2613.  
  2614. log10(+Expr)
  2615.     Result= 10 base logarithm of Expr
  2616.  
  2617.  
  2618. exp(+Expr)
  2619.     Result= e to the power Expr
  2620.  
  2621.  
  2622. +Expr1 ^ +Expr2
  2623.     Result= Expr1 to the power Expr2
  2624.  
  2625.  
  2626. pi
  2627.     Evaluates to the mathematical constant pi (3.141593...).
  2628.  
  2629.  
  2630. e
  2631.     Evaluates to the mathematical constant e (2.718282...).
  2632.  
  2633.  
  2634. cputime
  2635.     Evaluates to a floating point number expressing the cpu time (in
  2636.     seconds) used by Prolog up till now.  See also statistics/2 and
  2637.     time/1.
  2638.  
  2639.  
  2640. 3.21 Adding Arithmetic Functions
  2641.  
  2642. Prolog predicates can be given the role of arithmetic function.  The last
  2643. argument is used to return the result, the arguments before the last are
  2644. the inputs.  Arithmetic functions are added using the predicate
  2645. arithmetic_function/1, which takes the head as its argument.  Arithmetic
  2646. functions are module sensitive, that is they are only visible from the
  2647. module in which the function is defined and delared.  Global arithmetic
  2648. functions should be defined and registered from module user.  Global
  2649. definitions can be overruled locally in modules.  The builtin functions
  2650. described above can be redefined as well.
  2651.  
  2652.  
  2653. arithmetic_function(+Head)
  2654.     Register a Prolog predicate as an arithmetic function (see is/2, >/2,
  2655.     etc.).  The Prolog predicate should have one more argument than
  2656.     specified by Head, which it either a term Name/Arity, an atom or a
  2657.     complex term.  This last argument is an unbound variable at call time
  2658.     and should be instantiated to an integer or floating point number.
  2659.     The other arguments are the parameters.  This predicate is module
  2660.     sensitive and will declare the arithmetic function only for the
  2661.     context module, unless declared from module user.  Example:
  2662.  
  2663.         1 ?- [user].
  2664.         :- arithmetic_function(mean/2).
  2665.  
  2666.         mean(A, B, C) :-
  2667.                C is (A+B)/2.
  2668.         user compiled, 0.07 sec, 440 bytes.
  2669.  
  2670.         Yes
  2671.         2 ?- A is mean(4, 5).
  2672.  
  2673.         A = 4.500000
  2674.  
  2675.  
  2676. current_arithmetic_function(?Head)
  2677.     Succesively unifies all arithmetic functions that are visible from
  2678.     the context module with Head.
  2679.  
  2680.  
  2681. 3.22 List Manipulation
  2682.  
  2683.  
  2684. is_list(+Term)
  2685.     Succeeds if Term is bound to the empty list ([]) or a term with
  2686.     functor `.' and arity 2.
  2687.  
  2688.  
  2689. proper_list(+Term)
  2690.     Equivalent to is_list/1, but also requires the tail of the list to be
  2691.     a list (recursively).  Examples:
  2692.  
  2693.         is_list([x|A])         % true
  2694.         proper_list([x|A])      % false
  2695.  
  2696.  
  2697. append(?List1, ?List2, ?List3)
  2698.     Succeeds when List3 unifies with the concatenation of List1 and
  2699.     List2.  The predicate can be used with any instantiation pattern
  2700.     (even three variables).
  2701.  
  2702.  
  2703. member(?Elem, ?List)
  2704.     Succeeds when Elem can be unified with one of the members of List.
  2705.     The predicate can be used with any instantiation pattern.
  2706.  
  2707.  
  2708. memberchk(?Elem, +List)
  2709.     Equivalent to member/2, but leaves no choice point.
  2710.  
  2711.  
  2712. delete(+List1, ?Elem, ?List2)
  2713.     Delete all members of List1 that simultaneously unify with Elem and
  2714.     unify the result with List2.
  2715.  
  2716.  
  2717. select(?List1, ?Elem, ?List2)
  2718.     Select an element of List1 that unifies with Elem.  List2 is unified
  2719.     with the list remaining from List1 after deleting the selected
  2720.     element.  Normally used with the instantiation pattern +List1, -Elem,
  2721.     -List2, but can also be used to insert an element in a list using
  2722.     -List1, +Elem, +List2.
  2723.  
  2724.  
  2725. nth0(?Index, ?List, ?Elem)
  2726.     Succeeds when the Index-th element of List unifies with Elem.
  2727.     Counting starts at 0.
  2728.  
  2729.  
  2730. nth1(?Index, ?List, ?Elem)
  2731.     Succeeds when the Index-th element of List unifies with Elem.
  2732.     Counting starts at 1.
  2733.  
  2734.  
  2735. last(?Elem, ?List)
  2736.     Succeeds if Elem unifies with the last element of List.
  2737.  
  2738.  
  2739. reverse(+List1, -List2)
  2740.     Reverse the order of the elements in List1 and unify the result with
  2741.     the elements of List2.
  2742.  
  2743.  
  2744. flatten(+List1, -List2)
  2745.     Transform List1, possibly holding lists as elements into a `flat'
  2746.     list by replacing each list with its elements (recursively).  Unify
  2747.     the resulting flat list with List2.  Example:
  2748.  
  2749.         ?- flatten([a, [b, [c, d], e]], X).
  2750.  
  2751.         X = [a, b, c, d, e]
  2752.  
  2753.  
  2754. length(?List, ?Int)
  2755.     Succeeds if Int represents the number of elements of list List.  Can
  2756.     be used to create a list holding only variables.
  2757.  
  2758.  
  2759. merge(+List1, +List2, -List3)
  2760.     List1 and List2 are lists, sorted to the standard order of terms (see
  2761.     section 3.5).  List3 will be unified with an ordered list holding the
  2762.     both the elements of List1 and List2.  Duplicates are not removed.
  2763.  
  2764.  
  2765. 3.23 Set Manipulation
  2766.  
  2767.  
  2768. is_set(+Set)
  2769.     Succeeds if set is a proper list (see proper_list/1) without
  2770.     duplicates.
  2771.  
  2772.  
  2773. list_to_set(+List, -Set)
  2774.     Succeeds if Set holds the same elements as List in the same order,
  2775.     but has no duplicates.  See also sort/1.
  2776.  
  2777.  
  2778. intersection(+Set1, +Set2, -Set3)
  2779.     Succeeds if Set3 unifies with the intersection of Set1 and Set2.
  2780.     Set1 and Set2 are lists without duplicates.  They need not be
  2781.     ordered.
  2782.  
  2783.  
  2784. subtract(+Set, +Delete, -Result)
  2785.     Delete all elements of set `Delete' from `Set' and unify the
  2786.     resulting set with `Result'.
  2787.  
  2788.  
  2789. union(+Set1, +Set2, -Set3)
  2790.     Succeeds if Set3 unifies with the union of Set1 and Set2.  Set1 and
  2791.     Set2 are lists without duplicates.  They need not be ordered.
  2792.  
  2793.  
  2794. subset(+Subset, +Set)
  2795.     Succeeds if all elements of Subset are elements of Set as well.
  2796.  
  2797.  
  2798. merge_set(+Set1, +Set2, -Set3)
  2799.     Set1 and Set2 are lists without duplicates, sorted to the standard
  2800.     order of terms.  Set3 is unified with an ordered list without
  2801.     duplicates holding the union of the elements of Set1 and Set2.
  2802.  
  2803.  
  2804. 3.24 Sorting Lists
  2805.  
  2806.  
  2807. sort(+List, -Sorted)
  2808.     Succeeds if Sorted can be unified with a list holding the elements of
  2809.     List, sorted to the standard order of terms (see section 3.5).
  2810.     Duplicates are removed.
  2811.  
  2812.  
  2813. msort(+List, -Sorted)
  2814.     Equivalent to sort/2, but does not remove duplicates.
  2815.  
  2816.  
  2817. keysort(+List, -Sorted)
  2818.     List is a list of Key-Valuepairs (e.g.  terms of the functor `-'
  2819.     with arity 2).  keysort/2 sorts List like msort/2, but only compares
  2820.     the keys.  Can be used to sort terms not on standard order, but on
  2821.     any criterion that can be expressed on a multi-dimensional scale.
  2822.     Sorting on more than one criterion can be done using terms as keys,
  2823.     putting the first criterion as argument 1, the second as argument 2,
  2824.     etc.
  2825.  
  2826.  
  2827. predsort(+Pred, +List, -Sorted)
  2828.     Sorts similar to msort/2, but determines the order of two terms by
  2829.     applying Pred to pairs of elements from List (see apply/2).  The
  2830.     predicate should succeed if the first element should be before the
  2831.     second.
  2832.  
  2833.  
  2834. 3.25 Finding all Solutions to a Goal
  2835.  
  2836.  
  2837. findall(+Var, +Goal, -Bag)
  2838.     Creates a list of the instantiations Var gets successively on
  2839.     backtracking over Goal and unifies the result with Bag.  Succeeds
  2840.     with an empty list if Goal has no solutions.  findall/3 is equivalent
  2841.     to bagof/3 with all free variables bound with the existence operator
  2842.     (^), except that bagof/3 fails when goal has no solutions.
  2843.  
  2844.  
  2845. bagof(+Var, +Goal, -Bag)
  2846.     Unify Bag with the alternatives of Var, if Goal has free variables
  2847.     besides the one sharing with Var bagof will backtrack over the
  2848.     alternatives of these free variables, unifying Bag with the
  2849.     corresponding alternatives of Var.  The construct Var^Goal tells
  2850.     bagof not to bind Var in Goal.  Bagof/3 fails if Goal has no
  2851.     solutions.
  2852.  
  2853.     The example below illustrates bagof/3 and the ^ operator.  The
  2854.     variable bindings are printed together on one line to save paper.
  2855.  
  2856.         2 ?- listing(foo).
  2857.  
  2858.         foo(a, b, c).
  2859.         foo(a, b, d).
  2860.         foo(b, c, e).
  2861.         foo(b, c, f).
  2862.         foo(c, c, g).
  2863.  
  2864.         Yes
  2865.         3 ?- bagof(C, foo(A, B, C), Cs).
  2866.  
  2867.         A = a, B = b, C = G308, Cs = [c, d] ;
  2868.         A = b, B = c, C = G308, Cs = [e, f] ;
  2869.         A = c, B = c, C = G308, Cs = [g] ;
  2870.  
  2871.         No
  2872.         4 ?- bagof(C, A^foo(A, B, C), Cs).
  2873.  
  2874.         A = G324, B = b, C = G326, Cs = [c, d] ;
  2875.         A = G324, B = c, C = G326, Cs = [e, f, g] ;
  2876.  
  2877.         No
  2878.         5 ?-
  2879.  
  2880.  
  2881. setof(+Var, +Goal, -Set)
  2882.     Equivalent to bagof/3, but sorts the result using sort/2 to get a
  2883.     sorted list of alternatives without duplicates.
  2884.  
  2885.  
  2886. 3.26 Invoking Predicates on all Members of a List
  2887.  
  2888. All the predicates in this section call a predicate on all members of a
  2889. list or until the predicate called fails.  The predicate is called via
  2890. apply/2, which implies common arguments can be put in front of the
  2891. arguments obtained from the list(s).  For example:
  2892.  
  2893.     ?- maplist(plus(1), [0, 1, 2], X).
  2894.  
  2895.     X = [1, 2, 3]
  2896.  
  2897. we will phrase this as ``Predicate is applied on ...''
  2898.  
  2899.  
  2900. checklist(+Pred, +List)
  2901.     Pred is applied successively on each element of List until the end of
  2902.     the list or Pred fails.  In the latter case the checklist/2 fails.
  2903.  
  2904.  
  2905. maplist(+Pred, ?List1, ?List2)
  2906.     Apply Pred on all successive pairs of elements from List1 and List2.
  2907.     Fails if Pred can not be applied to a pair.  See the example above.
  2908.  
  2909.  
  2910. sublist(+Pred, +List1, ?List2)
  2911.     Unify List2 with a list of all elements of List1 to which Pred
  2912.     applies.
  2913.  
  2914.  
  2915. 3.27 Forall
  2916.  
  2917.  
  2918. forall(+Cond, +Action)
  2919.     For all alternative bindings of Cond Action can be proven.  The
  2920.     example verifies that all arithmic statements in the list L are
  2921.     correct.  It does not say which is wrong if one proves wrong.
  2922.  
  2923.         ?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]),
  2924.                        Result =:= Formula).
  2925.  
  2926.  
  2927. 3.28 Formatted Write
  2928.  
  2929. The current version of SWI-Prolog provides two formatted write predicates.
  2930. The first is writef/[1,2], which is compatible with Edinburgh C-Prolog.
  2931. The second is format/[1,2], which is compatible with Quintus Prolog.  We
  2932. hope the Prolog community will once define a standard formatted write
  2933. predicate.  If you want performance use format/[1,2] as this predicate is
  2934. defined in C. Otherwise compatibility reasons might tell you which
  2935. predicate to use.
  2936.  
  2937.  
  2938. 3.28.1 Writef
  2939.  
  2940.  
  2941. write_ln(+Term)
  2942.     Equivalent to write(Term), nl.
  2943.  
  2944.  
  2945. writef(+Atom)
  2946.     Equivalent to writef(Atom, []).
  2947.  
  2948.  
  2949. writef(+Format, +Arguments)
  2950.     Formatted write.  Format is an atom whose characters will be printed.
  2951.     Format may contain certain special character sequences which specify
  2952.     certain formatting and substitution actions.  Arguments then provides
  2953.     all the terms required to be output.
  2954.  
  2955.     Escape sequences to generate a single special character:
  2956.  
  2957.             \n     <NL> is output
  2958.  
  2959.             \l     <LF> is output
  2960.  
  2961.             \r     <CR> is output
  2962.  
  2963.             \t     <TAB> is output
  2964.  
  2965.             \\     The character `\' is output
  2966.  
  2967.             \%     The character `%' is output
  2968.  
  2969.             \nnn   where nnn is an integer (1-3 digits) the
  2970.                    character with ASCII code nnn is output (NB
  2971.                    : nnn is read as DECIMAL)
  2972.  
  2973.     Escape sequences to include arguments from Arguments.  Each time a %
  2974.     escape sequence is found in Format the next argument from Arguments
  2975.     is formatted according to the specification.
  2976.  
  2977.             %t     print/1 the next item (mnemonic:  term)
  2978.  
  2979.             %w     write/1 the next item
  2980.  
  2981.             %q     writeq/1 the next item
  2982.  
  2983.             %d     display/1 the next item
  2984.  
  2985.             %p     print/1 the next item (identical to %t)
  2986.  
  2987.             %n     put the next item as a character (i.e.  it
  2988.                    is an ASCII value)
  2989.  
  2990.             %r     write the next item N times where N is the
  2991.                    second item (an integer)
  2992.  
  2993.             %s     write the next item as a String (so it must
  2994.                    be a list of characters)
  2995.  
  2996.             %f     perform a ttyflush/0 (no items used)
  2997.  
  2998.             %Nc    write the next item Centered in N columns.
  2999.             %Nl    write the next item Left justified in N
  3000.                    columns.
  3001.             %Nr    write the next item Right justified in N
  3002.                    columns.  N is a decimal number with at
  3003.                    least one digit.  The item must be an atom,
  3004.                    integer, float or string.
  3005.  
  3006.  
  3007. swritef(-String, +Format, +Arguments)
  3008.     Equivalent to writef/3, but ``writes'' the result on String instead
  3009.     of the current output stream.  Example:
  3010.  
  3011.         ?- swritef(S, '%15L%w', ['Hello', 'World']).
  3012.  
  3013.         S = "Hello         World"
  3014.  
  3015.  
  3016. swritef(-String, +Format)
  3017.     Equivalent to swritef(String, Format, []).
  3018.  
  3019.  
  3020. 3.28.2 Format
  3021.  
  3022.  
  3023. format(+Format)
  3024.     Defined as `format(Format) :- format(Format, []).'
  3025.  
  3026.  
  3027. format(+Format, +Arguments)
  3028.     Format is an atom, list of ASCII values, or a Prolog string.
  3029.     Arguments provides the arguments required by the format
  3030.     specification.  If only one argument is required and this is not a
  3031.     list of ASCII values the argument need not be put in a list.
  3032.     Otherwise the arguments are put in a list.
  3033.  
  3034.     Special sequences start with the tilde (~), followed by an optional
  3035.     numeric argument, followed by a character describing the action to be
  3036.     undertaken.  A numeric argument is either a sequence of digits,
  3037.     representing a positive decimal number, a sequence `<character>,
  3038.     representing the ASCII value of the character (only useful for ~t) or
  3039.     a asterisk (*), in when the numeric argument is taken from the next
  3040.     argument of the argument list, which should be a positive integer.
  3041.     Actions are:
  3042.  
  3043.       ~ Output the tilde itself.
  3044.       a Output the next argument, which should be an atom.  This option
  3045.         is equivalent to w.  Compatibility reasons only.
  3046.  
  3047.       c Output the next argument as an ASCII value.  This argument should
  3048.         be an integer in the range [0, ..., 255] (including 0 and 255).
  3049.  
  3050.       d Output next argument as a decimal number.  It should be an
  3051.         integer.  If a numeric argument is specified a dot is inserted
  3052.         argument positions from the right (useful for doing fixed point
  3053.         arithmetic with integers, such as handling amounts of money).
  3054.  
  3055.       D Same as d, but makes large values easier to read by inserting a
  3056.         comma every three digits left to the dot or right.
  3057.  
  3058.       e Output next argument as a floating point number in exponentional
  3059.         notation.  The numeric argument specifies the precission.
  3060.         Default is 6 digits.  Exact representation depends on the C
  3061.         library function printf().  This function is invoked with the
  3062.         format %.<percission>e.
  3063.  
  3064.       E Equivalent to e, but outputs a capital E to indicate the
  3065.         exponent.
  3066.  
  3067.       f Floating point in non-exponentional notation.  See C library
  3068.         function printf().
  3069.  
  3070.       g Floating point in e or f notation, whichever is shorter.
  3071.  
  3072.       G Floating point in E or f notation, whichever is shorter.
  3073.  
  3074.       i Ignore next argument of the argument list.  Produces no output.
  3075.  
  3076.       k Give the next argument to displayq/1 (canonical write).
  3077.  
  3078.       n Output a newline character.
  3079.  
  3080.       N Only output a newline if the last character output on this stream
  3081.         was not a newline.  Not properly implemented yet.
  3082.  
  3083.       p Give the next argument to print/1.
  3084.  
  3085.       q Give the next argument to writeq/1.
  3086.  
  3087.       r Print integer in radix the numeric argument notation.  Thus ~16r
  3088.         prints its argument hexadecimal.  The argument should be in the
  3089.         range [2, ...  36].  Lower case letters are used for digits above
  3090.         9.
  3091.  
  3092.       R Same as r, but uses upper case letters for digits above 9.
  3093.  
  3094.       s Output a string of ASCII characters from the next argument.
  3095.  
  3096.       t All remaining space between 2 tabstops is distributed equaly over
  3097.         ~t statements between the tabstops.  This space is padded with
  3098.         spaces by default.  If an argument is supplied this is taken to
  3099.         be the ASCII value of the character used for padding.  This can
  3100.         be used to do left or right alignment, centering, distributing,
  3101.         etc.  See also ~| and ~+ to set tab stops.  A tabstop is assumed
  3102.         at the start of each line.
  3103.  
  3104.        __Set a tabstop on the current position.  If an argument is
  3105.         supplied set a tabstop on the position of that argument.  This
  3106.         will cause all ~t's to be distributed between the previous and
  3107.         this tabstop.
  3108.  
  3109.       + Set a tabstop relative to the current position.  Further the same
  3110.         as ~|.
  3111.  
  3112.       w Give the next argument to write/1.
  3113.  
  3114.     Example:
  3115.  
  3116.         simple_statistics :-
  3117.            <obtain statistics>        % left to the user
  3118.            format('~tStatistics~t~72|~n~n'),
  3119.            format('Runtime: ~`.t ~2f~34|  Inferences: ~`.t ~D~72|~n',
  3120.                                                [RunT, Inf]),
  3121.            ....
  3122.  
  3123.     Will output
  3124.  
  3125.                                   Statistics
  3126.  
  3127.         Runtime: .................. 3.45  Inferences: .......... 60,345
  3128.  
  3129.  
  3130. sformat(-String, +Format, +Arguments)
  3131.     Equivalent to format/3, but ``writes'' the result on String instead
  3132.     of the current output stream.  Example:
  3133.  
  3134.         ?- sformat(S, '~w~t~15|~w', ['Hello', 'World']).
  3135.  
  3136.         S = "Hello         World"
  3137.  
  3138.  
  3139. sformat(-String, +Format)
  3140.     Equivalent to `sformat(String, Format, []).'
  3141.  
  3142.  
  3143. 3.28.3 Programming Format
  3144.  
  3145.  
  3146. format_predicate(+Char, +Head)
  3147.     If a sequence ~c (tilde, followed by some character) is found, the
  3148.     format derivates will first check whether the user has defined a
  3149.     predicate to handle the format.  If not, the built in formatting
  3150.     rules described above are used.  Char is either an ascii value, or a
  3151.     one character atom, specifying the letter to be (re)defined.  Head is
  3152.     a term, whose name and arity are used to determine the predicate to
  3153.     call for the redefined formatting character.  The first argument to
  3154.     the predicate is the numeric argument of the format command, or the
  3155.     atom defaultif no argument is specified.  The remaining arguments
  3156.     are filled from the argument list.  The example below redefines ~n to
  3157.     produce  Arg times return followed by linefeed (so a (Grr.)  DOS
  3158.     machine is happy with the output).
  3159.  
  3160.         :- format_predicate(n, dos_newline(_Arg)).
  3161.  
  3162.         dos_newline(Arg) :-
  3163.                between(1, Ar, _), put(13), put(10), fail ; true.
  3164.  
  3165.  
  3166. 3.29 Terminal Control
  3167.  
  3168. The following predicates form a simple access mechanism to the Unix
  3169. termcap library to provide terminal independant I/O for screen terminals.
  3170. The library package tty builds on top of these predicates.
  3171.  
  3172.  
  3173. tty_get_capability(+Name, +Type, -Result)
  3174.     Get the capability named Name from the termcap library.  See
  3175.     termcap(5) for the capability names.  Type specifies the type of the
  3176.     expected result, and is one of string, numberor bool.  String
  3177.     results are returned as an atom, number result as an integer and bool
  3178.     results as the atom on or off.  If an option cannot be found this
  3179.     predicate fails silently.  The results are only computed once.
  3180.     Succesive queries on the same capability are fast.
  3181.  
  3182.  
  3183. tty_goto(+X, +Y)
  3184.     Goto position (X, Y) on the screen.  Note that the predicates
  3185.     line_count/2 and line_position/2 will not have a well defined
  3186.     behaviour while using this predicate.
  3187.  
  3188.  
  3189. tty_put(+Atom, +Lines)
  3190.     Put an atom via the termcap library function tputs().  This function
  3191.     decodes padding information in the strings returned by
  3192.     tty_get_capability/3 and should be used to output these strings.
  3193.     Lines is the number of lines affected by the operation, or 1 if not
  3194.     applicable (as in almost all cases).
  3195.  
  3196.  
  3197. set_tty(-OldStream, +NewStream)
  3198.     Set the output stream, used by tty_put/2 and tty_goto/2 to a specific
  3199.     stream.  Default is user_output.
  3200.  
  3201.  
  3202. 3.30 Unix Interaction
  3203.  
  3204.  
  3205. shell(+Command, -Status)
  3206.     Execute Command on the operating system.  Command is given to the
  3207.     bourne shell (/bin/sh).  Status is unified with the exit status of
  3208.     the command.
  3209.  
  3210.  
  3211. shell(+Command)
  3212.     Equivalent to `shell(Command, 0)'.
  3213.  
  3214.  
  3215. shell
  3216.     Start an interactive Unix shell.  Default is /bin/sh, the environment
  3217.     variable SHELL overrides this default.
  3218.  
  3219.  
  3220. getenv(+Name, -Value)
  3221.     Get Unix environment variable (see csh(1) and sh(1)).  Fails if the
  3222.     variable does not exist.
  3223.  
  3224.  
  3225. setenv(+Name, +Value)
  3226.     Set Unix environment variable.  Name and Value should be instantiated
  3227.     to atoms or integers.  The environment variable will be passed to
  3228.     shell/[0-2] and can be requested using getenv/2.
  3229.  
  3230.  
  3231. unsetenv(+Name)
  3232.     Remove Unix environment variable from the environment.
  3233.  
  3234.  
  3235. get_time(-Time)
  3236.     Return the number of seconds that elapsed since the epoch of Unix, 1
  3237.     January 1970, 0 hours.  Time is a floating point number.  Its
  3238.     granularity is system dependant.  On SUN, this is 1/60 of a second.
  3239.  
  3240.  
  3241. convert_time(+Time, -Year, -Month, -Day, -Hour, -Minute, -Second, -MilliSeconds)
  3242.  
  3243.     Convert a time stamp, provided by get_time/1, file_time/2, etc.  Year
  3244.     is unified with the year, Month with the month number (January is 1),
  3245.     Day with the day of the month (starting with 1), Hour with the hour
  3246.     of the day (0--23), Minute with the minute (0--59).  Second with the
  3247.     second (0--59) and MilliSecond with the milli seconds (0--999).  Note
  3248.     that the latter might not be acurate or might always be 0, depending
  3249.     on the timing capabilities of the system.
  3250.  
  3251.  
  3252. 3.31 Unix File System Interaction
  3253.  
  3254.  
  3255. access_file(+File, +Mode)
  3256.     Succeeds when File exists and can be accessed by this prolog process
  3257.     under mode Mode.  Mode is one of the atoms read, write or execute.
  3258.     File may also be the name of a directory.  Fails silently otherwise.
  3259.  
  3260.  
  3261. exists_file(+File)
  3262.     Succeeds when File exists.  This does not imply the user has read
  3263.     and/or write permission for the file.
  3264.  
  3265.  
  3266. same_file(+File1, +File2)
  3267.     Succeeds if both filenames refer to the same physical file.  That is,
  3268.     if File1 and File2 are the same string or both names exist and point
  3269.     to the same file (due to hard or symbolic links and/or relative vs.
  3270.     absolute paths).
  3271.  
  3272.  
  3273. exists_directory(+Directory)
  3274.     Succeeds if Directory exists.  This does not imply the user has read,
  3275.     search and or write permission for the directory.
  3276.  
  3277.  
  3278. delete_file(+File)
  3279.     Unlink File from the Unix file system.
  3280.  
  3281.  
  3282. rename_file(+File1, +File2)
  3283.     Rename File1 into File2.  Currently files cannot be moved across
  3284.     devices.
  3285.  
  3286.  
  3287. size_file(+File, -Size)
  3288.     Unify Size with the size of File in characters.
  3289.  
  3290.  
  3291. time_file(+File, -Time)
  3292.     Unify the last modification time of File with Time.  Time is a
  3293.     floating point number expressing the seconds ellapsed since Jan 1,
  3294.     1970.
  3295.  
  3296.  
  3297. absolute_file_name(+File, -Absolute)
  3298.     Expand Unix file specification into an absolute path.  User home
  3299.     directory expansion (~ and ~user) and variable expansion is done.
  3300.     The absolute path is canonised:  references to `.'  and `..'  are
  3301.     deleted.  SWI-Prolog uses absolute file names to register source
  3302.     files independant of the current working directory.
  3303.  
  3304.  
  3305. expand_file_name(+WildChart, -List)
  3306.     Unify List with a sorted list of files or directories matching
  3307.     WildChart.  The normal Unix wildchart constructs `?', `*', `[...]'
  3308.     and `{...}' are recognised.  The interpretation of `{...}' is
  3309.     interpreted slightly different from the C shell (csh(1)).  The comma
  3310.     separated argument can be arbitrary patterns, including `{...}'
  3311.     patterns.  The empty pattern is legal as well:  `{.pl,}' matches
  3312.     either `.pl' or the empty string.
  3313.  
  3314.  
  3315. chdir(+Path)
  3316.     Change working directory to Path.
  3317.  
  3318.  
  3319. 3.32 User Toplevel Manipulation
  3320.  
  3321.  
  3322. break
  3323.     Recursively start a new Prolog top level.  This Prolog top level has
  3324.     it's own stacks, but shares the heap with all break environments and
  3325.     the top level.  Debugging is switched off on entering a break and
  3326.     restored on leaving one.  The break environment is terminated by
  3327.     typing the system's end-of-filecharacter (control-D). If the
  3328.     -t toplevelcommand line option is given this goal is started instead
  3329.     of entering the default interactive top level (prolog/0).
  3330.  
  3331.  
  3332. abort
  3333.     Abort the Prolog execution and start a new top level.  If the
  3334.     -t toplevelcommand line options is given this goal is started
  3335.     instead of entering the default interactive top level.  Break
  3336.     environments are aborted as well.  All open files except for the
  3337.     terminal related files are closed.  The input- and output stream
  3338.     again refers to user.
  3339.  
  3340.     BUG: Erased clauses which could not actually be removed from the
  3341.     database, because they are active in the interpreter, will never be
  3342.     garbage collected after an abort.
  3343.  
  3344.  
  3345. halt
  3346.     Terminate Prolog execution.  Open files are closed and if the command
  3347.     line option -tty is not active the terminal status (see Unix stty(1))
  3348.     is restored.
  3349.  
  3350.  
  3351. prolog
  3352.     This goal starts the default interactive top level.  prolog/0 is
  3353.     terminated (succeeds) by typing control-D.
  3354.  
  3355.  
  3356. 3.33 Creating a Protocol of the Unser Interaction
  3357.  
  3358. SWI-Prolog offers the possibility to log the interaction with the user on
  3359. a file.  All Prolog interaction, including warnings and tracer output, are
  3360. written on the protocol file.
  3361.  
  3362.  
  3363. protocol(+File)
  3364.     Start protocolling on file File.  If there is already a protocol file
  3365.     open then close it first.  If File exists it is truncated.
  3366.  
  3367.  
  3368. protocola(+File)
  3369.     Equivalent to protocol/1, but does not truncate the File if it
  3370.     exists.
  3371.  
  3372.  
  3373. noprotocol
  3374.     Stop making a protocol of the user interaction.  Pending output is
  3375.     flushed on the file.
  3376.  
  3377.  
  3378. protocolling(-File)
  3379.     Succeeds if a protocol was started with protocol/1 or protocola/1 and
  3380.     unifies File with the current protocol output file.
  3381.  
  3382.  
  3383. 3.34 Debugging and Tracing Programs
  3384.  
  3385.  
  3386. trace
  3387.     Start the tracer.  trace/0 itself cannot be seen in the tracer.  Note
  3388.     that the Prolog toplevel treats trace/0 special; it means `trace the
  3389.     next goal'.
  3390.  
  3391.  
  3392. tracing
  3393.     Succeeds when the tracer is currently switched on.  tracing/0 itself
  3394.     can not be seen in the tracer.
  3395.  
  3396.  
  3397. notrace
  3398.     Stop the tracer.  notrace/0 itself cannot be seen in the tracer.
  3399.  
  3400.  
  3401. debug
  3402.     Start debugger (stop at spy points).
  3403.  
  3404.  
  3405. nodebug
  3406.     Stop debugger (do not trace, nor stop at spy points).
  3407.  
  3408.  
  3409. debugging
  3410.     Print debug status and spy points on current output stream.
  3411.  
  3412.  
  3413. spy(+Pred)
  3414.     Put a spy point on all predicates meeting the predicate specification
  3415.     Pred.  See section 3.3.
  3416.  
  3417.  
  3418. nospy(+Pred)
  3419.     Remove spy point from all predicates meeting the predicate
  3420.     specification Pred.
  3421.  
  3422.  
  3423. nospyall
  3424.     Remove all spy points from the entire program.
  3425.  
  3426.  
  3427. leash(?Ports)
  3428.     Set/query leashing (ports which allow for user interaction).  Ports
  3429.     is one of +Name, -Name, ?Name or a list of these.  +Nameenables
  3430.     leashing on that port, -Name disables it and ?Name succeeds or fails
  3431.     according to the current setting.  Recognised ports are:  call, redo,
  3432.     exit, fail and unify.  The special shorthand all refers to all ports,
  3433.     fullrefers to all ports except for the unify port (default).  half
  3434.     refers to the call, redo and fail port.
  3435.  
  3436.  
  3437. visible(+Ports)
  3438.     Set the ports shown by the debugger.  See leash/1 for a description
  3439.     of the port specification.  Default is full.
  3440.  
  3441.  
  3442. unknown(-Old, +New)
  3443.     Unify Old with the current value of the unknown system flag.  On
  3444.     success New will be used to specify the new value.  New should be
  3445.     instantiated to either fail or trace and determines the interpreter's
  3446.     action when an undefined predicate which is not declared dynamic is
  3447.     encountered (see dynamic/1).  fail implies the predicate just fails
  3448.     silently.  traceimplies the tracer is started.  Default is trace.
  3449.     The unknown flag is local to each module and unknown/2 is module
  3450.     transparent.  Using it as a directive in a module file will only
  3451.     change the unknown flag for that module.  Using the :/2 construct the
  3452.     behaviour on trapping an undefined predicate can be changed for any
  3453.     module.  Note that if the unknown flag for a module equals fail the
  3454.     system will not call exception/3 and will not try to resolve the
  3455.     predicate via the dynamic library system.  The system will still try
  3456.     to import the predicate from the public module.
  3457.  
  3458.  
  3459. style_check(+Spec)
  3460.     Set style checking options.  Spec is either +<option>, -<option>,
  3461.     ?<option> or a list of such options.  +<option> sets a style checking
  3462.     option, -<option> clears it and ?<option> succeeds or fails according
  3463.     to the current setting.  consult/1 and derivates resets the style
  3464.     checking options to their value before loading the file.  If --for
  3465.     example-- a file containing long atoms should be loaded the user can
  3466.     start the file with:
  3467.  
  3468.         :- style_check(-atom).
  3469.  
  3470.     Currently available options are:
  3471.  
  3472.       Name           Default   Description
  3473.  
  3474.       singleton        on      read_clause/1 (used by consult/1) warns on
  3475.                                variables only appearing once in a term
  3476.                                (clause) which have a name not starting with
  3477.                                an underscore.
  3478.       atom             on      read/1 and derivates will produce an error
  3479.                                message on quoted atoms or strings longer
  3480.                                than 5 lines.
  3481.       dollar           off     Accept dollar as a lower case character,
  3482.                                thus avoiding the need for quoting atoms
  3483.                                with dollar signs.  System maintenance use
  3484.                                only.
  3485.  
  3486.       discontiguous    on      Warn if the clauses for a predicate are not
  3487.                                together in the same source file.
  3488.  
  3489.       string           off     Read and derivates transform "..." into a
  3490.                                prolog string instead of a list of ASCII
  3491.                                characters.
  3492.  
  3493.  
  3494. 3.35 Obtaining Runtime Statistics
  3495.  
  3496.  
  3497. statistics(+Key, -Value)
  3498.     Unify system statistics determined by Key with Value.  The possible
  3499.     keys are given in the table 3.2.
  3500.  
  3501.     cputime      (User) cpu time since Prolog was started in
  3502.                  seconds
  3503.     inferences   Total number of passes via the call and redo ports
  3504.                  since Prolog was started.
  3505.  
  3506.     heapused     Bytes heap in use.
  3507.  
  3508.     local        Allocated size of the local stack in bytes.
  3509.  
  3510.     localused    Number of bytes in use on the local stack.
  3511.  
  3512.     locallimit   Size to which the local stack is allowed to grow
  3513.  
  3514.     global       Allocated size of the global stack in bytes.
  3515.  
  3516.     globalused   Number of bytes in use on the global stack.
  3517.  
  3518.     globallimit  Size to which the global stack is allowed to grow
  3519.  
  3520.     trail        Allocated size of the trail stack in bytes.
  3521.  
  3522.     trailused    Number of bytes in use on the trail stack.
  3523.  
  3524.     traillimit   Size to which the trail stack is allowed to grow
  3525.  
  3526.     atoms        Total number of defined atoms.
  3527.     functors     Total number of defined name/arity pairs.
  3528.  
  3529.     predicates   Total number of predicate definitions.
  3530.  
  3531.     modules      Total number of module definitions.
  3532.     externals    Total number of external references in all
  3533.                  clauses.
  3534.     codes        Total amount of byte codes in all clauses.
  3535.  
  3536.                   Table 3.2:  Keys for statistics/2
  3537.  
  3538.  
  3539. statistics
  3540.     Display a table of system statistics on the current output stream.
  3541.  
  3542.  
  3543. time(+Goal)
  3544.     Execute Goal just like once/1 (i.e.  leaving no choice points), but
  3545.     print used time, number of logical inferences and the average number
  3546.     of lips (logical inferences per second).  Note that SWI-Prolog counts
  3547.     the actual executed number of inferences rather than the number of
  3548.     passes through the call- and redo ports of the theoretical 4-port
  3549.     model.
  3550.  
  3551.  
  3552. 3.36 Finding Performance Bottlenecks
  3553.  
  3554. SWI-Prolog offers a statistical program profiler similar to Unix prof(1)
  3555. for C and some other languages.  A profiler is used as an aid to find
  3556. performance pigs in programs.  It provides information on the time spent
  3557. in the various Prolog predicates.
  3558.  
  3559. The profiler is based on the assumption that if we monitor the functions
  3560. on the execution stack on time intervals not correlated to the program's
  3561. execution the number of times we find a procedure on the environment stack
  3562. is a measure of the time spent in this procedure.  It is implemented by
  3563. calling a procedure each time slice Prolog is active.  This procedure
  3564. scans the local stack and either just counts the procedure on top of this
  3565. stack (plain profiling) or all procedures on the stack (cummulative
  3566. profiling).  To get accurate results each procedure one is interested in
  3567. should have a reasonable number of counts.  Typically a minute runtime
  3568. will suffice to get a rough overview of the most expensive procedures.
  3569.  
  3570.  
  3571. profile(+Goal, +Style, +Number)
  3572.     Execute Goal just like time/1.  Collect profiling statistics
  3573.     according to style (see profiler/2) and show the top Number
  3574.     procedures on the current output stream (see show_profile/1).  The
  3575.     results are kept in the database until reset_profiler/0 or profile/3
  3576.     is called and can be displayed again with show_profile/1.  profile/3
  3577.     is the normal way to invoke the profiler.  The predicates below are
  3578.     low-level predicates that can be used for special cases.
  3579.  
  3580.  
  3581. show_profile(+Number)
  3582.     Show the collected results of the profiler.  Stops the profiler first
  3583.     to avoid interference from show_profile/1.  It shows the top Number
  3584.     predicates according the percentage cpu-time used.
  3585.  
  3586.  
  3587. profiler(-Old, +New)
  3588.     Query or change the status of the profiler.  The status is one of
  3589.     off, plain or cummulative.  plainimplies the time used by childs of
  3590.     a predicate is not added to the time of the predicate.  For status
  3591.     cummulativethe time of childs is added (except for recursive calls).
  3592.     Cummulative profiling implies the stack is scanned upto the top on
  3593.     each time slice to find all active predicates.  This implies the
  3594.     overhead grows with the number of active frames on the stack.
  3595.     Cummulative profiling starts debuggin mode to disable tail recursion
  3596.     optimisation, which would otherwise remove the necessary parent
  3597.     environments.  Switching status from plain to cummulativeresets the
  3598.     profiler.  Switching to and from status off does not reset the
  3599.     collected statistics, thus allowing to suspend profiling for certain
  3600.     parts of the program.
  3601.  
  3602.  
  3603. reset_profiler
  3604.     Swiches the profiler to off and clears all collected statistics.
  3605.  
  3606.  
  3607. profile_count(+Head, -Calls, -Promilage)
  3608.     Obtain profile statistics of the predicate specified by Head.  Head
  3609.     is an atom for predicates with arity 0 or a term with the same name
  3610.     and arity as the predicate required (see current_predicate/2).  Calls
  3611.     is unified with the number of `calls' and `redos' while the profiler
  3612.     was active.  Promilage is unified with the relative number of counts
  3613.     the predicate was active (cummulative) or on top of the stack
  3614.     (plain).  Promilage is an integer between 0 and 1000.
  3615.  
  3616.  
  3617. 3.37 Memory Management
  3618.  
  3619. Note:  limit_stack/2 and trim_stacks/0 have no effect on machines that do
  3620. not offer dynamic stack expansion.  On these machines these predicates
  3621. simply succeed to improve portability.
  3622.  
  3623.  
  3624. garbage_collect
  3625.     Invoke the global- and trail stack garbage collector.  Normally the
  3626.     garbage collector is invoked automatically if necessary.  Explicit
  3627.     invokation might be useful to reduce the need for garbage collections
  3628.     in time critical segments of the code.  After the garbage collection
  3629.     trim_stacks/0 is invoked to release the collected memory resources.
  3630.  
  3631.  
  3632. limit_stack(+Key, +Kbytes)
  3633.     Limit one of the stack areas to the specified value.  Key is one of
  3634.     local, globalor trail.  The limit is an integer, expressing the
  3635.     desired stack limit in K bytes.  If the desired limit is smaller than
  3636.     the currently used value, the limit is set to the nearest legal value
  3637.     above the currently used value.  If the desired value is larger than
  3638.     the maximum, the maximum is taken.  Finally, if the desired value is
  3639.     either 0 or the atom unlimitedthe limit is set to its maximum.  The
  3640.     maximum and initial limit is determined by the command line options
  3641.     -L, -G and -T.
  3642.  
  3643.  
  3644. trim_stacks
  3645.     Release stack memory resources that are not in use at this moment,
  3646.     returning them to the operating system.  Trim stack is a relatively
  3647.     cheap call.  It can be used to release memory resources in a
  3648.     backtracking loop, where the iterations require typically seconds of
  3649.     execution time and very different, potentionally large, amounts of
  3650.     stack space.  Such a loop should be written as follows:
  3651.  
  3652.         loop :-
  3653.                generator,
  3654.                    trim_stacks,
  3655.                    potentionally_expensive_operation,
  3656.                stop_condition, !.
  3657.  
  3658.     The prolog top level loop is written this way, reclaiming memory
  3659.     resources after every user query.
  3660.  
  3661.  
  3662. 3.38 Miscellaneous
  3663.  
  3664.  
  3665. dwim_match(+Atom1, +Atom2)
  3666.     Succeeds if Atom1 matches Atom2 in `Do What I Mean' sence.  Both
  3667.     Atom1 and Atom2 may also be integers or floats.  The two atoms match
  3668.     if:
  3669.  
  3670.         They are identical
  3671.  
  3672.         They differ by one character (spy == spu)
  3673.  
  3674.         One character is insterted/deleted (debug == deug)
  3675.  
  3676.         Two characters are transposed (trace == tarce)
  3677.  
  3678.         `Sub-words' are glued differently (existsfile == existsFile ==
  3679.         exists_file)
  3680.  
  3681.         Two adjacent sub words are transposed (existsFile == fileExists)
  3682.  
  3683.  
  3684. dwim_match(+Atom1, +Atom2, -Difference)
  3685.     Equivalent to dwim_match/2, but unifies Difference with an atom
  3686.     identifying the the difference between Atom1 and Atom2.  The return
  3687.     values are (in the same order as above):  equal, mismatched_char,
  3688.     inserted_char, transposed_char, separatedand transposed_word.
  3689.  
  3690.  
  3691. wildcard_match(+Pattern, +String)
  3692.     Succeeds if String matches the wildcart pattern Pattern.  Pattern is
  3693.     very simular the the Unix csh pattern matcher.  The patterns are
  3694.     given below:
  3695.  
  3696.       ?       Matches one arbitrary character
  3697.       *       Matches any number of arbitrary characters
  3698.       [...]   Matches one of the characters specified at ... <char>-<char> indi*
  3699.  *cates a range.
  3700.       f...g   Matches any of the patterns of the comma separated list between t*
  3701.  *he brackets.
  3702.  
  3703.     Example:
  3704.  
  3705.         ?- wildcard_match('[a-z]*.{pro,pl}[%~]', 'a_hello.pl%').
  3706.  
  3707.         Yes.
  3708.  
  3709.  
  3710. gensym(+Base, -Unique)
  3711.     Generate a unique atom from base Base and unify it with Unique.  Base
  3712.     should be an atom.  The first call will return <base>1, the next
  3713.     <base>2, etc.  Note that this is no warant that the atom is unique in
  3714.     the system.
  3715.  
  3716.     BUG: I plan to supply a real gensym/2 which does give this warrant
  3717.     for future versions.
  3718.  
  3719.  
  3720. sleep(+Time)
  3721.     Suspend execution Time seconds.  Time is either a floating point
  3722.     number or an integer.  Granularity is dependent on the system's timer
  3723.     granularity (1/60 seconds on most Unix systems).  A negative time
  3724.     causes the timer to return immediately.  As Unix is a multi-tasking
  3725.     environment we can only ensure execution is suspended for at least
  3726.     Time seconds.
  3727.  
  3728.  
  3729. Chapter  4
  3730.  
  3731. Using  Modules
  3732.  
  3733.                                 384
  3734.  
  3735.  
  3736. 4.1 Why Using Modules?
  3737.  
  3738. In traditional Prolog systems the predicate space was flat.  This approach
  3739. is not very suitable for the development of large applications, certainly
  3740. not if these applications are developed by more than one programmer.  In
  3741. many cases, the definition of a Prolog predicate requires sub-predicates
  3742. that are intented only to complete the definition of the main predicate.
  3743. With a flat and global predicate space these support predicates will be
  3744. visible from the entire program.
  3745.  
  3746. For this reason, it is desirable that each source module has it's own
  3747. predicate space.  A module consists of a declaration for it's name, it's
  3748. public predicates and the predicates themselves.  This approach allow the
  3749. programmer to use short (local) names for support predicates without
  3750. worrying about name conflicts with the support predicates of other
  3751. modules.  The module declaration also makes explicit which predicates are
  3752. meant for public usage and which for private purposes.  Finally, using the
  3753. module information, cross reference programs can indicate possible
  3754. problems much better.
  3755.  
  3756.  
  3757. 4.2 Name-based versus Predicate-based Modules
  3758.  
  3759. Two approaches to realise a module system are commonly used in Prolog and
  3760. other languages.  The first one is the name based module system.  In these
  3761. systems, each atom read is tagged (normally prefixed) with the module
  3762. name, with the exception of those atoms that are defined public.  In the
  3763. second approach, each module actually implements its own predicate space.
  3764.  
  3765. A critical problem with using modules in Prolog is introduced by the
  3766. meta-predicates that transform between Prolog data and Prolog predicates.
  3767. Consider the case where we write:
  3768.  
  3769.     :- module(extend, [add_extension/3]).
  3770.  
  3771.     add_extension(Extension, Plain, Extended) :-
  3772.            maplist(extend_atom(Extension), Plain, Extended).
  3773.  
  3774.     extend_atom(Extension, Plain, Extended) :-
  3775.            concat(Plain, Extension, Extended).
  3776.  
  3777. In this case we would like maplist to call extend_atom/3 in the module
  3778. extend.  A name based module system will do this correctly.  It will tag
  3779. the atom extend_atom with the module and maplist will use this to
  3780. construct the tagged term extend_atom/3.  A name based module however,
  3781. will not only tag the atoms that will eventually be used to refer to a
  3782. predicate, but all atoms that are not declared public.  So, with a name
  3783. based module system also data is local to the module.  This introduces
  3784. another serious problem:
  3785.  
  3786.     :- module(action, [action/3]).
  3787.  
  3788.     action(Object, sleep, Arg) :- ....
  3789.     action(Object, awake, Arg) :- ....
  3790.  
  3791.     :- module(process, [awake_process/2]).
  3792.  
  3793.     awake_process(Process, Arg) :-
  3794.            action(Process, awake, Arg).
  3795.  
  3796. This code uses a simple object-oriented implementation technique were
  3797. atoms are used as method selectors.  Using a name based module system,
  3798. this code will not work, unless we declare the selectors puclic atoms in
  3799. all modules that use them.  Predicate based module systems do not require
  3800. particular precautions for handling this case.
  3801.  
  3802. It appears we have to choose either to have local data, or to have trouble
  3803. with meta-predicates.  Probably it is best to choose for the predicate
  3804. based approach as novice users will not often write generic
  3805. meta-predicates that have to be used across multiple modules, but are
  3806. likely to write programs that pass data around across modules.
  3807. Experienced Prolog programmers should be able to deal with the
  3808. complexities of meta-predicates in a predicate based module system.
  3809.  
  3810.  
  3811. 4.3 Defining a Module
  3812.  
  3813. Modules normally are created by loading a module file.  A module file is a
  3814. file holding a module/2 directive as its first term.  The module/2
  3815. directive declares the name and the public (i.e. externally visible)
  3816. predicates of the module.  The rest of the file is loaded into the module.
  3817. Below is an example of a module file, defining reverse/2.
  3818.  
  3819.     :- module(reverse, [reverse/2]).
  3820.  
  3821.     reverse(List1, List2) :-
  3822.            rev(List1, [], List2).
  3823.  
  3824.     rev([], List, List).
  3825.     rev([Head|List1], List2, List3) :-
  3826.            rev(List1, [Head|List2], List3).
  3827.  
  3828.  
  3829. 4.4 Importing Predicates into a Module
  3830.  
  3831. As explained before, in the predicate based approach ad<apted by
  3832. SWI-Prolog, each module has it's own predicate space.  In SWI-Prolog, a
  3833. module initially is completely empty.  Predicates can be added to a module
  3834. by loading a module file as demonstrated in the previous section, using
  3835. assert or by importing them from another module.
  3836.  
  3837. Two mechanisms for importing predicates explicitely from another module
  3838. exist.  The use_module/[1,2] predicates load a module file and import
  3839. (part of the) public predicates of the file.  The import/1 predicate
  3840. imports any predicate from any module.
  3841.  
  3842.  
  3843. use_module(+File)
  3844.     Load the file(s) specified with File just like ensure_loaded/1.  The
  3845.     files should all be module files.  All exported predicates from the
  3846.     loaded files are imported into the context module.  The difference
  3847.     between this predicate and ensure_loaded/1 becomes apparent if the
  3848.     file is already loaded into another module.  In this case
  3849.     ensure_loaded/1 does nothing; use_module will import all public
  3850.     predicates of the module into the current context module.
  3851.  
  3852.  
  3853. use_module(+File, +ImportList)
  3854.     Load the file specified with File (only one file is accepted).  File
  3855.     should be a module file.  ImportList is a list of name/arity pairs
  3856.     specifying the predicates that should be imported from the loaded
  3857.     module.  If a predicate is specified that is not exported from the
  3858.     loaded module a warning will be printed.  The predicate will
  3859.     nevertheless be imported to simplify debugging.
  3860.  
  3861.  
  3862. import(+Head)
  3863.     Import predicate Head into the current context module.  Head should
  3864.     specify the source module using the <module>:<term> construct.
  3865.     Note that predicates are normally imported using one of the
  3866.     directives use_module/[1,2].  import/1 is meant for handling imports
  3867.     into dynamically created modules.
  3868.  
  3869.  
  3870. It would be rather inconvient to have to import each predicate refered to
  3871. by the module, including the system predicates.  For this reason each
  3872. module is assigned a default module.  All predicates in the default module
  3873. are available without extra declarations.  Their definition however can be
  3874. overruled in the local module.  This schedule is implemented by the
  3875. exception handling mechanism of SWI-Prolog:  if an undefined predicate
  3876. exception is raised for a predicate in some module, the exception handler
  3877. first tries to import the predicate from the module's default module.  On
  3878. success, normal execution is resumed.
  3879.  
  3880.  
  3881. 4.4.1 Reserved Modules
  3882.  
  3883. SWI-Prolog contains two special modules.  The first one is the module
  3884. system.  This module contains all built-in predicates described in this
  3885. manual.  Module system has no default module assigned to it.  The second
  3886. special module is the module user.  This module forms the initial working
  3887. space of the user.  Initially it is empty.  The default module of module
  3888. user is system, making all built-in predicate definitions available as
  3889. defaults.  Built-in predicates thus can be overruled by defining them in
  3890. module user before they are used.
  3891.  
  3892. All other modules default to module user.  This implies they can use all
  3893. predicates imported into user without explicitely importing them.
  3894.  
  3895.  
  3896. 4.5 Using the Module System
  3897.  
  3898. The current structure of the module system has been designed with some
  3899. specific organisations for large programs in mind.  Many large programs
  3900. define a basic library layer on top of which the actual program itself is
  3901. defined.  The module user, acting as the default module for all other
  3902. modules of the program can be used to distribute these definitions over
  3903. all program module without introducing the need to import this common
  3904. layer each time explicitely.  It can also be used to redefine built-in
  3905. predicates if this is required to maintain compatibility to some other
  3906. Prolog implementation.  Typically, the loadfile of a large application
  3907. looks like this:
  3908.  
  3909.     :- use_module(compatibility).   % load XYZ prolog compatibility
  3910.  
  3911.     :- use_module(                % load generic parts
  3912.            [ error                % errors and warnings
  3913.            , goodies              % general goodies (library
  3914.     extensions)
  3915.            , debug                % application specific debugging
  3916.            , virtual_machine       % virtual machine of application
  3917.            , ...                 % more generic stuff
  3918.            ]).
  3919.  
  3920.     :- ensure_loaded(
  3921.            [ ...                 % the application itself
  3922.            ]).
  3923.  
  3924. The `use_module' declarations will import the public predicates from the
  3925. generic modules into the user module.  The `ensure_loaded' directive loads
  3926. the modules that constitute the actual application.  It is assumed these
  3927. modules import predicates from each other using use_module/[1,2] as far as
  3928. necessary.
  3929.  
  3930. In combination with the object-oriented schema described below it is
  3931. possible to define a neat modular architecture.  The generic code defines
  3932. general utilities and the message passing predicates (invoke/3 in the
  3933. example below).  The application modules define classes that communicate
  3934. using the message passint predicates.
  3935.  
  3936.  
  3937. 4.5.1 Object Oriented Programming
  3938.  
  3939. Another typical way to use the module system is for defining classes
  3940. within an object oriented paradigm.  The class structure and the methods
  3941. of a class can be defined in a module and the explicit module-boundary
  3942. overruling describes in section ??  can by used by the message passing
  3943. code to invoke the behaviour.  An outline of this mechanism is given
  3944. below.
  3945.  
  3946.     %       Define class point
  3947.  
  3948.     :- module(point, []).          % class point, no exports
  3949.  
  3950.     %       name          type,          default access
  3951.     %                                   value
  3952.  
  3953.     variable(x,            integer,       0,      both).
  3954.     variable(y,            integer,       0,      both).
  3955.  
  3956.     %        method name   predicate name  arguments
  3957.  
  3958.     behaviour(mirror,       mirror,        []).
  3959.  
  3960.     mirror(P) :-
  3961.            fetch(P, x, X),
  3962.            fetch(P, y, Y),
  3963.            store(P, y, X),
  3964.            store(P, x, Y).
  3965.  
  3966. The predicates fetch/3 and store/3 are predicates that change instance
  3967. variables of instances.  The figure below indicates how message passing
  3968. can easily be implemented:
  3969.  
  3970.     %       invoke(+Instance, +Selector, ?ArgumentList)
  3971.     %       send a message to an instance
  3972.  
  3973.     invoke(I, S, Args) :-
  3974.            class_of_instance(I, Class),
  3975.            Class:behaviour(S, P, ArgCheck), !,
  3976.            convert_arguments(ArgCheck, Args, ConvArgs),
  3977.            Goal =.. [P|ConvArgs],
  3978.            Class:Goal.
  3979.  
  3980. The construct `Module:Goal' explicitely calls Goal in module Module.  It
  3981. is discussed in more detail in section ??.
  3982.  
  3983.  
  3984. 4.6 Meta-Predicates in Modules
  3985.  
  3986. As indicated in the introduction, the problem with a predicate based
  3987. module system lies in the difficulty to find the correct predicate from a
  3988. Prolog term.  The predicate `solution(Solution)' can exist in more than
  3989. one module, but `assert(solution(4))' in some module is supposed to refer
  3990. to the correct version of solution/1.
  3991.  
  3992. Various approaches are possible to solve this problem.  One is to add an
  3993. extra argument to all predicates (e.g. `assert(Module, Term)').  Another
  3994. is to tag the term somehow to indicate which module is desired (e.g.
  3995. `assert(Module:Term)').  Both approaches are not very attractive as they
  3996. make the user responsible for chosing the correct module, inviting unclear
  3997. programming by asserting in other modules.  The predicate assert/1 is
  3998. supposed to assert in the module it is called from and should do so
  3999. without being told explicitely.  For this reason, the notion context
  4000. module has been introduced.
  4001.  
  4002.  
  4003. 4.6.1 Definition and Context Module
  4004.  
  4005. Each predicate of the program is assigned a module, called it's definition
  4006. module.  The definition module of a predicate is always the module in
  4007. which the predicate was originally defined.  Each active goal in the
  4008. Prolog system has a context module assigned to it.
  4009.  
  4010. The context module is used to find predicates from a Prolog term.  By
  4011. default, this module is the definition module of the predicate running the
  4012. goal.  For meta-predicates however, this is the context module of the goal
  4013. that invoked them.  We call this module_transparent in SWI-Prolog.  In the
  4014. `using maplist' example above, the predicate maplist/3 is declared
  4015. module_transparent.  This implies the context module remains extend, the
  4016. context module of add_extension/3.  This way maplist/3 can decide to call
  4017. extend_atom in module extend rather than in it's own definition module.
  4018.  
  4019. All built-in predicates that refer to predicates via a Prolog term are
  4020. declared module_transparent.  Below is the code defining maplist.
  4021.  
  4022.     :- module(maplist, maplist/3).
  4023.  
  4024.     :- module_transparent maplist/3.
  4025.  
  4026.     %       maplist(+Goal, +List1, ?List2)
  4027.     %       True if Goal can succesfully be applied to all succesive
  4028.     pairs
  4029.     %       of elements of List1 and List2.
  4030.  
  4031.     maplist(_, [], []).
  4032.     maplist(Goal, [Elem1|Tail1], [Elem2|Tail2]) :-
  4033.            apply(Goal, [Elem1, Elem2]),
  4034.            maplist(Goal, Tail1, Tail2).
  4035.  
  4036.  
  4037. 4.6.2 Overruling Module Boundaries
  4038.  
  4039. The mechanism above is sufficient to create an acceptable module system.
  4040. There are however cases in which we would like to be able to overrule this
  4041. schema and explicitely call a predicate in some module or assert
  4042. explicitly in some module.  The first is useful to invoke goals in some
  4043. module from the user's toplevel or to implement a object-oriented system
  4044. (see above).  The latter is useful to create and modify dynamic modules
  4045. (see section 4.7).
  4046.  
  4047. For this purpose, the reserved term :/2 has been introduced.  All built-in
  4048. predicates that transform a term into a predicate reference will check
  4049. whether this term is of the form `<Module>:<Term>'.  If so, the
  4050. predicate is searched for in Module instead of the goal's context module.
  4051. The :/2 operator may be nested, in which case the inner-most module is
  4052. used.
  4053.  
  4054. The special calling construct <Module>:<Goal> pretends Goal is called
  4055. from Module instead of the context module.  Examples:
  4056.  
  4057.     ?- assert(world:done).  % asserts done/0 into module world
  4058.     ?- world:assert(done).  % the same
  4059.     ?- world:done.         % calls done/0 in module world
  4060.  
  4061.  
  4062. 4.7 Dynamic Modules
  4063.  
  4064. Sofar, we discussed modules that were created by loading a module-file.
  4065. These modules have been introduced on facilitate the development of large
  4066. applications.  The modules are fully defined at load-time of the
  4067. application and normally will not change during execution.  Having the
  4068. notion of a set of predicates as a self-contained world can be attractive
  4069. for other purposes as well.  For example, assume an application that can
  4070. reason about multiple worlds.  It is attractive to store the data of a
  4071. particular world in a module, so we extract information from a world
  4072. simply by invoking goals in this world.
  4073.  
  4074. Dynamic modules can easily be created.  Any built-in predicate that tries
  4075. to locate a predicate in a specific module will create this module as a
  4076. side-effect if it did not yet exist.  Example:
  4077.  
  4078.     ?- assert(world_1, consistent),
  4079.        world_1:unkown(_, fail).
  4080.  
  4081. These calls create a module called world and make the call
  4082. `world:consistent' succeed.  Undefined predicates will not start the
  4083. tracer or autoloader for this module (see unknown/2).
  4084.  
  4085. Import and export from dynamically created world is arranged via the
  4086. predicates import/1 and export/1:
  4087.  
  4088.     ?- world_5:export(solve(_,_)).         % exports solve/2 from
  4089.     world_5
  4090.     ?- world_3:import(world_5:solve(_,_)).  % and import it to world_3
  4091.  
  4092.  
  4093. 4.8 Module Handling Predicates
  4094.  
  4095. This section gives the predicate definitions for the remaining built-in
  4096. predicates that handle modules.
  4097.  
  4098.  
  4099. :- module(+Module, +PublicList)
  4100.     This directive can only be used as the first term of a source file.
  4101.     It declares the file to be a module file, defining Module and
  4102.     exporting the predicates of PublicList.  PublicList is a list of
  4103.     name/arity pairs.
  4104.  
  4105.  
  4106. module_transparent +Name/+Arity, ...
  4107.     Preds is a comma separated list of name/arity pairs (like dynamic/1).
  4108.     Each goal associated with a transparent declared predicate will
  4109.     inherit the context module from its parent goal.
  4110.  
  4111.  
  4112. context_module(-Module)
  4113.     Unify Module with the context module of the current goal.
  4114.     context_module/1 itself is transparent.
  4115.  
  4116.  
  4117. export(+Head)
  4118.     Add a predicate to the public list of the context module.  This
  4119.     implies the predicate will be imported into another module if this
  4120.     module is imported with use_module/[1,2].  Note that predicates are
  4121.     normally exported using the directive module/2.  export/1 is meant to
  4122.     handle export from dynamically created modules.
  4123.  
  4124.  
  4125. 4.9 Compatibility of the Module System
  4126.  
  4127. The principles behind the module system of SWI-Prolog differ in a number
  4128. of aspects from the Quintus Prolog module system.
  4129.  
  4130.     The SWI-Prolog module system allows the user to redefine system
  4131.     predicates.
  4132.  
  4133.     All predicates that are available in the system and user modules are
  4134.     visible in all other modules as well.
  4135.  
  4136.     Quintus has the `meta_predicate/1' declaration were SWI-Prolog has
  4137.     the module_transparent/1 declaration.
  4138.  
  4139. The meta_predicate/1 declaration causes the compiler to tag arguments that
  4140. pass module sensitive information with the module using the :/2 operator.
  4141. This approach has some disadvantages:
  4142.  
  4143.     Changing a meta_predicate declaration implies all predicates calling
  4144.     the predicate need to be reloaded.  This can cause serious
  4145.     consistency problems.
  4146.  
  4147.     It does not help for dynamically defined predicates calling module
  4148.     sensitive predicates.
  4149.  
  4150.     It slows down the compiler (at least in the SWI-Prolog architecture).
  4151.  
  4152.     At least within the SWI-Prolog architecture the run-time overhead is
  4153.     larger than the overhead introduced by the transparent mechanism.
  4154.  
  4155. Unfortunately the transparent predicate approach also has some
  4156. disadvantages.  If a predicate A passes module sensitive information to a
  4157. predicate B, passing the same information to a module sensitive system
  4158. predicate both A and B should be declared transparent.  Using the Quintus
  4159. approach only A needs to be treated special (i.e.  declared with
  4160. meta_predicate/1).  A second problem arises if the body of a transparent
  4161. predicate uses module sensitive predicates for which it wants to refer to
  4162. its own module.  Suppose we want to define findall/3 using assert/1 and
  4163. retract/1.  The example in figure 4.1 gives the solution.
  4164.  
  4165.     :- module(findall, [findall/3]).
  4166.  
  4167.     :- dynamic
  4168.            solution/1.
  4169.  
  4170.     :- module_transparent
  4171.            findall/3,
  4172.            store/2.
  4173.  
  4174.     findall(Var, Goal, Bag) :-
  4175.            assert(findall:solution('$mark')),
  4176.            store(Var, Goal),
  4177.            collect(Bag).
  4178.  
  4179.     store(Var, Goal) :-
  4180.            Goal,                 % refers to context module of
  4181.                                  % caller of findall/3
  4182.            assert(findall:solution(Var)),
  4183.            fail.
  4184.     store(_, _).
  4185.  
  4186.     collect(Bag) :-
  4187.            ...,
  4188.  
  4189.                   Figure 4.1:  Findall using modules
  4190.  
  4191. The Quintus meta_predicate/1 directive can in many cases be replaced by
  4192. the transparent declaration.  Figure 4.2 gives a definition of
  4193. meta_predicate/1 as available from the `quintus' library package.
  4194.  
  4195.     :- op(1150, fx, (meta_predicate)).
  4196.  
  4197.     meta_predicate((Head, More)) :- !,
  4198.            meta_predicate1(Head),
  4199.            meta_predicate(More).
  4200.     meta_predicate(Head) :-
  4201.            meta_predicate1(Head).
  4202.  
  4203.     meta_predicate1(Head) :-
  4204.            Head =.. [Name|Arguments],
  4205.            member(Arg, Arguments),
  4206.            module_expansion_argument(Arg), !,
  4207.            functor(Head, Name, Arity),
  4208.            module_transparent(Name/Arity).
  4209.     meta_predicate1(_).            % just a mode declaration
  4210.  
  4211.     module_expansion_argument(:).
  4212.     module_expansion_argument(N) :- integer(N).
  4213.  
  4214.               Figure 4.2:  Definition of meta_predicate/1
  4215.  
  4216. The discussion above about the problems with the transparent mechanism
  4217. show the two cases in which this simple transformation does not work.
  4218.  
  4219.  
  4220. Chapter  5
  4221.  
  4222. Foreign  Language  Interface
  4223.  
  4224. SWI-Prolog offers a powerful interface to C . The main design objectives
  4225. of the foreign language interface are flexibility and performance.  Most
  4226. Prolog foreign language interfaces allow the user only to pass primitive
  4227. data via the interface.  The user should normally specify for each
  4228. argument whether it is an input or output argument as well as the type of
  4229. the argument.  Because type checking and conversion to/from C data types
  4230. is done by Prolog the actual foreign code is usually short if something
  4231. simple is wanted.  The SWI-Prolog interface does not offer these
  4232. primitives.  Instead Prolog terms in their internal representation are
  4233. passed via the interface.  This allows the user to write `logical'
  4234. predicates and pass arbitrary Prolog data over the interface.  As a
  4235. trade-off the user is responsible for type checking and should be careful
  4236. not to violate consistency rules as Prolog provides access to its internal
  4237. data structures.
  4238.  
  4239.                                 406
  4240.  
  4241.  
  4242. 5.1 Portability of the Foreign Interface
  4243.  
  4244. The foreign language interface is highly system dependent.  It can easily
  4245. be ported to machines for which the C linker allows you to link an object
  4246. file using the symbol table of a (running) executable and use BSD Unix
  4247. format a.out files.  On many Unix systems such an object file can be
  4248. created using the -A option of ld(1).  See the introduction section for a
  4249. list of systems to which the foreign interface is available.
  4250.  
  4251.  
  4252. 5.2 Overview of the Interface
  4253.  
  4254. A special include file called ``SWI-prolog.h'' should be included with
  4255. each C-source file that is to be loaded via the foreign interface.  This
  4256. C-header file defines various data types, macros and functions that can be
  4257. used to communicate with SWI-Prolog.  Functions and macros can be divided
  4258. into the following categories:
  4259.  
  4260.     Analysing arbitrary Prolog terms
  4261.  
  4262.     Constructing new terms or instantiating existing ones
  4263.  
  4264.     Returning control information to Prolog
  4265.  
  4266.     Registering foreign predicates with Prolog
  4267.  
  4268.     Calling Prolog from C
  4269.  
  4270.     Communicating about modules
  4271.  
  4272.     Printing standard Prolog warning/error messages
  4273.  
  4274.     Global actions on Prolog (halt, break, abort, etc.)
  4275.  
  4276.     Querying the status of Prolog
  4277.  
  4278. A C-file to be included normally defines a number of functions that
  4279. implement foreign language Prolog predicates, private support functions
  4280. and an installation function.  The user should compile this file into a
  4281. `.o' file using `cc -c file ...', after which Prolog can be asked to load
  4282. the file using the simplified load_foreign/2 predicate or the more
  4283. flexible load_foreign/5 predicate.  Prolog will call the Unix loader ld(1)
  4284. to create an executable.  It will then determine the actual size of the
  4285. executable, allocate memory for it and call the loader again to create an
  4286. executable that can be loaded in the allocated memory.  After the
  4287. executable is loaded the entry point of the new executable is called.
  4288. This function should register all defined foreign predicates with Prolog.
  4289.  
  4290.  
  4291. 5.3 Loading Foreign Modules
  4292.  
  4293.  
  4294. load_foreign(+File, +Entry)
  4295.     Load a foreign file or list of files specified by File.  The files
  4296.     are searched for similar to consult/1.  Except that the `.o'
  4297.     extension is used rather than `.pl'.  Thus `test' is a valid
  4298.     specification for `test.o' in the current directory,
  4299.     `[test, library(basics)]' specifies `test.o' in the current directory
  4300.     and `basics.o' in one of the library directories.  To simplify
  4301.     maintenance of packages in heterogeneous networks the system first
  4302.     tries whether the object file is available from a subdirectory whose
  4303.     name depends on the system used.  The names of the subdirectories is
  4304.     shown below.
  4305.  
  4306.                   Directory   Machine
  4307.                   sun4        Sparc Station 1 and SUN-4
  4308.                   sun3        SUN-3
  4309.                   hpux        HP9000 running HPUX
  4310.  
  4311.     Entry defines the entry point of the resulting executable.  The entry
  4312.     point will be called by Prolog to install the foreign predicates.
  4313.  
  4314.  
  4315. load_foreign(+File, +Entry, +Options, +Libraries, +Size)
  4316.     The first two arguments are identical to those of load_foreign/2.
  4317.     Options is (a list of) additional option to be given to the loader.
  4318.     The default command is:
  4319.  
  4320.         ld -N -A <symbolfile> -T <offset> -e <entry> -o <executable>
  4321.           <files> -lc
  4322.  
  4323.     The options are inserted just before the files.  Libraries is (a list
  4324.     of) libraries to be passed to the loader.  They are inserted just
  4325.     after the files.
  4326.  
  4327.     If Size is specified Prolog first assumes that the resulting
  4328.     executable will fit in Size bytes and do the loading in one pass.  If
  4329.     the executable turns out to be larger than Size bytes the loading
  4330.     sequence is started again, using the calculated size.  To determine
  4331.     the size of an executable specify a size that is too small.  Prolog
  4332.     will then print the actual size on the current output stream.
  4333.  
  4334.  
  4335. foreign_file(?File)
  4336.     Is true if File is the absolute path name of a file loaded as foreign
  4337.     file.
  4338.  
  4339.  
  4340. 5.4 Interface Data types
  4341.  
  4342. The interface functions can be divided into two groups.  The first group
  4343. are functions to obtain data from Prolog or pass data to Prolog.  These
  4344. functions use Prolog internal data types.  The second group consists of
  4345. type conversion functions convert between Prolog internal data and C
  4346. primitive types.  Below is a description of the Prolog data types used in
  4347. the interface.
  4348.  
  4349. termTerms represent arbitrary Prolog data (variables, atoms, integers,
  4350.     floats and compound terms).  Terms live either until backtracking
  4351.     takes us back to a point before the term was created or the garbage
  4352.     collector has collected the term.
  4353.  
  4354. atomicAtomics are Prologs primitive data types (integers, atoms and
  4355.     floats).  They can be transformed to C data types (int, char * resp.
  4356.     double).  The Prolog representation for an integer is a tagged
  4357.     version of that integer.  The mapping between C ints and Prolog
  4358.     integers can only be different over different releases of SWI-Prolog.
  4359.     Atoms are represented by a pointer to a data structure on the Prolog
  4360.     heap.  Each such data structure is a unique representation of a
  4361.     string (e.g.  to verify that two atoms represent the same string
  4362.     comparing the atoms suffices).  The mapping between atoms and string
  4363.     are likely to vary over different sessions of Prolog.  Floats are
  4364.     represented as (tagged) pointers to a float living on the global
  4365.     stack.  For their life time the same rules apply as for terms.
  4366.     Whether two floats represent the same number can only be discovered
  4367.     by transforming both to C floats and then comparing them.  Strings
  4368.     are represented as a tagged pointer to a char * on the global stack
  4369.     or heap.  The rules for their lifetime and comparison equal those for
  4370.     floats and terms.
  4371.  
  4372. functorA functor is the internal representation of a name/arity pair.
  4373.     They are used to find the name and arity of a compound term as well
  4374.     as to construct new compound terms.  Like atoms they live for the
  4375.     whole Prolog session and are unique.
  4376.  
  4377. moduleA module is a unique handle to a Prolog module.  Modules are used
  4378.     only to call predicates in a specific module.
  4379.  
  4380.  
  4381. 5.5 The Foreign Include File
  4382.  
  4383.  
  4384. 5.5.1 Argument Passing and Control
  4385.  
  4386. If Prolog encounters a foreign predicate at run time it will call a
  4387. function specified in the predicate definition of the foreign predicate.
  4388. The arguments (1, ..., arity) pass the Prolog arguments to the goal as
  4389. Prolog terms.  Foreign functions should be declared of type foreign_t.
  4390. Deterministic foreign functions have two alternatives to return control
  4391. back to Prolog:
  4392.  
  4393.  
  4394. void PL_succeed
  4395.      Succeed deterministically.  PL_succeed is defined as ``return TRUE''.
  4396.  
  4397.  
  4398. void PL_fail
  4399.      Fail and start Prolog backtracking.  PL_fail is defined as ``return
  4400.      FALSE''.
  4401.  
  4402.  
  4403. 5.5.1.1 Non-deterministic Foreign Predicates
  4404.  
  4405. By default foreign predicates are deterministic.  Using the
  4406. PL_FA_NONDETERMINISTIC attribute (see PL_register_foreign()) it is
  4407. possible to register a predicate as a non-deterministic predicate.
  4408. Writing non-deterministic foreign predicates is slightly more complicated
  4409. as the foreign function needs context information for generating the next
  4410. solution.  Note that the same foreign function should be prepared to be
  4411. simultaneously active in more than one goal.  Suppose the
  4412. natural_number_below_n/2 is a non-deterministic foreign predicate,
  4413. backtracking over all natural numbers lower than the first argument.  Now
  4414. consider the following predicate:
  4415.  
  4416.     quotient_below_n(Q, N) :-
  4417.            natural_number_below_n(N, N1),
  4418.            natural_number_below_n(N, N2),
  4419.            Q =:= N1 / N2, !.
  4420.  
  4421. In this predicate the function natural_number_below_n/2 simultaneously
  4422. generates solutions for both its invocations.
  4423.  
  4424. Non-deterministic foreign functions should be prepared to handle three
  4425. different calls from Prolog:
  4426.  
  4427. Initial call (PL_FIRST_CALL)
  4428.     Prolog has just created a frame for the foreign function and asks it
  4429.     to produce the first answer.
  4430.  
  4431. Redo call (PL_REDO)
  4432.     The previous invocation of the foreign function associated with the
  4433.     current goal indicated it was possible to backtrack.  The foreign
  4434.     function should produce the next solution.
  4435.  
  4436. Terminate call (PL_CUTTED)
  4437.     The choice point left by the foreign function has been destroyed by a
  4438.     cut.  The foreign function is given the opportunity to clean the
  4439.     environment.
  4440.  
  4441. Both the context information and the type of call is provided by an
  4442. argument of type foreign_t appended to the argument list for deterministic
  4443. foreign functions.  The macro PL_foreign_control() extracts the type of
  4444. call from the control argument.  The foreign function can pass a context
  4445. handle using the PL_retry() macro and extract the handle from the extra
  4446. argument using the PL_foreign_context() macro.
  4447.  
  4448.  
  4449. void PL_retry(handle)
  4450.      The foreign function succeeds while leaving a choice point.  On
  4451.      backtracking over this goal the foreign function will be called
  4452.      again, but the control argument now indicates it is a `Redo' call and
  4453.      the macro PL_foreign_context() will return the handle passed via
  4454.      PL_retry().  This handle is a 30 bits signed value (two bits are used
  4455.      for status indication).
  4456.  
  4457.  
  4458. int PL_foreign_control(control_argument)
  4459.     Extracts the type of call from the control argument.  The return
  4460.     values are described above.  Note that the function should be
  4461.     prepared to handle the PL_CUTTED case and should be aware that the
  4462.     other arguments are not valid in this case.
  4463.  
  4464.  
  4465. long PL_foreign_context(control_argument)
  4466.      Extracts the context from the context argument.  In the call type is
  4467.      PL_FIRST_CALL the context value is 0L. Otherwise it is the value
  4468.      returned by the last PL_retry() associated with this goal (both if
  4469.      the call type is PL_REDO as PL_CUTTED).
  4470.  
  4471.  
  4472. Note:  If a non-deterministic foreign function returns using PL_succeed or
  4473. PL_fail, Prolog assumes the foreign function has cleaned its environment.
  4474. No call with control argument PL_CUTTED will follow.
  4475.  
  4476. The code of figure 5.1 shows a skeleton for a non-deterministic foreign
  4477. predicate definition.
  4478.  
  4479.     typedef struct                /* define a context structure */
  4480.     { ...
  4481.     } context;
  4482.  
  4483.     foreign_t
  4484.     my_function(a0, a1, handle)
  4485.     term a0, a1;
  4486.     foreign_t handle;
  4487.     { struct context * ctxt;
  4488.  
  4489.       switch( PL_foreign_control(handle) )
  4490.       { case PL_FIRST_CALL:
  4491.            ctxt = (struct context *) malloc(sizeof(struct context));
  4492.            ...
  4493.            PL_retry(ctxt);
  4494.         case PL_REDO:
  4495.            ctxt = (struct context *) PL_foreign_context(handle);
  4496.            ...
  4497.            PL_retry(ctxt);
  4498.         case PL_CUTTED:
  4499.            free(ctxt);
  4500.            PL_succeed;
  4501.       }
  4502.     }
  4503.  
  4504.       Figure 5.1:  Skeleton for non-deterministic foreign functions
  4505.  
  4506.  
  4507. 5.5.2 Analysing Terms via the Foreign Interface
  4508.  
  4509. Each argument of a foreign function (except for the control argument) is
  4510. of type term.  To analyse a term one should first obtain the type of the
  4511. term.  Primitive terms can then be transformed into atomic data in
  4512. internal Prolog representation.  This atomic data can be transformed into
  4513. C-data types.  Complex terms are analysed in terms on their functor and
  4514. arguments.  The arguments themselves are terms, allowing the same
  4515. procedure to be repeated recursively.
  4516.  
  4517.  
  4518. int PL_type(term)
  4519.     Obtain the type of term, which should be a term returned by one of
  4520.     the other interface predicates or passed as an argument.  The
  4521.     function returns the type of the Prolog term.  The type identifiers
  4522.     are listed below.
  4523.  
  4524.       PL_VARIABLE            An unbound variable.  The value of term as
  4525.                              such is a unique identifier for the
  4526.                              variable.
  4527.       PL_ATOM                A Prolog atom.
  4528.  
  4529.       PL_STRING              A Prolog string.
  4530.  
  4531.       PL_INTEGER             A Prolog integer.
  4532.  
  4533.       PL_FLOAT               A Prolog floating point number.
  4534.  
  4535.       PL_TERM                A compound term.  Note that a list is a
  4536.                              compound term with name `.'  and arity 2.
  4537.  
  4538.  
  4539. atomic PL_atomic(term)
  4540.        Return the atomic value of term in Prolog internal representation.
  4541.        Term should be atomic (e.g.  atom, integer, float or string).
  4542.  
  4543.  
  4544. long PL_integer_value(atomic)
  4545.      Transforms an integer from Prolog internal representation into a C
  4546.      long.
  4547.  
  4548.  
  4549. double PL_float_value(atomic)
  4550.        Transforms a float from Prolog internal representation into a C
  4551.        double.
  4552.  
  4553.  
  4554. char * PL_atom_value(atomic)
  4555.        Transforms an atom from Prolog internal representation into a
  4556.        0-terminated C char *.  The pointer points directly into the Prolog
  4557.        heap and can assumed to be static.  The contents of the character
  4558.        string however should under NO circumstances be modified.
  4559.  
  4560.  
  4561. char * PL_string_value(string)
  4562.        Transform a string from Prolog internal representation into a C char
  4563.        *.  The pointer points directly into the Prolog data area.  Unlike
  4564.        the pointer returned by PL_atom_value() the C user should copy the
  4565.        value to a private data area if its value should survive the current
  4566.        foreign language call.  Like PL_atom_value(), changing the contents
  4567.        of the character string is NOT allowed.
  4568.  
  4569.  
  4570. functor PL_functor(term)
  4571.         term should be a complex term.  The return value is a unique
  4572.         identifier of the term's name and arity.  The following example
  4573.         demonstrates this:
  4574.  
  4575.             pl_same_functor(t1, t2)
  4576.             term t1, t2;
  4577.             { if ( PL_type(t1) != PL_TERM || PL_type(t2) != PL_TERM )
  4578.                PL_fail;
  4579.               if ( PL_functor(t1) == PL_functor(t2) )
  4580.                PL_succeed;
  4581.               PL_fail;
  4582.             }
  4583.  
  4584.  
  4585. atomic PL_functor_name(functor)
  4586.        Return an atom representing the name of functor.  To get the functor
  4587.        name as char * of a term which is known to be compound:
  4588.  
  4589.        #define functor_name(term) PL_atom_value(PL_functor_name(PL_functor(term*
  4590.  *)))
  4591.  
  4592.  
  4593. int PL_functor_arity(functor)
  4594.     Return a C integer representing the arity of functor.
  4595.  
  4596.  
  4597. term PL_arg(term, int)
  4598.      Return the int-th argument of term.  Argument counting starts at 1
  4599.      and is valid up to and including the arity of term.  No checks on
  4600.      these boundaries are performed.
  4601.  
  4602.  
  4603. Figure 5.2 shows a definition of display/1 to illustrate the described
  4604. functions.
  4605.  
  4606.     pl_display(t)
  4607.     term t;
  4608.     { functor functor;
  4609.       int arity, n;
  4610.  
  4611.       switch( PL_type(t) )
  4612.       { case PL_VARIABLE:
  4613.            printf("_%d", t);
  4614.            break;
  4615.         case PL_ATOM:
  4616.            printf("%s", PL_atom_value(PL_atomic(t)));
  4617.            break;
  4618.         case PL_STRING:
  4619.            printf("\"%s\"", PL_string_value(PL_atomic(t)));
  4620.            break;
  4621.         case PL_INTEGER:
  4622.            printf("%d", PL_integer_value(PL_atomic(t)));
  4623.            break;
  4624.         case PL_FLOAT:
  4625.            printf("%f", PL_float_value(PL_atomic(t)));
  4626.            break;
  4627.         case PL_TERM:
  4628.            functor = PL_functor(t);
  4629.            arity = PL_functor_arity(functor);
  4630.            printf("%s", PL_atom_value(PL_functor_name(functor)));
  4631.            printf("(");
  4632.            pl_display(PL_arg(t, 1));
  4633.            for( n = 2; n <= arity; n++)
  4634.            { printf(", ");
  4635.              pl_display(PL_arg(t, n));
  4636.            }
  4637.            printf(")");
  4638.            break;
  4639.         default:
  4640.            PL_fatal_error("Illegal type in pl_display(): %d",
  4641.                                                PL_type(t));
  4642.       }
  4643.  
  4644.       PL_succeed;
  4645.     }
  4646.  
  4647.              Figure 5.2:  Foreign definition of display/1
  4648.  
  4649.  
  4650. 5.5.3 Instantiating and Constructing Terms
  4651.  
  4652. Terms are instantiated as in Prolog itself by unification.  Variables can
  4653. be unified with atomic data, with a functor and with other terms.  New
  4654. terms are first constructed as a single unbound variable.
  4655.  
  4656.  
  4657. term PL_new_term()
  4658.      Create a new term.  The term is an unbound variable living on the
  4659.      global stack.  In the current implementation it lives until Prolog
  4660.      backtracks to before this call.  Garbage collection might change this
  4661.      in the future.
  4662.  
  4663.  
  4664. atomic PL_new_atom(char *)
  4665.        Create a Prolog atom from a C char *.  The contents of the char * are
  4666.        copied to the Prolog heap.
  4667.  
  4668.  
  4669. atomic PL_new_string(char *)
  4670.        Create a Prolog string, living on the global stack.  The contents of
  4671.        the char * are copied into Prolog's data area.
  4672.  
  4673.  
  4674. atomic PL_new_integer(long)
  4675.        Create a Prolog integer from a C long.  Note that the integer is
  4676.        truncated to 28 bits.  No checks on this are performed.
  4677.  
  4678.  
  4679. atomic PL_new_float(double)
  4680.        Create a Prolog float living on the global stack from double.
  4681.  
  4682.  
  4683. functor PL_new_functor(atomic, int)
  4684.         Create a Prolog functor identifier form atomic (which should be an
  4685.         atom) and int, the arity.  Arity is valid for any arity  0.  Arity = 0
  4686.         is used internally, but none of the interface functions use it.
  4687.  
  4688.  
  4689. bool PL_unify(term, term)
  4690.      Unify two terms.  Return value is TRUE or FALSE.
  4691.  
  4692.  
  4693. bool PL_unify_atomic(term, atomic)
  4694.      Unify a term with an atomic value.
  4695.  
  4696.  
  4697. bool PL_unify_functor(term, functor)
  4698.      Unify a term with a functor.  The unification simply succeeds if term
  4699.      is already instantiated to a term with functor functor.  If term is
  4700.      variable it will be instantiated to the most general term of functor
  4701.      (e.g.  a term with all arguments unbound variables).  Otherwise FALSE
  4702.      is returned.
  4703.  
  4704.      If this call succeeds the arguments can be further instantiated by
  4705.      calling PL_arg() and recursively unifying the returned terms.
  4706.  
  4707.  
  4708. An example of using these functions is shown in figure 5.3.
  4709.  
  4710.  
  4711. 5.5.4 Calling Prolog from C
  4712.  
  4713. The Prolog system can be called back from C. This is done by constructing
  4714. a term with the functions described above and then calling PL_call().
  4715. PL_call() executes the goal and returns TRUE or FALSE depending on success
  4716. or failure of the called predicate.  There are no means to backtrack over
  4717. the Prolog predicate.  If alternatives are wanted call findall/3 and read
  4718. the result from the third argument.
  4719.  
  4720.  
  4721. bool PL_call(term, module)
  4722.      Call term just like the Prolog predicate once/1.  Term is called in
  4723.      the specified module, or in the context module if module = NULL.
  4724.      Returns TRUE if the call succeeds, FALSE otherwise.  Figure 5.3 shows
  4725.      an example to obtain the number of defined atoms.  All checks are
  4726.      omitted to improve readability.
  4727.  
  4728.  
  4729. 5.5.5 Discarding Data
  4730.  
  4731. The Prolog data created during setting up the call and calling Prolog can
  4732. in most cases be discarded right after the call.  See figure 5.3 for an
  4733. example.
  4734.  
  4735.  
  4736. void PL_mark(bktrk_buf)
  4737.      Mark the global and trail stacks in bktrk_buf.
  4738.  
  4739.  
  4740. void PL_bktrk(bktrk_buf)
  4741.      Undo all changes in the runtime stacks since a snapshot has been made
  4742.      in buffer using PL_mark().  Changes to the heap are not affected.
  4743.  
  4744.  
  4745. It is not necessary to call PL_bktrk() for each PL_mark().  The user
  4746. should ensure that PL_bktrk() is never called with a buffer that is
  4747. created after a buffer to which PL_bktrk() has been called.  Thus
  4748. PL_mark(b1) ...  PL_mark(b2) ...  PL_bktrk(b1) is valid, but it is not
  4749. allowed to call PL_bktrk(b2) after this sequence.
  4750.  
  4751.     int
  4752.     count_atoms()
  4753.     { term t;
  4754.       int atoms;
  4755.       bktrk_buf buf;
  4756.  
  4757.       PL_mark(&buf);           /* mark the global stack */
  4758.  
  4759.       t = PL_new_term();       /* create `statistics(atoms, Var)' */
  4760.       PL_unify_functor(t, PL_new_functor(PL_new_atom("statistics"), 2));
  4761.       PL_unify_atomic(PL_arg(t,1), PL_new_atom("atoms"));
  4762.  
  4763.       PL_call(t);              /* call it */
  4764.  
  4765.                              /* extract the value from the 2nd arg */
  4766.       atoms = PL_integer_value(PL_atomic(PL_arg(t, 2)));
  4767.  
  4768.       PL_bktrk(&buf);          /* discard global stack data created */
  4769.  
  4770.       return atoms;
  4771.     }
  4772.  
  4773.                      Figure 5.3:  Calling Prolog
  4774.  
  4775.  
  4776. 5.5.6 Foreign Code and Modules
  4777.  
  4778. Modules are identified via a unique handle.  The following functions are
  4779. available to query and manipulate modules.
  4780.  
  4781.  
  4782. module PL_context()
  4783.        Return the module identifier of the context module of the currently
  4784.        active foreign predicate.
  4785.  
  4786.  
  4787. term PL_strip_module(term, module *)
  4788.      Utility function.  If term is a term, possibly holding the module
  4789.      construct module:rest this function will return rest and fill module
  4790.      * with module.  For further nested module constructs the inner most
  4791.      module is returned via module *.  If term is not a module construct
  4792.      term will simply be returned.  If module * is NULL it will be set to
  4793.      the context module.  Otherwise it will be left untouched.  The
  4794.      following example shows how to obtain the plain term and module if
  4795.      the default module is the user module:
  4796.  
  4797.          { module m = PL_new_module(PL_new_atom("user"));
  4798.  
  4799.            if ( (term = PL_strip_module(term, &m)) == NULL )
  4800.             return PL_warning("Illegal module specification");
  4801.  
  4802.            ...
  4803.  
  4804.  
  4805. atomic PL_module_name(module)
  4806.        Return the name of module as an atom.
  4807.  
  4808.  
  4809. module PL_new_module(atomic)
  4810.        Find an existing or create a new module with name specified by the
  4811.        atom atomic.
  4812.  
  4813.  
  4814. 5.5.7 Catching Unix Signals
  4815.  
  4816. SWI-Prolog catches the Unix signals SIGINT, SIGFPE and SIGSEGV. To avoid
  4817. problems with foreign code attempting to catch these signals foreign code
  4818. should call PL_signal() to install signal handlers rather than the Unix
  4819. library function signal().  SWI-Prolog will always handle SIGINT itself.
  4820. SIGFPE and SIGSEGV are passed to the foreign code handlers if Prolog did
  4821. not expect that signal.
  4822.  
  4823.  
  4824. void (*PL_signal(sig, func))()
  4825.      This function should be used to install signal handlers rather than
  4826.      the Unix library function signal().  It ensures consistent signal
  4827.      handling between SWI-Prolog and the foreign code and reinstalls
  4828.      signal handlers if a state created with save_program/1 is restarted.
  4829.  
  4830.  
  4831. 5.5.8 Errors and warnings
  4832.  
  4833. Two standard functions are available to print standard Prolog errors to
  4834. the standard error stream.
  4835.  
  4836.  
  4837. bool PL_warning(format, a1, ...)
  4838.      Print an error message starting with `[WARNING:', followed by the
  4839.      output from format, followed by a `]' and a newline.  Then start the
  4840.      tracer.  format and the arguments are the same as for printf(2).  No
  4841.      more than 10 arguments can be provided.
  4842.  
  4843.  
  4844. void PL_fatal_error(format, a1, ...)
  4845.      Print a message like PL_warning(), but starting with `FATAL ERROR:'
  4846.      and then exits Prolog.
  4847.  
  4848.  
  4849. 5.5.9 Environment Control from Foreign Code
  4850.  
  4851.  
  4852. bool PL_action(int, C_type)
  4853.      Perform some action on the Prolog system.  int describes the action,
  4854.      C_type provides the argument if necessary.  The actions are listed in
  4855.      table 5.1.
  4856.  
  4857.       PL_ACTION_TRACE        Start Prolog tracer
  4858.  
  4859.       PL_ACTION_DEBUG        Switch on Prolog debug mode
  4860.  
  4861.       PL_ACTION_BACKTRACE    Print backtrace on current output stream
  4862.  
  4863.       PL_ACTION_HALT         Halt Prolog execution.  This action should
  4864.                              be called rather than Unix exit() to give
  4865.                              Prolog the opportunity to clean up.  This
  4866.                              call does not return.
  4867.       PL_ACTION_ABORT        Generate a Prolog abort.  This call does not
  4868.                              return.
  4869.       PL_ACTION_BREAK        Create a standard Prolog break environment.
  4870.                              Returns after the user types control-D.
  4871.  
  4872.       PL_ACTION_SYMBOLFILE   The argument (a char *) is considered to be
  4873.                              hold the symbolfile for further incremental
  4874.                              loading.  Should be called by user
  4875.                              applications that perform incremental
  4876.                              loading as well and want to inform Prolog of
  4877.                              the new symbol table.
  4878.  
  4879.                     Table 5.1:  PL_action() options
  4880.  
  4881.  
  4882. 5.5.10 Querying Prolog
  4883.  
  4884.  
  4885. C_type PL_query(int)
  4886.        Obtain status information on the Prolog system.  The actual argument
  4887.        type depends on the information required.  int describes what
  4888.        information is wanted.  The options are given in table 5.2.
  4889.  
  4890.         PL_QUERY_ARGC          Return an integer holding the number of
  4891.                                arguments given to Prolog from Unix.
  4892.  
  4893.         PL_QUERY_ARGV          Return a char ** holding the argument vector
  4894.                                given to Prolog from Unix.
  4895.  
  4896.         PL_QUERY_SYMBOLFILE    Return a char * holding the current symbol
  4897.                                file of the running process.
  4898.  
  4899.         PL_QUERY_ORGSYMBOLFILE Return the initial symbol file (before
  4900.                                loading) of Prolog.  By setting the symbol
  4901.                                file to this value no name clashes can occur
  4902.                                with previously loaded foreign files (but no
  4903.                                symbols can be shared with earlier loaded
  4904.                                modules as well).
  4905.  
  4906.                        Table 5.2:  PL_query() options
  4907.  
  4908.  
  4909. 5.5.11 Registering Foreign Predicates
  4910.  
  4911.  
  4912. bool PL_register_foreign(name, arity, function, [...option...]  0)
  4913.      Register a C-function to implement a Prolog predicate.  After this
  4914.      call returns successfully a predicate with name name (a char *) and
  4915.      arity arity (a C int) is created.  When called in Prolog, Prolog will
  4916.      call function.  [...option...]  forms a 0-terminated list of options
  4917.      for the installation.  These are:
  4918.  
  4919.           PL_FA_NOTRACE           Predicate cannot be seen in the
  4920.                                   tracer
  4921.           PL_FA_TRANSPARENT       Predicate is module transparent
  4922.  
  4923.           PL_FA_NONDETERMINISTIC  Predicate is non-deterministic.  This
  4924.                                   attribute is currently ignored, but
  4925.                                   will probably be used in future
  4926.                                   versions.
  4927.  
  4928.  
  4929. 5.6 Example of Using the Foreign Interface
  4930.  
  4931. Below is an example showing all stages of the declaration of a foreign
  4932. predicate that transforms atoms possibly holding uppercase letters into an
  4933. atom only holding lower case letters.  Figure 5.4 shows the C-source file.
  4934.  
  4935.  
  4936. 5.6.1 C-Source file (lowercase.c)
  4937.  
  4938.     /*  Include file depends on local installation */
  4939.     #include "/usr/local/lib/pl/library/SWI-prolog.h"
  4940.     #include <ctype.h>
  4941.  
  4942.     long
  4943.     pl_lowercase(u, l)
  4944.     term u, l;
  4945.     { char *copy;
  4946.       char *s, *q;
  4947.       atomic la;
  4948.  
  4949.       if ( PL_type(u) != PL_ATOM )
  4950.         return PL_warning("lowercase/2: instantiation fault");
  4951.       s = PL_atom_value(PL_atomic(u));
  4952.       copy = (char *) malloc(strlen(s)+1);
  4953.  
  4954.       for( q=copy; *s; q++, s++)
  4955.         *q = (isupper(*s) ? tolower(*s) : *s);
  4956.       *q = '\0';
  4957.  
  4958.       la = PL_new_atom(copy);
  4959.       free(copy);
  4960.  
  4961.       return PL_unify_atomic(l, la);
  4962.     }
  4963.  
  4964.     init_lowercase()
  4965.     { PL_register_foreign("lowercase", 2, pl_lowercase, 0);
  4966.     }
  4967.  
  4968.                   Figure 5.4:  Lowercase source file
  4969.  
  4970.  
  4971. 5.6.2 Compiling and Loading Foreign Code
  4972.  
  4973.     sun% cc -O -c lowercase.c
  4974.     sun% pl
  4975.     /staff/jan/.plrc consulted, 0.166667 seconds, 2256 bytes.
  4976.     Welcome to SWI-Prolog (version 1.5.0, August 1990)
  4977.     Copyright (c) 1990, University of Amsterdam
  4978.  
  4979.     1 ?- load_foreign(lowercase, init_lowercase).
  4980.     foreign file(s) lowercase loaded, 0.016667 seconds, 464 bytes.
  4981.  
  4982.     Yes
  4983.     2 ?- lowercase('Hello World!', L).
  4984.  
  4985.     L = 'hello world!'
  4986.  
  4987.     Yes
  4988.  
  4989.  
  4990. 5.7 Notes on Using Foreign Code
  4991.  
  4992.  
  4993. 5.7.1 Garbage Collection and Foreign Code
  4994.  
  4995. Currently no interface between foreign code and the garbage collector has
  4996. been defined.  The garbage collector is disabled during execution of
  4997. foreign code.  Future versions might define such an interface.  This
  4998. probably will introduce incompatible changes to the current interface
  4999. definition.
  5000.  
  5001.  
  5002. 5.7.2 Memory Allocation
  5003.  
  5004. SWI-Prolog's memory allocation is based on the malloc() library routines.
  5005. Foreign applications can savely use malloc(), realloc() and free().
  5006. Memory allocation using brk() or sbrk() is not allowed as these calls
  5007. conflict with malloc().
  5008.  
  5009.  
  5010. 5.7.3 Debugging Foreign Code
  5011.  
  5012. NOTE: this section is highly machine dependent.  The tricks described here
  5013. are tested on SUN-3 and SUN-4.  They might work on other BSD variants of
  5014. Unix.
  5015.  
  5016. Debugging incrementally loaded executables is a bit more difficult than
  5017. debugging normal executables.  The oldest way of debugging (putting print
  5018. statements in your code at critical points) of course still works.
  5019. `Post-crash' debugging however is not possible.  For adb/dbx to work they
  5020. need (besides the core) the text segment and the symbol table.  The symbol
  5021. table lives somewhere on /tmp (called `/tmp/pl_ld_..._.', where `...'  is
  5022. the process id and `.'  is an additional number to make sure the temporary
  5023. file is unique.  The text segment lives partly in the core (the
  5024. incremental loaded bit) and partly in the SWI-Prolog executable.
  5025.  
  5026. The only way to debug foreign language code using a debugger is by
  5027. starting the debugger on the running core image.  Dbx(1) can do this.
  5028. First compile the source files to be debugged with the `-g' option to
  5029. include dbx debugging information.  Then load them into SWI-Prolog.  Now
  5030. obtain the name of the current symbol table and the process id of Prolog.
  5031. Then start dbx (or dbxtool) using
  5032.  
  5033.     sun% dbx[tool] <symbol file> <pid>
  5034.  
  5035. Should this be done often then the following foreign predicate definition
  5036. might help:
  5037.  
  5038.     pl_dbx()
  5039.     { char *symbolfile = PL_query(PL_QUERY_SYMBOLFILE);
  5040.       char cmd[256];
  5041.  
  5042.       sprintf(cmd, "dbxtool %s %d &", symbolfile, getpid());
  5043.       if ( system(cmd) == 0 )
  5044.         PL_succeed;
  5045.       else
  5046.         PL_fail;
  5047.     }
  5048.  
  5049. Register this predicate as dbx/0 using the following call in your
  5050. initialisation function:
  5051.  
  5052.     PL_register_foreign("dbx", 0, pl_dbx, 0);
  5053.  
  5054.  
  5055. 5.7.4 Name Conflicts in C modules
  5056.  
  5057. In the current version of the system all public C functions of SWI-Prolog
  5058. are in the symbol table.  This can lead to name clashes with foreign code.
  5059. Someday I should write a program to strip all these symbols from the
  5060. symbol table (why does Unix not have that?).  For now I can only suggest
  5061. to give your function another name.  You can do this using the C
  5062. preprocessor.  If --for example-- your foreign package uses a function
  5063. warning(), which happens to exist in SWI-Prolog as well, the following
  5064. macro should fix the problem.
  5065.  
  5066.     #define warning warning_
  5067.  
  5068.  
  5069. 5.7.5 Compatibility of the Foreign Interface
  5070.  
  5071. As far as I' aware of, there is no standard for foreign language
  5072. interfaces in Prolog.  The SWI-Prolog interface is no attempt to propose
  5073. such a standard.  It is (in part) tailored to the possibilities of the
  5074. SWI-Prolog machinery.  BIM-Prolog has a similar interface to analyse and
  5075. construct terms.  The major difference is that they have garbage
  5076. collection and calls are made available to lock and unlock terms for
  5077. garbage collection.  I built a similar interface to Edinburgh C-Prolog
  5078. (although less clean).  This at least tells us that the interface can work
  5079. for various forms of the WAM as well as a structure sharing Prolog.
  5080.  
  5081. As no standard exists nor emerges, users of the foreign language interface
  5082. should carefully design the interface if the C-code should be portable to
  5083. other Prolog implementation.  The best advice to give is to define a small
  5084. interface layer around the C-application and interface this to Prolog.
  5085.  
  5086.  
  5087. Chapter  6
  5088.  
  5089. Hackers  corner
  5090.  
  5091. This appendix describes a number of predicates which enable the Prolog
  5092. user to inspect the Prolog environment and manipulate (or even redefine)
  5093. the debugger.  They can be used as entry points for experiments with
  5094. debugging tools for Prolog.  The predicates described here should be
  5095. handled with some care as it is easy to corrupt the consistency of the
  5096. Prolog system by misusing them.
  5097.  
  5098.                                 477
  5099.  
  5100.  
  5101. 6.1 Examining the Environment Stack
  5102.  
  5103.  
  5104. prolog_current_frame(-Frame)
  5105.     Unify Frame with an integer providing a reference to the parent of
  5106.     the current local stack frame.  A pointer to the current local frame
  5107.     cannot be provided as the predicate succeeds deterministically and
  5108.     therefore its frame is destroyed immediately after succeeding.
  5109.  
  5110.  
  5111. prolog_frame_attribute(+Frame, +Key, -Value)
  5112.     Obtain information about the local stack frame Frame.  Frame is a
  5113.     frame reference as obtained through prolog_current_frame/1,
  5114.     prolog_trace_interception/3 or this predicate.  The key values are
  5115.     described in table 6.1.
  5116.  
  5117.     Key               Value
  5118.     alternative       Value is unified with an integer reference
  5119.                       to the local stack frame in which execution
  5120.                       is resumed if the goal associated with Frame
  5121.                       fails.  Fails if the frame has no
  5122.                       alternative frame.
  5123.     has_alternatives  Value is unified with `1' if Frame still is
  5124.                       a candidate for backtracking.  `0'
  5125.                       otherwise.
  5126.     goal              Value is unified with the goal associated
  5127.                       with Frame.  If the definition module of the
  5128.                       active predicate is not user the goal is
  5129.                       represented as module:goal.  Do not
  5130.                       instantiate variables in this goal unless
  5131.                       you know what you are doing!
  5132.  
  5133.     level             Value is unified with the recursion level of
  5134.                       Frame.  The top level frame is at level `0'.
  5135.  
  5136.     parent            Value is unified with an integer reference
  5137.                       to the parent local stack frame of Frame.
  5138.                       Fails if Frame is the top frame.
  5139.  
  5140.     context_module    Value is unified with the name of the
  5141.                       context module of the environment.
  5142.     top               Value is unified with `1' if Frame is the
  5143.                       top Prolog goal from a recursive call back
  5144.                       from the foreign language.  `0' otherwise.
  5145.  
  5146.             Table 6.1:  Key values of prolog_current_frame/1
  5147.  
  5148.  
  5149. 6.2 Intercepting the Tracer
  5150.  
  5151.  
  5152. prolog_trace_interception(+Port, +Frame, -Action)
  5153.     Dynamic predicate, normally not defined.  This predicate is called
  5154.     from the SWI-Prolog debugger just before it would show a port.  If
  5155.     this predicate succeeds the debugger assumes the trace action has
  5156.     been taken care of and continues execution as described by Action.
  5157.     Otherwise the normal Prolog debugger actions are performed.
  5158.  
  5159.     Port is one of call, redo, exit, fail or unify.  Frame is an integer
  5160.     reference to the current local stack frame.  Action should be unified
  5161.     with one of the atoms continue(just continue execution), retry
  5162.     (retry the current goal) or fail (force the current goal to fail).
  5163.     Leaving it a variable is identical to continue.
  5164.  
  5165.     Together with the predicates described in section 3.34 and the other
  5166.     predicates of this chapter this predicate enables the Prolog user to
  5167.     define a complete new debugger in Prolog.  Besides this it enables
  5168.     the Prolog programmer monitor the execution of a program.  The
  5169.     example shown in figure 6.1 records all goals trapped by the tracer
  5170.     in the database.  To trace the execution of `go' this way the
  5171.     following query should be given:
  5172.  
  5173.         ?- trace, go, notrace.
  5174.  
  5175.        prolog_trace_interception(Port, Frame, continue) :-
  5176.               prolog_frame_attribute(Frame, goal, Goal),
  5177.               prolog_frame_attribute(Frame, level, Level),
  5178.               recordz(trace, trace(Port, Level, Goal)).
  5179.  
  5180.               Figure 6.1:  Record a trace in the database
  5181.  
  5182.  
  5183. prolog_skip_level(-Old, +New)
  5184.     Unify Old with the old value of `skip level' and than set this level
  5185.     according to New.  New is an integer, or the special atom very_deep
  5186.     (meaning don't skip).  The `skip level' is a global variable of the
  5187.     Prolog system that disables the debugger on all recursion levels
  5188.     deeper than the level of the variable.  Used to implement the trace
  5189.     options `skip' (sets skip level to the level of the frame) and `up'
  5190.     (sets skip level to the level of the parent frame (i.e. the level of
  5191.     this frame minus 1).
  5192.  
  5193.  
  5194. 6.3 Exception Handling
  5195.  
  5196. A start has been made to make exception handling available to the Prolog
  5197. user.  On exceptions a dynamic and multifile defined predicate exception/3
  5198. is called.  If this user defined predicate succeeds Prolog assumes the
  5199. exception has been taken care of.  Otherwise the system default exception
  5200. handler is called.
  5201.  
  5202.  
  5203. exception(+Exception, +Context, -Action)
  5204.     Dynamic predicate, normally not defined.  Called by the Prolog system
  5205.     on run-time exceptions.  Currently exception/3 is only used for
  5206.     trapping undefined predicates.  Future versions might handle signal
  5207.     handling, floating exceptions and other runtime errors via this
  5208.     mechanism.  The values for Exception are described below.
  5209.  
  5210.     undefined_predicate
  5211.         If Exception is undefined_predicateContext is instantiated to a
  5212.         term Name/Arity.  Name refers to the name and Arity to the arity
  5213.         of the undefined predicate.  If the definition module of the
  5214.         predicate is not user Context will be of the form
  5215.         Module:Name/Arity.  If the predicate fails Prolog will print the
  5216.         default error warning and start the tracer.  If the predicate
  5217.         succeeds it should instantiate the last argument either to the
  5218.         atom fail to tell Prolog to fail the predicate or the atom retry
  5219.         to tell Prolog to retry the predicate.  This only makes sense if
  5220.         the exception handler has defined the predicate.  Otherwise it
  5221.         will lead to a loop.
  5222.  
  5223.     warning
  5224.         If prolog wants to give a warning while reading a file, it will
  5225.         first raise the exception warning.  The context argument is a
  5226.         term of the form warning(Path, LineNo, Message), where Path is
  5227.         the absolute filename of the file prolog is reading; LineNo is an
  5228.         extimate of the line number where the error occurred and Message
  5229.         is a Prolog string indicating the message.  The Action argument
  5230.         is ignored.  The error is supposed to be presented to the user if
  5231.         the exception handler succeeds.  Otherwise the standard Prolog
  5232.         warning message is printed.
  5233.  
  5234.         This exception is used by the library emacs_interface, that
  5235.         integrates error handling with GNU-Emacs.
  5236.  
  5237.  
  5238. Chapter  7
  5239.  
  5240. Predicate  Summary
  5241.  
  5242. !/0                         Cut.  Discard choicepoints
  5243. */2                         Arithmetic:  multiplication
  5244. +/2                         Arithmetic:  addition
  5245. ,/2                         Conjuction of goals
  5246. -/1                         Arithmetic:  unary minus
  5247. -/2                         Arithmetic:  subtraction
  5248. ->/2                        If-then-else
  5249. ./2                         List operator.  Also consult
  5250. ///2                        Arithmetic:  Integer division
  5251. //2                         Arithmetic:  division
  5252. /\/2                        Arithmetic:  bitwise and
  5253. ;/2                         Disjunction of goals
  5254. </2                         Arithmetic smaller
  5255. <</2                        Arithmetic:  bitwise left shift
  5256. =../2                       Univ.  Term to list conversion
  5257. =/2                         Unification
  5258. =:=/2                       Arithmetic equal
  5259. =</2                        Arithmetic smaller or equal
  5260. ==/2                        Identical
  5261. =@=/2                       Structural identical
  5262. =\=/2                       Arithmetic not equal
  5263. >/2                         Arithmetic larger
  5264. >=/2                        Arithmetic larger or equal
  5265. >>/2                        Arithmetic:  bitwise right shift
  5266. @</2                        Standard order smaller
  5267. @=</2                       Standard order smaller or equal
  5268. @>/2                        Standard order larger
  5269. @>=/2                       Standard order larger or equal
  5270. \/1                         Bitwise negation
  5271. \//2                        Arithmetic:  bitwise or
  5272. \+/1                        Negation by failure (not provable)
  5273. \=/2                        Not unifyable
  5274. \==/2                       Not identical
  5275. \=@=/2                      Not structural identical
  5276. ^/2                         Existential quantification (bagof/3, setof/3)
  5277. abolish/2                   Remove predicate definition from the database
  5278. abort/0                     Abort execution, return to top level
  5279. abs/1                       Arithmetic:  absolute value
  5280. absolute_file_name/2         Get absolute Unix path name
  5281. access_file/2                Check access permissions of a file
  5282. acos/1                      Arithmetic:  inverse (arc) cosine
  5283. append/1                    Append to a file
  5284. append/3                    Concatenate lists
  5285. apply/2                     Call goal with additional arguments
  5286. apropos/1                   Show related predicates and manual sections
  5287. arithmetic_function/1        Register an evaluable function
  5288. arg/3                       Access argument of a term
  5289. asin/1                      Arithmetic:  inverse (arc) sine
  5290. assert/1                    Add a clause to the database
  5291. assert/2                    Add a clause to the database, give reference
  5292. asserta/1                   Add a clause to the database (first)
  5293. asserta/2                   Add a clause to the database (first)
  5294. assertz/1                   Add a clause to the database (last)
  5295. assertz/2                   Add a clause to the database (last)
  5296. atan/1                      Arithmetic:  inverse (arc) tangent
  5297. atan/2                      Arithmetic:  rectangular to polar conversion
  5298. atom/1                      Type check for an atom
  5299. atom_length/2                Determine length of an atom
  5300. atom_to_term/3               Convert between atom and term
  5301. atomic/1                    Type check for primitive
  5302. bagof/3                     Find all solutions to a goal
  5303. between/3                   Integer range checking/generating
  5304. break/0                     Start interactive toplevel
  5305. call/1                      Call a goal
  5306. ceil/1                      Arithmetic:  smallest integer larger than argument
  5307. character_count/2            Get character index on a stream
  5308. chdir/1                     Change working directory
  5309. checklist/2                 Invoke goal on all members of a list
  5310. clause/2                    Get clauses of a predicate
  5311. clause/3                    Get clauses of a predicate
  5312. close/1                     Close stream
  5313. compiling/0                 Is this a compilation run?
  5314. concat/3                    Append two atoms
  5315. concat_atom/2                Append a list of atoms
  5316. consult/1                   Read (compile) a Prolog source file
  5317. context_module/1             Get context module of current goal
  5318. convert_time/8               Convert time stamp
  5319. copy_term/2                 Make a copy of a term
  5320. cos/1                       Arithmetic:  cosine
  5321. cputime/0                   Arithmetic:  get CPU time
  5322. current_atom/1               Examine existing atoms
  5323. current_arithmetic_function/1 Examine evaluable functions
  5324. current_flag/1               Examine existing flags
  5325. current_functor/2            Examine existing name/arity pairs
  5326. current_input/1              Get current input stream
  5327. current_key/1                Examine existing database keys
  5328. current_op/3                Examine current operator declaractions
  5329. current_output/1             Get the current output stream
  5330. current_predicate/2          Examine existing predicates
  5331. current_stream/3             Examine open streams
  5332. debug/0                     Test for debugging mode
  5333. debugging/0                 Show debugger status
  5334. delete/3                    Delete all matching members from a list
  5335. delete_file/1                Unlink a file from the Unix file system
  5336. discontiguous/1              Indicate distributed definition of a predicate
  5337. display/1                   Write a term, ignore operators
  5338. display/2                   Write a term, ignore operators on a stream
  5339. displayq/1                  Write a term with quotes, ignore operators
  5340. displayq/2                  Write a term with quotes, ignore operators on a str*
  5341.  *eam
  5342. dwim_match/2                Atoms match in ``Do What I Mean'' sense
  5343. dwim_match/3                Atoms match in ``Do What I Mean'' sense
  5344. dwim_predicate/2             Find predicate in ``Do What I Mean'' sense
  5345. dynamic/1                   Indicate predicate definition may change
  5346. e/0                         Arithmetic:  mathematical constant
  5347. ed/0                        Edit last edited predicate
  5348. ed/1                        Edit a predicate
  5349. edit/0                      Edit last edited file
  5350. edit/1                      Edit a file
  5351. ensure_loaded/1              Consult a file if that has not yet been done
  5352. erase/1                     Erase a database record or clause
  5353. exception/3                 Handle runtime exceptions
  5354. exists_directory/1           Check existence of Unix directory
  5355. exists_file/1                Check existence of Unix file
  5356. exp/1                       Arithmetic:  exponent (base e)
  5357. expand_file_name/2           Wildcard expansion of file names
  5358. export/1                    Export a predicate from a module
  5359. fail/0                      Always false
  5360. fileerrors/2                Do/Don't warn on file errors
  5361. findall/3                   Find all solutions to a goal
  5362. flag/3                      Simple global variable system
  5363. flatten/2                   Transform nested list into flat list
  5364. float/1                     Type check for a floating point number
  5365. floor/1                     Arithmetic:  largest integer below argument
  5366. flush/0                     Output pending characters on current stream
  5367. flush_output/1               Output pending characters on specified stream
  5368. forall/2                    Prove goal for all solutions of another goal
  5369. foreign_file/1               Examine loaded foreign files
  5370. format/1                    Produce formatted output
  5371. format/2                    Produce formatted output on a stream
  5372. format_predicate/2           Program format/[1,2]
  5373. free_variables/2             Find unbound variables in a term
  5374. functor/3                   Get name and arity of a term or construct a term
  5375. garbage_collect/0            Invoke the garbage collector
  5376. gensym/2                    Generate unique atoms from a base
  5377. get/1                       Read first non-blank character
  5378. get/2                       Read first non-blank character from a stream
  5379. get0/1                      Read next character
  5380. get0/2                      Read next character from a stream
  5381. get_single_char/1            Read next character from the terminal
  5382. get_time/1                  Get current time
  5383. getenv/2                    Get Unix environment variable
  5384. ground/1                    Verify term holds no unbound variables
  5385. halt/0                      Exit from Prolog
  5386. help/0                      Give help on help
  5387. help/1                      Give help on predicates and show parts of manual
  5388. history_depth/1              Number of remembered queries
  5389. read_history/6               Read using history substitution
  5390. ignore/1                    Call the argument, but always succeed
  5391. import/1                    Import a predicate from a module
  5392. index/1                     Change clause indexing
  5393. int_to_atom/2                Convert from integer to atom
  5394. int_to_atom/3                Convert from integer to atom (non-decimal)
  5395. integer/1                   Arithmetic:  round to nearest integer
  5396. integer/1                   Type check for integer
  5397. intersection/3               Set intersection
  5398. is/2                        Evaluate arithmetic expression
  5399. is_list/1                   Type check for a list
  5400. is_set/1                    Type check for a set
  5401. keysort/2                   Sort, using a key
  5402. last/2                      Last element of a list
  5403. leash/1                     Change ports visited by the tracer
  5404. length/2                    Length of a list
  5405. library_directory/1          Directories holding Prolog libraries
  5406. limit_stack/2                Limit stack expansion
  5407. line_count/2                Line number on stream
  5408. line_position/2              Character position in line on stream
  5409. list_to_set/2                Remove duplicates
  5410. listing/0                   List program in current module
  5411. listing/1                   List predicate
  5412. load_foreign/2               Load foreign (C) module
  5413. load_foreign/5               Load foreign (C) module
  5414. log/1                       Arithmetic:  natural logarithm
  5415. log10/1                     Arithmetic:  10 base logarithm
  5416. make/0                      Reconsult all changed source files
  5417. maplist/3                   Transform all elements of a list
  5418. max/2                       Arithmetic:  Maximum of two numbers
  5419. member/2                    Element is member of a list
  5420. memberchk/2                 Deterministic member/2
  5421. merge/3                     Merge two sorted lists
  5422. merge_set/3                 Merge two sorted sets
  5423. min/2                       Arithmetic:  Minimum of two numbers
  5424. mod/2                       Arithmetic:  remainder of division
  5425. module/2                    Declare a module
  5426. module_transparent/1         Indicate module based meta predicate
  5427. msort/2                     Sort, do not remove duplicates
  5428. multifile/1                 Indicate distributed definition of predicate
  5429. name/2                      Convert between atom and list of ASCII characters
  5430. nl/0                        Generate a newline
  5431. nl/1                        Generate a newline on a stream
  5432. nodebug/0                   Disable debugging
  5433. nonvar/1                    Type check for bound term
  5434. noprotocol/0                Disable logging of user interaction
  5435. nospy/1                     Remove spy point
  5436. nospyall/0                  Remove all spy points
  5437. not/1                       Negation by failure (not provable)
  5438. notrace/0                   Stop tracing
  5439. nth0/3                      N-th element of a list (0-based)
  5440. nth1/3                      N-th element of a list (1-based)
  5441. number/1                    Type check for integer or float
  5442. numbervars/4                Enumerate unbound variables of a term
  5443. once/1                      Call a goal deterministicaly
  5444. op/3                        Declare an operator
  5445. open/3                      Open a file (creating a stream)
  5446. open_null_stream/1           Open a stream to discard output
  5447. pi/0                        Arithmetic:  mathematical constant
  5448. please/3                    Query/change environment parameters
  5449. plus/3                      Logical integer addition
  5450. portray/1                   Modify behaviour of print/1
  5451. portray_clause/1             Pretty print a clause
  5452. predicate_property/2         Query predicate attributes
  5453. predsort/3                  Sort, using a predicate to determine the order
  5454. preprocessor/2               Install a preprocessor before the compiler
  5455. print/1                     Print a term
  5456. print/2                     Print a term on a stream
  5457. profile/3                   Obtain execution statistics
  5458. profile_count/3              Obtain profile results on a predicate
  5459. profiler/2                  Obtain/change status of the profiler
  5460. prolog/0                    Run interactive toplevel
  5461. prolog_current_frame/1       Reference to goal's environment stack
  5462. prolog_frame_attribute/3      Obtain information on a goal environment
  5463. prolog_skip_level/2          Indicate deepest recursion to trace
  5464. prolog_trace_interception/3   Intercept the Prolog tracer
  5465. prompt/2                    Change the prompt used by read/1
  5466. proper_list/1                Type check for list
  5467. protocol/1                  Make a log of the user interaction
  5468. protocola/1                 Append log of the user interaction to file
  5469. protocolling/1               On what file is user interaction logged
  5470. put/1                       Write a character
  5471. put/2                       Write a character on a stream
  5472. random/1                    Arithmetic:  generate random number
  5473. read/1                      Read Prolog term
  5474. read/2                      Read Prolog term from stream
  5475. read_clause/1                Read clause
  5476. read_clause/2                Read clause from stream
  5477. read_variables/2             Read clause including variable names
  5478. read_variables/3             Read clause including variable names from stream
  5479. recorda/2                   Record term in the database (first)
  5480. recorda/3                   Record term in the database (first)
  5481. recorded/2                  Obtain term from the database
  5482. recorded/3                  Obtain term from the database
  5483. recordz/2                   Record term in the database (last)
  5484. recordz/3                   Record term in the database (last)
  5485. rename_file/2                Change name of Unix file
  5486. repeat/0                    Succeed, leaving infinite backtrackpoints
  5487. reset_profiler/0             Clear statistics obtained by the profiler
  5488. retract/1                   Remove clause from the database
  5489. retractall/1                Remove unifying clauses from the database
  5490. reverse/2                   Inverse the order of the elements in a list
  5491. same_file/2                 Succeeds if arguments refer to same file
  5492. save_program/1               Save the current program on a file
  5493. save_program/2               Save the current program on a file
  5494. see/1                       Change the current input stream
  5495. seeing/1                    Query the current input stream
  5496. seen/0                      Close the current input stream
  5497. select/3                    Select element of a list
  5498. set_input/1                 Set current input stream from a stream
  5499. set_output/1                Set current output stream from a stream
  5500. set_tty/2                   Set `tty' stream
  5501. setenv/2                    Set Unix environment variable
  5502. setof/3                     Find all unique solutions to a goal
  5503. sformat/2                   Format on a string
  5504. sformat/3                   Format on a string
  5505. shell/0                     Execute interactive Unix subshell
  5506. shell/1                     Execute Unix command
  5507. shell/2                     Execute Unix command
  5508. show_profile/1               Show results of the profiler
  5509. sin/1                       Arithmetic:  sine
  5510. size_file/2                 Get size of a file in characters
  5511. sleep/1                     Suspend execution for specified time
  5512. sort/2                      Sort elements in a list
  5513. source_file/1                Examine currently loaded source files
  5514. source_file/2                Obtain source file of predicate
  5515. spy/1                       Force tracer on specified predicate
  5516. sqrt/1                      Arithmetic:  square root
  5517. statistics/0                Show execution statistics
  5518. statistics/2                Obtain collected statistics
  5519. stream_position/3            Get/seek to position in file
  5520. string/1                    Type check for string
  5521. string_length/2              Determine length of a string
  5522. string_to_atom/2             Conversion between string and atom
  5523. string_to_list/2             Conversion between string and list of ASCII
  5524. style_check/1                Change level of warnings
  5525. sublist/3                   Determine elements that meet condition
  5526. subset/2                    Generate/check subset relation
  5527. substring/4                 Get part of a string
  5528. subtract/3                  Delete elements that do not meet condition
  5529. succ/2                      Logical integer successor relation
  5530. swritef/2                   Formatted write on a string
  5531. swritef/3                   Formatted write on a string
  5532. tab/1                       Output number of spaces
  5533. tab/2                       Output number of spaces on a stream
  5534. tan/1                       Arithmetic:  tangent
  5535. tell/1                      Change current output stream
  5536. telling/1                   Query current output stream
  5537. term_expansion/2             Convert term before compilation
  5538. term_to_atom/2               Convert between term and atom
  5539. time/1                      Determine time needed to execute goal
  5540. time_file/2                 Get last modification time of file
  5541. told/0                      Close current output
  5542. trace/0                     Start the tracer
  5543. tracing/0                   Query status of the tracer
  5544. trim_stacks/0                Release unused memory resources
  5545. true/0                      Succeed
  5546. tty_fold/2                  Make terminal fold long lines in output
  5547. tty_get_capability/3         Get terminal parameter
  5548. tty_goto/2                  Goto position on screen
  5549. tty_put/2                   Write control string to terminal
  5550. ttyflush/0                  Flush output on terminal
  5551. union/3                     Union of two sets
  5552. unknown/2                   Trap undefined predicates
  5553. unsetenv/1                  Delete Unix environment variable
  5554. use_module/1                Import a module
  5555. use_module/2                Import predicates from a module
  5556. var/1                       Type check for unbound variable
  5557. visible/1                   Set ports that are visible in the tracer
  5558. wait_for_input/3             Wait for input with optional timeout
  5559. wildcard_match/2             Csh(1) style wildcard match
  5560. write/1                     Write term
  5561. write/2                     Write term to stream
  5562. write_ln/1                  Write term, followed by a newline
  5563. writef/1                    Formatted write
  5564. writef/2                    Formatted write
  5565. writeq/1                    Write term, insert quotes
  5566. writeq/2                    Write term, insert quotes on stream
  5567. xor/2                       Arithmetic:  exclusive or
  5568. |/2                         Disjunction of goals
  5569.  
  5570.                                 486
  5571.