home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / plbin.zip / pl / man / builtin.doc (.txt) next >
LaTeX Document  |  1992-10-21  |  99KB  |  2,051 lines

  1. \chapter{Built-In Predicates}
  2. .S Notation of Predicate Descriptions
  3. We have tried to keep the predicate descriptions clear and concise.
  4. First the predicate name is printed in bold face, followed by the
  5. arguments in italics.  Arguments are preceded by a `+', `--' or `?' sign.
  6. `+' indicates the argument is input to the predicate, `--' denotes output
  7. and `?' denotes `either input or output'.%
  8.     \footnote{These marks do NOT suggest instanstiation (e.g. var(+Var)).}
  9. Constructs like `op/3' refer to the predicate `op' with arity `3'.
  10. .S Consulting Prolog Source files
  11. SWI-Prolog source files normally have a suffix `\tty{.pl}'.  Specifying
  12. the suffix is optional.  All predicates that handle source files first
  13. check whether a file with suffix `\tty{.pl}' exists.  If not the plain
  14. file name is checked for existence.  Library files are specified by
  15. embedding the file name using the functor library/1.  Thus `\tty{foo}'
  16. refers to `\tty{foo.pl}' or `\tty{foo}' in the current directory, 
  17. `\tty{library(foo)}' refers to `\tty{foo.pl}' or `\tty{foo}' in one of the
  18. library directories specified by the dynamic predicate
  19. library_directory/1.
  20. SWI-Prolog recognises grammar rules as defined in \cite{Clocksin:81}.  The
  21. user may define additional compilation of the source file by defining
  22. the dynamic predicate term_expansion/2.  Transformations by this
  23. predicate overrule the systems grammar rule transformations.  It is not
  24. allowed to use assert/1, retract/1 or any other database predicate in
  25. term_expansion/2 other than for local computational purposes.%
  26.     \footnote{
  27.     It does work for consult, but makes it impossible to compile
  28.     programs into a stand alone executable (see
  29.     section~\ref{compilation})}
  30. Directives may be placed anywhere in a source file, invoking any
  31. predicate.  They are executed when encountered.  If the directive fails,
  32. a warning is printed.  Directives are specified by :-/1 or ?-/1.  There
  33. is no difference between the two.
  34. SWI-Prolog does not have a separate reconsult/1 predicate. Reconsulting
  35. is implied automatically by the fact that a file is consulted which is
  36. already loaded.
  37. .C consult 1 +File
  38. Read {\em File} as a Prolog source file.  {\em File} may be a list of
  39. files, in which case all members are consulted in turn.  {\em File} may
  40. start with the csh(1) special sequences \verb+~+, \verb+~<user>+ and
  41. \verb+$<var>+. {\em File} may also be \tty{library(Name)}, in which case
  42. the libraries are searched for a file with the specified name.  See also
  43. library_directory/1.  consult/1 may be abbreviated by just typing a
  44. number of file names in a list.  Examples:
  45. \begin{center}\begin{tabular}{ll}
  46. \tt ?- consult(load).        & \% consult `load' or `load.pl'    \\
  47. \tt ?- [library(quintus)].    & \% load Quintus compatibility library    \\
  48. \end{tabular}\end{center}
  49. .C ensure_loaded 1 +File
  50. Equivalent to consult/1, but the file is consulted only if this was not
  51. done before.  This is the recommended way to load files from other
  52. files.
  53. .C make 0
  54. Consult all source files that have been changed since they were
  55. consulted.  It checks {\em all} loaded source files: files loaded into a
  56. compiled state using {\tt pl -c ...} and files loaded using consult or
  57. one of its derivates.  make/0 is normally invoked by the edit/[0,1] and
  58. ed/[0,1] predicates.  make/0 can be combined with the compiler to speed
  59. up the development of large packages.  In this case compile the package
  60. using
  61. \begin{code}
  62. sun% pl -g make -o my_program -c file ...
  63. \end{code}
  64. If `my_program' is started it will first reconsult all source files
  65. that have changed since the compilation.
  66. .C library_directory 1 -Atom
  67. Dynamic predicate used to specify library directories.  Default
  68. \tty{.}, \tty{./lib}, \verb$~/lib/prolog$ and the system's library
  69. (in this order) are defined.  The user may add library directories
  70. using assert/1 or remove system defaults using retract/1.
  71. .C source_file 1 -File
  72. Succeeds if {\em File} was loaded using consult/1 or ensure_loaded/1.
  73. {\em File} refers to the full path name of the file (see
  74. expand_file_name/2). Source_file/1 backtracks over all loaded source
  75. files.
  76. .C source_file 2 ?Pred, ?File
  77. Is true if the predicate specified by {\em Pred} was loaded from file
  78. {\em File}, where {\em File} is an absolute path name (see
  79. expand_file_name/2).  Can be used with any instantiation pattern, but the
  80. database only maintains the source file for each predicate.  Predicates
  81. declared {\em multifile} (see multifile/1) cannot be found this way.
  82. .C term_expansion 2 +Term1, -Term2
  83. Dynamic predicate, normally not defined.  When defined by the user all
  84. terms read during consulting that are given to this predicate.  If the
  85. predicate succeeds Prolog will assert {\em Term2} in the database rather
  86. then the read term ({\em Term1}).  {\em Term2} may be a term of a the
  87. form `?- {\em Goal}' or `:- {\em Goal}'.  {\em Goal} is then treated as
  88. a directive.  {\em Term2} may also be a list, in which case all terms of
  89. the list are stored in the database or called (for directives).  See
  90. also expand_term/2.
  91. .C expand_term 2 +Term1, -Term2
  92. This predicate is normally called by the compiler to perform preprocessing.
  93. First it calls term_expansion/2.  If this predicate fails it performs
  94. a grammar-rule translation.  If this fails it returns the first argument.
  95. .C compiling 0
  96. Succeeds if the system is compiling source files with the \tty{-c}
  97. option into an intermediate code file.  Can be used to perform code
  98. optimisations in expand_term/2 under this condition.
  99. .C preprocessor 2 -Old, +New
  100. Read the input file via a Unix process that acts as preprocessor. A
  101. preprocessor is specified as an atom. The first occurrence of the string
  102. `\verb+%f+' is replaced by the name of the file to be loaded. The
  103. resulting atom is called as a Unix command and the standard output of
  104. this command is loaded. To use the Unix C preprocessor one should
  105. define:
  106. \begin{code}
  107. ?- preprocessor(Old, '/lib/cpp -C -P %f'), consult(...).
  108. Old = none
  109. \end{code}
  110. .S Listing Predicates and Editor Interface
  111. \label{listing}
  112. SWI-Prolog offers an interface to the Unix {\em vi} editor (vi(1)),
  113. Richard O'Keefe's {\em top} editor \cite{TOP:manual} and the GNU-EMACS
  114. invocations {\tt emacs} and {\tt emacsclient}.  Which editor is
  115. used is determined by the Unix environment variable \tty{EDITOR}, which
  116. should hold the full pathname of the editor.  If this variable is not
  117. defined, vi(1) is used.
  118. After the user quits the editor make/0 is invoked to reload all modified
  119. source files using consult/1.  If the editor can be quit such that an
  120. exit status non-equal to 0 is returned make/0 will not be invoked.  {\em
  121. top} can do this by typing control-C, {\em vi} cannot do this.
  122. A predicate specification is either a term with the same functor and arity
  123. as the predicate wanted, a term of the form \tty{Functor/Arity} or a
  124. single atom.  In the latter case the database is searched for a
  125. predicate of this name and arbitrary arity (see current_predicate/2).
  126. When more than one such predicate exists the system will prompt for
  127. confirmation on each of the matched predicates. Predicates specifications
  128. are given to the `Do What I Mean' system (see dwim_predicate/2) if the
  129. requested predicate does not exist.
  130. .C ed 1 +Pred
  131. Invoke the user's preferred editor on the source file of {\em Pred}, 
  132. providing a search specification which searches for the predicate at
  133. the start of a line.
  134. .C ed 0
  135. Invoke ed/1 on the predicate last edited using ed/1.  Asks the user to
  136. confirm before starting the editor.
  137. .C edit 1 +File
  138. Invoke the user's preferred editor on {\em File}.  {\em File} is a file
  139. specification as for consult/1 (but not a list).  Note that the file
  140. should exist.
  141. .C edit 0
  142. Invoke edit/1 on the file last edited using edit/1.  Asks the user to
  143. confirm before starting the editor.
  144. .C listing 1 +Pred
  145. List specified predicates (when an atom is given all predicates with
  146. this name will be listed).  The listing is produced on the basis of the
  147. internal representation, thus loosing user's layout and variable name
  148. information.  See also portray_clause/1.
  149. .C listing 0
  150. List all predicates of the database using listing/1.
  151. .C portray_clause 1 +Clause
  152. Pretty print a clause as good as we can.  A clause should be specified
  153. as a term `\tty{Head :- Body}' (put brackets around it to avoid operator
  154. precedence problems).  Facts are represented as `\tty{Head :- true}'.
  155. .S Verify Type of a Term
  156. .C var 1 +Term
  157. Succeeds if {\em Term} currently is a free variable.
  158. .C nonvar 1 +Term
  159. Succeeds if {\em Term} currently is not a free variable.
  160. .C integer 1 +Term
  161. Succeeds if {\em Term} is bound to an integer.
  162. .C float 1 +Term
  163. Succeeds if {\em Term} is bound to a floating point number.
  164. .C number 1 +Term
  165. Succeeds if {\em Term} is bound to an integer or a floating point number.
  166. .C atom 1 +Term
  167. Succeeds if {\em Term} is bound to an atom.
  168. .C string 1 +Term
  169. Succeeds if {\em Term} is bound to a string.
  170. .C atomic 1 +Term
  171. Succeeds if {\em Term} is bound to an atom, string, integer or floating
  172. point number.
  173. .C ground 1 +Term
  174. Succeeds if {\em Term} holds no free variables.
  175. .S Comparison and Unification or Terms
  176. \label{sec:compare}
  177. \subsection*{Standard Order of Terms}
  178. Comparison and unification of arbitrary terms. Terms are ordered in the
  179. so called ``standard order''. This order is defined as follows:
  180. \begin{enumerate}
  181. \setlength{\itemsep}{-2pt}
  182.     \item ${\it Variables} < {\it Atoms} < {\it Strings}%
  183.     \footnote{Strings might be considered atoms in future versions. See
  184.           also section~\ref{sec:strings}}
  185.       < {\it Numbers} < {\it Terms}$
  186.     \item $\it Old~Variable < New~Variable$%
  187.     \footnote{In fact the variables are compared on their (dereferenced)
  188.           addresses. Variables living on the global stack are always
  189.           $<$ than variables on the local stack.  Programs
  190.           should not rely on the order in which variables are sorted.}
  191.     \item {\it Atoms} are compared alphabetically.
  192.     \item {\it Strings} are compared alphabetically.
  193.     \item {\it Numbers} are compared by value. Integers and floats are
  194.           treated identically.
  195.     \item {\it Terms} are first checked on their functor
  196.       (alphabetically), then on their arity and finally recursively on
  197.       their arguments, left most argument first.    
  198. \end{enumerate}
  199. .IT +Term1 == +Term2
  200. Succeeds if {\em Term1} is equivalent to {\em Term2}. A variable is only
  201. identical to a sharing variable.
  202. .IT +Term1 \== +Term2
  203. Equivalent to `\verb@\+ Term1 == Term2@'.
  204. .IT +Term1 = +Term2
  205. Unify {\em Term1} with {\em Term2}. Succeeds if the unification succeeds.
  206. .IT +Term1 \= +Term2
  207. Equivalent to `\verb@\+ Term1 = Term2@'.
  208. .IT +Term1 =@= +Term2
  209. Succeeds if {\em Term1} is `structurally equal' to {\em Term2}.
  210. Structural equivalence is weaker than equivalence ({\tt ==}/2), but
  211. stronger than unification ({\tt =}/2).  Two terms are structurally equal if
  212. their tree representation is identical and they have the same `pattern'
  213. of variables.  Examples:
  214. \begin{quote}
  215. \begin{tabular}{r@{ \tt=@= }lc}
  216. \tt a        & \tt        A     & false \\
  217. \tt A        & \tt        B    & true \\
  218. \tt x(A,A)    & \tt        x(B,C)    & false \\
  219. \tt x(A,A)    & \tt        x(B,B)    & true \\
  220. \tt x(A,B)    & \tt        x(C,D)    & true \\
  221. \end{tabular}
  222. \end{quote}
  223. .IT +Term1 \=@= +Term2
  224. Equivalent to \verb$`\+ Term1 =@= Term2'$.
  225. .IT +Term1 @< +Term2
  226. Succeeds if {\em Term1} is before {\em Term2} in the standard order of terms.
  227. .IT +Term1 @=< +Term2
  228. Succeeds if both terms are equal ({\tt ==}) or {\em Term1} is before {\em Term2} in
  229. the standard order of terms.
  230. .IT +Term1 @> +Term2
  231. Succeeds if {\em Term1} is after {\em Term2} in the standard order of terms.
  232. .IT +Term1 @>= +Term2
  233. Succeeds if both terms are equal ({\tt ==}) or {\em Term1} is after {\em Term2} in
  234. the standard order of terms.
  235. .S Control Predicates
  236. The predicates of this section implement control structures.  Normally
  237. these constructs are translated into virtual machine instructions by
  238. the compiler.  It is still necessary to implement these constructs
  239. as true predicates to support meta-calls, as demonstrated in the
  240. example below. The predicate finds all currently defined atoms of 1
  241. character long. Note that the cut has no effect when called via one
  242. of these predicates (see !/0).
  243. \begin{code}
  244. one_character_atoms(As) :-
  245.     findall(A, (current_atom(A), atom_length(A, 1)), As).
  246. \end{code}
  247. .C fail 0
  248. Always fail.
  249. .C true 0
  250. Always succeed.
  251. .C repeat 0
  252. Always succeed, provide an infinite number of choice points.
  253. .C ! 0
  254. Cut.  Discard choice points of parent frame and frames created after the
  255. parent frame.  Note that the control structures \verb$;/2$, \verb$|/2$
  256. \verb$->/2$ and \verb$\+/1$ are normally handled by the compiler and do
  257. not create a frame, which implies the cut operates through these
  258. predicates.  Some examples are given below.  Note the difference between
  259. t3/1 and t4/1.  Also note the effect of call/1 in t5/0.  As the argument
  260. of call/1 is evaluated by predicates rather than the compiler the cut
  261. has no effect.%
  262.     \footnote{Version 1.2 did not compile \verb$;/2$, etc.. To make the
  263.           cut work a special predicate attribute called `cut_parent'
  264.           was introduced. This implied the cut had effect in all the
  265.           examples.  The current implementation is much neater and
  266.           considerably faster.}
  267. \begin{center}\begin{tabular}{ll}
  268. \tt t1 :- (a, !, fail ; b).          & \% cuts a/0 and t1/0 \\
  269. \tt t2 :- (a -> b, ! ; c).           & \% cuts b/0 and t2/0 \\
  270. \tt t3(G) :- a, G, fail.         & \% if `G = !' cuts a/0 and t1/1 \\
  271. \tt t4(G) :- a, call(G), fail.       & \% if `G = !' cut has no effect \\
  272. \tt t5 :- call((a, !, fail ; b)).    & \% Cut has no effect \\
  273. \tt t6 :- \verb$\+$ (a, !, fail ; b).& \% cuts a/0 and t6/0 \\
  274. \end{tabular}\end{center}
  275. .I +Goal1 , +Goal2
  276. Conjunction.  Succeeds if both `Goal1' and `Goal2' can be proved.  It is
  277. defined as (this definition does not lead to a loop as the second comma
  278. is handled by the compiler):
  279. \begin{code}
  280. Goal1, Goal2 :- Goal1, Goal2.
  281. \end{code}
  282. .I +Goal1 ; +Goal2
  283. The `or' predicate is defined as:
  284. \begin{code}
  285. Goal1 ; _Goal2 :- Goal1.
  286. _Goal1 ; Goal2 :- Goal2.
  287. \end{code}
  288. .IT +Goal1 | +Goal2
  289. Equivalent to \tty{;/2}.  Retained for compatibility only.  New code
  290. should use \verb$;/2$.
  291. .IT +Condition -> +Action
  292. If-then and If-Then-Else. Implemented as:
  293. \begin{code}
  294. If -> Then; _Else :- If, !, Then.
  295. If -> _Then; Else :- !, Else.
  296. If -> Then :- If, !, Then.
  297. \end{code}
  298. .PT \+ +Goal
  299. Succeeds if `Goal' cannot be proven (mnemnonic: + refers to {\em provable}
  300. and the backslash is normally used to indicate negation).
  301. .S Meta-Call Predicates
  302. \label{sec:metacall}
  303. Meta call predicates are used to call terms constructed at run time.
  304. The basic meta-call mechanism offered by SWI-Prolog is to use
  305. variables as a subclause (which should of course be bound to a valid
  306. goal at runtime).  A meta-call is slower than a normal call as it
  307. involves actually searching the database at runtime for the predicate,
  308. while for normal calls this search is done at compile time.
  309. .C call 1 +Goal
  310. Invoke {\em Goal} as a goal. Note that clauses may have variables as
  311. subclauses, which is identical to call/1, except when the argument is
  312. bound to the cut. See !/0.
  313. .C apply 2 +Term, +List
  314. Append the members of {\em List} to the arguments of {\em Term} and call the
  315. resulting term. For example: `\tty{apply(plus(1), [2, X])}' will call
  316. `\tty{plus(1, 2, X)}'. Apply/2 is incorporated in the virtual machine of
  317. SWI-Prolog. This implies that the overhead can be compared to the
  318. overhead of call/1.
  319. .P not +Goal
  320. Succeeds when {\em Goal} cannot be proven.  Retained for compatibility
  321. only. New code should use \verb$\+/1$.
  322. .C once 1 +Goal
  323. Defined as:
  324. \begin{code}
  325. once(Goal) :-
  326.     Goal, !.
  327. \end{code}
  328. Once/1 can in many cases be replaced with \verb$->/2$. The only
  329. difference is how the cut behaves (see !/0). The following two clauses
  330. are identical:
  331. \begin{code}
  332. 1) a :- once((b, c)), d.
  333. 2) a :- b, c -> d.
  334. \end{code}
  335. .C ignore 1 +Goal
  336. Calls {\em Goal} as once/1, but succeeds, regardless of whether {\em
  337. Goal} succeeded or not.  Defined as:
  338. \begin{code}
  339. ignore(Goal) :-
  340.     Goal, !.
  341. ignore(_).
  342. \end{code}
  343. .S Database
  344. SWI-Prolog offers three different database mechanisms. The first one is
  345. the common assert/retract mechanism for manipulating the clause
  346. database. As facts and clauses asserted using assert/1 or one of it's
  347. derivates become part of the program these predicates compile the term
  348. given to them. Retract/1 and retractall/1 have to unify a term and
  349. therefore have to decompile the program. For these reasons the
  350. assert/retract mechanism is expensive. On the other hand, once compiled, 
  351. queries to the database are faster than querying the recorded database
  352. discussed below.  See also dynamic/1.
  353. The second way of storing arbitrary terms in the database is using the
  354. ``recorded database''. In this database terms are associated with a
  355. {\em key}. A key can be an atom, integer or term. In the last case
  356. only the functor and arity determine the key. Each key has a chain of
  357. terms associated with it. New terms can be added either at the head or
  358. at the tail of this chain. This mechanism is considerably faster than
  359. the assert/retract mechanism as terms are not compiled, but just copied
  360. into the heap.
  361. The third mechanism is a special purpose one.  It associates an integer
  362. or atom with a key, which is an atom, integer or term.  Each key can
  363. only have one atom or integer associated with it.  It again is
  364. considerably faster than the mechanisms described above, but can only be
  365. used to store simple status information like counters, etc.
  366. .C abolish 2 +Functor, +Arity
  367. Removes all clauses of a predicate with functor {\em Functor} and arity
  368. {\em Arity} from the database.  Unlike version 1.2, all predicate attributes
  369. (dynamic, multifile, index, etc.) are reset to their defaults.  Abolishing
  370. an imported predicate only removes the import link; the predicate
  371. will keep its old definition in its definition module.  For `cleanup' of
  372. the dynamic database, one should use retractall/1 rather than abolish/2.
  373. .C retract 1 +Term
  374. When {\em Term} is an atom or a term it is unified with the first unifying
  375. fact or clause in the database. The fact or clause is removed from the
  376. database.
  377. .C retractall 1 +Term
  378. All facts or clauses in the database that unify with {\em Term} are
  379. removed.
  380. .C assert 1 +Term
  381. Assert a fact or clause in the database. {\em Term} is asserted as the last
  382. fact or clause of the corresponding predicate.
  383. .C asserta 1 +Term
  384. Equivalent to assert/1, but {\em Term} is asserted as first clause or fact
  385. of the predicate.
  386. .C assertz 1 +Term
  387. Equivalent to assert/1.
  388. .C assert 2 +Term, -Reference
  389. Equivalent to assert/1, but {\em Reference} is unified with a unique
  390. reference to the asserted clause. This key can later be used with
  391. clause/3 or erase/1.
  392. .C asserta 2 +Term, -Reference
  393. Equivalent to assert/2, but {\em Term} is asserted as first clause or fact
  394. of the predicate.
  395. .C assertz 2 +Term, -Reference
  396. Equivalent to assert/2.
  397. .C recorda 3 +Key, +Term, -Reference
  398. Assert {\em Term} in the recorded database under key {\em Key}. {\em Key} is an
  399. integer, atom or term. {\em Reference} is unified with a unique reference
  400. to the record (see erase/1).
  401. .C recorda 2 +Key, +Term
  402. Equivalent to \tty{recorda(Key, Value, _)}.
  403. .C recordz 3 +Key, +Term, -Reference
  404. Equivalent to recorda/3, but puts the {\em Term} at the tail of the terms
  405. recorded under {\em Key}.
  406. .C recordz 2 +Key, +Term
  407. Equivalent to \tty{recordz(Key, Value, _)}.
  408. .C recorded 3 +Key, -Value, -Reference
  409. Unify {\em Value} with the first term recorded under {\em Key} which does
  410. unify. {\em Reference} is unified with the memory location of the record.
  411. .C recorded 2 +Key, -Value
  412. Equivalent to \tty{recorded(Key, Value, _)}.
  413. .C erase 1 +Reference
  414. Erase a record or clause from the database.  {\em Reference} is an
  415. integer returned by recorda/3 or recorded/3, clause/3, assert/2,
  416. asserta/2 or assertz/2.  Other integers might conflict with the internal
  417. consistency of the system.  Erase can only be called once on a record or
  418. clause.  A second call also might conflict with the internal consistency
  419. of the system.%
  420. \bug{The system should have a special type for pointers, thus avoiding
  421. the Prolog user having to worry about consistency matters. Currently some
  422. simple heuristics are used to determine whether a reference is valid.}
  423. .C flag 3 +Key, -Old, +New
  424. {\em Key} is an atom, integer or term.  Unify {\em Old} with the old
  425. value associated with {\em Key}.  If the key is used for the first time
  426. {\em Old} is unified with the integer 0.  Then store the value of {\em
  427. New}, which should be an integer, atom or arithmetic integer
  428. expression, under {\em Key}.  flag/3 is a very fast mechanism for
  429. storing simple facts in the database.  Example:
  430. \begin{code}
  431. :- module_transparent succeeds_n_times/2.
  432. succeeds_n_times(Goal, Times) :-
  433.     flag(succeeds_n_times, _, 0),
  434.     Goal,
  435.     flag(succeeds_n_times, N, N+1),
  436.     fail ; flag(succeeds_n_times, Times, Times).
  437. \end{code}
  438. .S Declaring Properties of Predicates
  439. \label{ch:dynamic}
  440. \label{sec:declare}
  441. This section describes directives which manipulate attributes of
  442. predicate definitions.  The functors dynamic/1, multifile/1 and
  443. discontiguous/1 are operators of priority 1150 (see op/3), which
  444. implies the list of predicates they involve can just be a comma
  445. separated list: 
  446. \begin{code}
  447. :- dynamic
  448.         foo/0, 
  449.         baz/2.
  450. \end{code}
  451. On SWI-Prolog all these directives are just predicates. This implies
  452. they can also be called by a program.  Do not rely on this feature if
  453. you want to maintain portability to other Prolog implementations.
  454. .P dynamic +Functor/+Arity, ...
  455. Informs the interpreter that the definition of the predicate(s) may change
  456. during execution (using assert/1 and/or retract/1).  Currently dynamic/1
  457. only stops the interpreter from complaining about undefined predicates (see
  458. unknown/2).  Future releases might prohibit assert/1 and retract/1 for
  459. not-dynamic declared procedures.
  460. .P multifile +Functor/+Arity, ...
  461. Informs the system that the specified predicate(s) may be defined over
  462. more than one file. This stops consult/1 from redefining a predicate
  463. when a new definition is found.
  464. .P discontiguous +Functor/+Arity, ...
  465. Informs the system that the clauses of the specified predicate(s) might
  466. not be together in the source file.  See also style_check/1.
  467. .C index 1 +Head
  468. Index the clauses of the predicate with the same name and arity as {\em
  469. Head} on the specified arguments. {\em Head} is a term of which all
  470. arguments are either `1' (denoting `index this argument') or `0'
  471. (denoting `do not index this argument'). Indexing has no implications
  472. for the semantics of a predicate, only on its performance. If indexing
  473. is enabled on a predicate a special purpose algorithm is used to select
  474. candidate clauses based on the actual arguments of the goal. This
  475. algorithm checks whether indexed arguments might unify in the clause
  476. head. Only atoms, integers and functors (e.g. name and arity of a term)
  477. are considered. Indexing is very useful for predicates with many
  478. clauses representing facts.
  479. Due to the representation technique used at most 4 arguments can be
  480. indexed. All indexed arguments should  be in the first 32 arguments of
  481. the predicate. If more than 4 arguments are specified for indexing only
  482. the first 4 will be accepted. Arguments above 32 are ignored for indexing.
  483. By default all predicates with ${\rm arity} \ge 1$ are indexed on their
  484. first argument.  It is possible to redefine indexing on predicates that
  485. already have clauses attached to them.  This will initiate a scan
  486. through the predicate's clause list to update the index summary
  487. information stored with each clause.
  488. If --for example-- one wants to represents sub-types using a fact list
  489. \mbox{`sub_type(Sub, Super)'} that should be used both to determine sub- and
  490. super types one should declare sub_type/2 as follows:
  491. \begin{boxed}
  492. \begin{code}
  493. :- index(sub_type(1, 1)).
  494. sub_type(horse, animal).
  495. \end{code}
  496. \end{boxed}
  497. .S Examining the Program
  498. .C current_atom 1 -Atom
  499. Successively unifies {\em Atom} with all atoms known to the system.
  500. Note that current_atom/1 always succeeds if {\em Atom} is intantiated to
  501. an atom.
  502. .C current_functor 1 ?Name, ?Arity
  503. Successively unifies {\em Name} with the name and {\em Arity} with the
  504. arity of functors known to the system.
  505. .C current_flag 1 -FlagKey
  506. Successively unifies {\em FlagKey} with all keys used for flags (see
  507. flag/3).
  508. .C current_key 1 -Key
  509. Successively unifies {\em Key} with all keys used for records (see
  510. recorda/3, etc.).
  511. .C current_predicate 2 ?Name, ?Head
  512. Successively unifies {\em Name} with the name of predicates currently
  513. defined and {\em Head} with the most general term built from {\em
  514. Name} and the arity of the predicate.  This predicate succeeds for all
  515. predicates defined in the specified module, imported to it, or in one
  516. of the modules from which the predicate will be imported if it is
  517. called.
  518. .C predicate_property 2 ?Head, ?Property
  519. Succeeds if {\em Head} refers to a predicate that has property {\em
  520. Property}. Can be used to test whether a predicate has a certain
  521. property, obtain all properties known for {\em Head}, find all
  522. predicates having {\em property} or even obtaining all information
  523. available about the current program. {\em Property} is one of:
  524. \begin{description}
  525.     \item[interpreted]\mbox{}\\
  526. Is true if the predicate is defined in Prolog. We return true on this
  527. because, although the code is actually compiled, it is completely
  528. transparent, just like interpreted code.
  529.     \item[built_in]\mbox{}\\
  530. Is true if the predicate is locked as a built-in predicate. This
  531. implies it cannot be redefined in it's definition module and it can
  532. normally not be seen in the tracer.
  533.     \item[foreign]\mbox{}\\
  534. Is true if the predicate is defined in the C language.
  535.     \item[dynamic]\mbox{}\\
  536. Is true if the predicate is declared dynamic using the dynamic/1
  537. declaration.
  538.     \item[multifile]\mbox{}\\
  539. Is true if the predicate is declared multifile using the multifile/1
  540. declaration.
  541.     \item[undefined]\mbox{}\\
  542. Is true if a procedure definition block for the predicate exists, 
  543. but there are no clauses in it and it is not declared dynamic. This is
  544. true if the predicate occurs in the body of a loaded predicate, an
  545. attempt to call it has been made via one of the meta-call predicates or
  546. the predicate had a definition in the past.  See the library package
  547. {\em check} for example usage.
  548.     \item[transparent]\mbox{}\\
  549. Is true if the predicate is declared transparent using the
  550. module_transparent/1 declaration.
  551.     \item[exported]\mbox{}\\
  552. Is true if the predicate is in the public list of the context module.
  553.     \item[imported_from({\em Module})]\mbox{}\\
  554. Is true if the predicate is imported into the context module from
  555. module {\em Module}.
  556.     \item[indexed({\em Head})]\mbox{}\\
  557. Predicate is indexed (see index/1) according to {\em Head}. {\em Head}
  558. is a term whose name and arity are identical to the predicate. The
  559. arguments are unified with `1' for indexed arguments, `0' otherwise.
  560. \end{description}
  561. .C dwim_predicate 2 +Term, -Dwim
  562. `Do What I Mean' (`dwim') support predicate. {\em Term} is a term, 
  563. which name and arity are used as a predicate specification.  {\em Dwim}
  564. is instantiated with the most general term built from {\em Name} and the
  565. arity of a defined predicate that matches the predicate specified by
  566. {\em Term} in the `Do What I Mean' sence.  See dwim_match/2 for `Do
  567. What I Mean' string matching.  Internal system predicates are
  568. not generated, unless \mbox{style_check(+dollar)} is active.  Backtracking
  569. provides all alternative matches.
  570. .C clause 2 ?Head, ?Body
  571. Succeeds when {\em Head} can be unified with a clause head and {\em
  572. Body} with the corresponding clause body.  Gives alternative clauses on
  573. backtracking.  For facts {\em Body} is unified with the atom {\em true}.
  574. Normally clause/2 is used to find clause definitions for a predicate, but it
  575. can also be used to find clause heads for some body template.
  576. .C clause 3 ?Head, ?Body, ?Reference
  577. Equivalent to clause/2, but unifies {\em Reference} with a unique reference to
  578. the clause (see also assert/2, erase/1). If {\em Reference} is instantiated
  579. to a reference the clause's head and body will be unified with {\em
  580. Head} and {\em Body}.
  581. .S Input and Output
  582. SWI-Prolog provides two different packages for input and output.  One
  583. confirms to the Edinburgh standard.  This package has a notion of
  584. `current-input' and `current-output'.  The reading and writing
  585. predicates implicitely refer to these streams.  In the second package,
  586. streams are opened explicitely and the resulting handle is used as
  587. an argument to the reading and writing predicate to specify the source
  588. or destination.  Both packages are fully integrated; the user may
  589. switch freely between them.
  590. .SS Input and Output Using Implicit Source and Destination
  591. The package for implicit input and output destination is upwards
  592. compatible to DEC-10 and C-Prolog.  The reading and writing predicates
  593. refer to resp.  the current input- and output stream.  Initially these
  594. streams are connected to the terminal.  The current output stream is
  595. changed using tell/1 or append/1.  The current input stream is changed
  596. using see/1.  The stream's current value can be obtained using telling/1
  597. for output- and seeing/1 for input streams.  The table below shows the
  598. valid stream specifications.  The reserved names \tty{user_input},
  599. \tty{user_output} and \tty{user_error} are for neat integration with
  600. the explicit streams.
  601. \begin{center}
  602. \begin{tabular}{|l|p{3in}|}
  603. \hline
  604. \tt user        & This reserved name refers to the terminal \\
  605. \tt user_input        & Input from the terminal \\
  606. \tt user_output        & Output to the terminal \\
  607. \tt stderr or user_error& Unix error stream (output only) \\
  608. \em Atom        & Name of a Unix file \\
  609. \tt pipe({\em Atom})    & Name of a Unix command \\
  610. \hline
  611. \end{tabular}
  612. \end{center}
  613. Source and destination are either a file, one of the reserved words
  614. above, or a term `pipe({\em Command})'.  In the predicate descriptions
  615. below we will call the source/destination argument `{\em SrcDest}'.
  616. Below are some examples of source/destination specifications.
  617. \begin{center}\begin{tabular}{ll}
  618. \tt ?- see(data).    & \% Start reading from file `data'. \\
  619. \tt ?- tell(stderr).    & \% Start writing on the error stream. \\
  620. \tt ?- tell(pipe(lpr)).    & \% Start writing to the printer.
  621. \end{tabular}\end{center}
  622. Another example of using the pipe/1 construct is shown on in
  623. figure~\ref{fig:getwd}.  Note that the pipe/1 construct is not part of
  624. Prolog's standard I/O reportoire.
  625. \begin{figure}
  626. \begin{boxed}\begin{code}
  627. getwd(Wd) :-
  628.     seeing(Old), see(pipe(pwd)), 
  629.     collect_wd(String), 
  630.     seen, see(Old), 
  631.     name(Wd, String).
  632. collect_wd([C|R]) :-
  633.     get0(C), C \== -1, !, 
  634.     collect_wd(R).
  635. collect_wd([]).
  636. \end{code}\end{boxed}
  637.     \caption{Get the working directory}
  638.     \label{fig:getwd}
  639. \end{figure}
  640. .C see 1 +SrcDest
  641. Make {\em SrcDest} the current input stream.  If {\em SrcDest} was already opened for
  642. reading with see/1 and has not been closed since, reading will be
  643. resumed.  Otherwise {\em SrcDest} will be opened and the file pointer is
  644. positioned at the start of the file.
  645. .C tell 1 +SrcDest
  646. Make {\em SrcDest} the current output stream.  If {\em SrcDest} was already opened for
  647. writing with tell/1 or append/1 and has not been closed since, writing
  648. will be resumed.  Otherwise the file is created or --when existing--
  649. truncated. See also append/1.
  650. .C append 1 +File
  651. Similar to tell/1, but positions the file pointer at the end of {\em File}
  652. rather than truncating an existing file. The pipe construct is not
  653. accepted by this predicate.
  654. .C seeing 1 -SrcDest
  655. Unify the name of the current input stream with {\em SrcDest}.
  656. .C telling 1 -SrcDest
  657. Unify the name of the current output stream with {\em SrcDest}.
  658. .C seen 0
  659. Close the current input stream. The new input stream becomes
  660. {\em user}.
  661. .C told 0
  662. Close the current output stream. The new output stream becomes
  663. {\em user}.
  664. .SS Explicit Input and Output Streams
  665. The predicates below are part of the Quintus compatible stream-based
  666. I/O package.  In this package streams are explicitely created using the
  667. predicate open/3.  The resulting stream identifier is then passed as a
  668. parameter to the reading and writing predicates to specify the source
  669. or destination of the data.
  670. .C open 3 +SrcDest, +Mode, ?Stream
  671. {\em SrcDest} is either an atom, specifying a Unix file, or a term
  672. `pipe({\em Command})', just like see/1 and tell/1.  {\em Mode} is one
  673. of \tty{read}, \tty{write} or \tty{append}.  {\em Stream} is either a
  674. variable, in which case it is bound to a small integer identifying the
  675. stream, or an atom, in which case this atom will be the stream
  676. indentifier.  In the latter case the atom cannot be an already existing
  677. stream identifier.  Examples:
  678. \begin{center}\begin{tabular}{ll}
  679. \tt ?- open(data, read, Stream).     & \% Open `data' for reading. \\
  680. \tt ?- open(pipe(lpr), write, printer).    & \% `printer' is a stream to `lpr'. \\
  681. \end{tabular}\end{center}
  682. .C open_null_stream 1 ?Stream
  683. On Unix systems, this is  equivalent  to  \tty{open('/dev/null',  write,
  684. Stream)}.   Characters  written  to this stream are lost, but the stream
  685. information (see character_count/2, etc.) is maintained.
  686. .C close 1 +Stream
  687. Close the specified stream.  If {\em Stream} is not open an error
  688. message is displayed.  If the closed stream is the current input or
  689. output stream the terminal is made the current input or output.
  690. .C current_stream 3 ?File, ?Mode, ?Stream
  691. Is true if a stream with file specification {\em File}, mode {\em Mode}
  692. and stream identifier {\em Stream} is open.  The reserved streams {\em
  693. user} and {\em user_error} are not generated by this predicate.  If a
  694. stream has been opened with mode \tty{append} this predicate will
  695. generate mode {\em write}.
  696. .C stream_position 3 +Stream, -Old, +New
  697. Unify the position parameters of {\em Stream} with {\em Old} and set them to
  698. {\em New}.  A position is represented by the following term:
  699. \begin{code}
  700. '$stream_position'(CharNo, LineNo, LinePos).
  701. \end{code}
  702. It is only possible to change the position parameters if the stream is
  703. connected to a disk file.
  704. .SS Switching Between Implicit and Explicit I/O
  705. The predicates below can be used for switching between the implicit-
  706. and the explicit stream based I/O predicates.
  707. .C set_input 1 +Stream
  708. Set the current input stream to become {\em Stream}.  Thus, open(file,
  709. read, Stream), set_input(Stream) is equivalent to see(file).
  710. .C set_output 1 +Stream
  711. Set the current output stream to become {\em Stream}.
  712. .C current_input 1 -Stream
  713. Get the current input stream.  Useful to get access to the status
  714. predicates associated with streams.
  715. .C current_output 1 -Stream
  716. Get the current output stream.
  717. .S Status of Input and Output Streams
  718. .C wait_for_input 3 +ListOfStreams, -ReadyList, +TimeOut
  719. Wait for input on one of the streams in {\em ListOfStreams} and return
  720. a list of streams on which input is available in {\em ReadyList}.
  721. wait_for_input/3 waits for at most {\em TimeOut} seconds.  {\em
  722. Timeout} may be specified as a floating point number to specify
  723. fractions of a second. If {\em Timeout} equals 0, wait_for_input/3
  724. waits indefinetely.  This predicate can be used to implement
  725. timeout while reading and to handle input from multiple sources. The
  726. following example will wait for input from the user and an
  727. explicitely opened second terminal.  On return, {\em Inputs} may hold
  728. \tty{user} or {\em P4} or both.
  729. \begin{code}
  730. ?- open('/dev/ttyp4', read, P4),
  731.    wait_for_input([user, P4], Inputs, 0).
  732. \end{code}
  733. .C character_count 2 +Stream, -Count
  734. Unify {\em Count} with the current character index.  For input streams
  735. this is the number of characters read since the open, for output
  736. streams this is the number of characters written. Counting starts at 0.
  737. .C line_count 2 +Stream, -Count
  738. Unify {\em Count} with the number of lines read or written.  Counting
  739. starts at 1.
  740. .C line_position 2 +Stream, -Count
  741. Unify {\em Count} with the position on the current line. Note that this
  742. assumes the position is 0 after the open.  Tabs are assumed to be
  743. defined on each 8-th character and backspaces are assumed to reduce the
  744. count by one, provided it is positive.
  745. .C fileerrors 2 -Old, +New
  746. Define error behaviour on errors when opening a file for reading or
  747. writing. Valid values are the atoms \tty{on} (default) and \tty{off}.
  748. First {\em Old} is unified with the current value. Then the new value is
  749. set to {\em New}.%
  750.     \footnote{Note that Edinburgh Prolog defines fileerrors/0 and
  751.           nofileerrors/0.  As this does not allow you to switch back
  752.           to the old mode I think this definition is better.}
  753. .C tty_fold 2 -OldColumn, +NewColumn
  754. Fold Prolog output to stream {\em user} on column {\em NewColumn}.  If {\em
  755. Column} is 0 or less no folding is performed (default).  {\em
  756. OldColumn} is first unified with the current folding column. To be
  757. used on terminals that do not support line folding. 
  758. .S Primitive Character Input and Output
  759. .C nl 0
  760. Write a newline character to the current output stream.  On Unix systems
  761. {\em nl/0} is equivalent to \tty{put(10)}.
  762. .C nl 1 +Stream
  763. Write a newline to {\em Stream}.
  764. .C put 1 +Char
  765. Write {\em Char} to the current output stream, {\em Char} is either an
  766. integer-expression evaluating to an ASCII value ($0 \leq {\em Char}
  767. \leq 255$) or an atom of one character.
  768. .C put 2 +Stream, +Char
  769. Write {\em Char} to {\em Stream}.
  770. .C tab 1 +Amount
  771. Writes {\em Amount} spaces on the current output stream.  {\em Amount}
  772. should be an expression that evaluates to a positive integer (see
  773. section~\ref{sec:arith}).
  774. .C tab 2 +Stream, +Amount
  775. Writes {\em Amount} spaces to {\em Stream}.
  776. .C flush 0
  777. Flush pending output on current output stream.  flush/0 is automatically
  778. generated by read/1 and derivates if the current input stream is {\em
  779. user} and the cursor is not at the left margin.
  780. .C flush_output 1 +Stream
  781. Flush output on the specified stream.  The stream must be open for
  782. writing.
  783. .C ttyflush 0
  784. Flush pending output on stream {\em user}. See also flush/0.
  785. .C get0 1 -Char
  786. Read the current input stream and unify the next character with {\em Char}.
  787. {\em Char} is unified with -1 on end of file.
  788. .C get0 2 +Stream, -Char
  789. Read the next character from {\em Stream}.
  790. .C get 1 -Char
  791. Read the current input stream and unify the next non-blank character
  792. with {\em Char}. {\em Char} is unified with -1 on end of file.
  793. .C get 2 +Stream, -Char
  794. Read the next non-blank character from {\em Stream}.
  795. .C get_single_char 1 -Char
  796. Get a single character from input stream `user' (regardless of the
  797. current input stream). Unlike get0/1 this predicate does not wait for a
  798. return. The character is not echoed to the user's terminal. This
  799. predicate is meant for keyboard menu selection etc.. If SWI-Prolog was
  800. started with the \verb$-tty$ flag this predicate reads an entire line of
  801. input and returns the first non-blank character on this line, or the
  802. ASCII code of the newline (10) if the entire line consisted of blank
  803. characters.
  804. .S Term Reading and Writing
  805. .C display 1 +Term
  806. Write {\em Term} on the current output stream using standard
  807. parenthesised prefix notation (i.e. ignoring operator declarations).
  808. Display is normally used to examine the internal representation for
  809. terms holding operators.
  810. .C display 2 +Stream, +Term
  811. Display {\em Term} on {\em Stream}.
  812. .C displayq 1 +Term
  813. Write {\em Term} on the current output stream using standard
  814. parenthesised prefix notation (i.e. ignoring operator declarations).
  815. Atoms that need quotes are quoted.  Terms written with this predicate
  816. can always be read back, regardless of current operator declarations.
  817. .C displayq 2 +Stream, +Term
  818. Display {\em Term} on {\em Stream}.  Equivalent to Quintus
  819. write_canonical/2.
  820. .C write 1 +Term
  821. Write {\em Term} to the current output, using brackets and operators where
  822. appropriate.
  823. .C write 2 +Stream, +Term
  824. Write {\em Term} to {\em Stream}.
  825. .C writeq 1 +Term
  826. Write {\em Term} to the current output, using brackets and operators where
  827. appropriate. Atoms that need quotes are quoted. Terms written with this
  828. predicate can be read back with read/1 provided the currently active
  829. operator declarations are identical.
  830. .C writeq 2 +Stream, +Term
  831. Write {\em Term} to {\em Stream}, inserting quotes.
  832. .C print 1 +Term
  833. Prints {\em Term} on the current output stream similar to write/1, 
  834. but for each (sub)term of {\em Term} first the dynamic predicate
  835. portray/1 is called.  If this predicate succeeds {\em print} assumes the
  836. (sub)term has been written.  This allows for user defined term writing.
  837. .C print 2 +Stream, +Term
  838. Print {\em Term} to {\em Stream}.
  839. .C portray 1 +Term
  840. A dynamic predicate, which can be defined by the user to change the
  841. behaviour of print/1 on (sub)terms.  For each subterm encountered that
  842. is not a variable print/1 first calls portray/1 using the term as
  843. argument.  For lists only the list as a whole is given to portray/1.  If
  844. portray succeeds print/1 assumes the term has been written.
  845. .C read 1 -Term
  846. Read the next Prolog term from the current input stream and unify it
  847. with {\em Term}.  On a syntax error read/1 displays an error message, 
  848. attempts to skip the erroneous term and fails.  On reaching end-of-file
  849. {\em Term} is unified with the atom \verb+end_of_file+.
  850. .C read 2 +Stream, -Term
  851. Read {\em Term} from {\em Stream}.
  852. .C read_clause 1 -Term
  853. Equivalent to read/1, but warns the user for variables only occurring
  854. once in a term (singleton variables) which do not start with an
  855. underscore if \tty{style_check(singleton)} is active (default).
  856. Used to read Prolog source files (see consult/1).
  857. .C read_clause 2 +Stream, -Term
  858. Read a clause from {\em Stream}.
  859. .C read_variables 2 -Term, -Bindings
  860. Similar to read/1, but {\em Bindings} is unified with a list of
  861. `${\it Name} = {\it Var}$' tuples, thus providing access to the actual
  862. variable names.
  863. .C read_variables 3 +Stream, -Term, -Bindings
  864. Read, returning term and bindings from {\em Stream}.
  865. .C read_history 6 +Show, +Help, +Special, +Prompt, -Term, -Bindings
  866. Similar to read_variables/2, but allows for history substitutions.
  867. history_read/6 is used by the top level to read the user's actions.
  868. {\em Show} is the command the user should type to show the saved events.
  869. {\em Help} is the command to get an overview of the capabilities.  {\em
  870. Special} is a list of commands that are not saved in the history.  {\em
  871. Prompt} is the first prompt given.  Continuation prompts for more lines
  872. are determined by prompt/2.  A \verb+%w+ in the prompt is substituted by
  873. the event number.  See section~\ref{sec:history} for available
  874. substitutions.
  875. SWI-Prolog calls history_read/6 as follows:
  876. \begin{code}
  877. read_history(h, '!h', [trace], '%w ?- ', Goal, Bindings)
  878. \end{code}
  879. .C history_depth 1 -Int
  880. Dynamic predicate, normally not defined. The user can define this
  881. predicate to set the history depth. It should unify the argument with a
  882. positive integer. When not defined 15 is used as the default.
  883. .C prompt 2 -Old, +New
  884. Set prompt associated with read/1 and its derivates.  {\em Old}
  885. is first unified with the current prompt.  On success the prompt will be
  886. set to {\em New} if this is an atom.  Otherwise an error message is
  887. displayed.  A prompt is printed if one of the read predicates is
  888. called and the cursor is at the left margin.  It is also printed
  889. whenever a newline is given and the term has not been terminated.
  890. Prompts are only printed when the current input stream is {\em user}.
  891. .S Analysing and Constructing Terms
  892. .C functor 3 ?Term, ?Functor, ?Arity
  893. Succeeds if {\em Term} is a term with functor {\em Functor} and arity
  894. {\em Arity}.  If {\em Term} is a variable it is unified with a new term
  895. holding only variables.  functor/3 silently fails on instantiation
  896. faults%
  897.     \footnote{In version 1.2 instantiation fauls let to error messages.
  898.           The new version can be used to do type testing without the
  899.           need to catch illegal instantiations first.}
  900. .C arg 3 +Arg, +Term, ?Value
  901. {\em Term} should be instantiated to a term, {\em Arg} to an integer
  902. between 1 and the arity of {\em Term}. {\em Value} is unified with the
  903. {\em Arg}-th argument of {\em Term}.
  904. .I ?Term =.. ?List
  905. {\em List} is a list which head is the functor of {\em Term} and the
  906. remaining arguments are the arguments of the term. Each of the
  907. arguments may be a variable, but not both.  This predicate is called
  908. `Univ'.  Examples:
  909. \begin{boxed}\begin{code}
  910. ?- foo(hello, X) =.. List.
  911. List = [foo, hello, X]
  912. ?- Term =.. [baz, foo(1)]
  913. Term = baz(foo(1))
  914. \end{code}\end{boxed}
  915. .C numbervars 4 +Term, +Functor, +Start, -End
  916. Unify the free variables of {\em Term} with a term constructed from the
  917. atom {\em Functor} with one argument.  The argument is the number of the
  918. variable.  Counting starts at {\em Start}.  {\em End} is unified with
  919. the number that should be given to the next variable. Example:
  920. \begin{code}
  921. ?- numbervars(foo(A, B, A), this_is_a_variable, 0, End).
  922. A = this_is_a_variable(0)
  923. B = this_is_a_variable(1)
  924. End = 2
  925. \end{code}
  926. In Edinburgh Prolog the second argument is missing.  It is fixed to be
  927. \verb+'$VAR'+.
  928. .C free_variables 2 +Term, -List
  929. Unify {\em List} with a list of variables, each sharing with a unique variable
  930. of {\em Term}. For example:
  931. \begin{code}
  932. ?- free_variables(a(X, b(Y, X), Z), L).
  933. L = [G367, G366, G371]
  934. X = G367
  935. Y = G366
  936. Z = G371
  937. \end{code}
  938. .C copy_term 2 +In, -Out
  939. Make a copy of term {\em In} and unify the result with {\em Out}.
  940. Ground parts of {\em In} are shared by {\em Out}.  Provided {\em In} and
  941. {\em Out} have no sharing variables before this call they will have no
  942. sharing variables afterwards.  copy_term/2 is semantically equivalent
  943. \begin{code}
  944. copy_term(In, Out) :-
  945.     recorda(copy_key, In, Ref),
  946.     recorded(copy_key, Out, Ref),
  947.     erase(Ref).
  948. \end{code}
  949. .S Analysing and Constructing Atoms
  950. .C name 2 ?Atom, ?String
  951. {\em String} is a list of ASCII values describing {\em Atom}. Each of the
  952. arguments may be a variable, but not both. When {\em String} is bound to an
  953. ASCII value list describing an integer and {\em Atom} is a variable {\em Atom}
  954. will be unified with the integer value described by {\em String} (e.g.
  955. `\tty{name(N, "300"), 400 is N + 100}' succeeds).
  956. .C int_to_atom 3 +Int, +Base, -Atom
  957. Convert {\em Int} to an ascii representation using base {\em Base} and unify
  958. the result with {\em Atom}. If ${\em Base} \not= 10$ the base will be
  959. prepended to {\em Atom}.  ${\em Base} = 0$ will try to interpret
  960. {\em Int} as an ASCII value and return \verb+0'c+.  Otherwise
  961. $2 \leq {\em Base} \leq 36$.
  962.  Some examples are
  963. given below.
  964. \begin{center}\begin{tabular}{l@{\hspace{20pt}$\longrightarrow$\hspace{20pt}}l}
  965. int_to_atom(45, 2, A)     &  $A = 2'101101$ \\
  966. int_to_atom(97, 0, A)     &  $A = 0'a$ \\
  967. int_to_atom(56, 10, A)    &  $A = 56$ \\
  968. \end{tabular}\end{center}
  969. .C int_to_atom 2 +Int, -Atom
  970. Equivalent to \verb+int_to_atom(Int, 10, Atom)+.
  971. .C term_to_atom 2 ?Term, ?Atom
  972. Succeeds if {\em Atom} describes a term that unifies with {\em Term}. When
  973. {\em Atom} is instantiated {\em Atom} is converted and then unified with
  974. {\em Term}. Otherwise {\em Term} is ``written'' on {\em Atom} using write/1.
  975. .C atom_to_term 3 +Atom, -Term, -Bindings
  976. Use {\em Atom} as input to read_variables/2 and return the read term in
  977. {\em Term} and the variable bindings in {\em Bindings}.  {\em Bindings}
  978. is a list of ${\it Name} = {\it Var}$ couples, thus providing access to
  979. the actual variable names.  See also read_variables/2.
  980. .C concat 3 ?Atom1, ?Atom2, ?Atom3
  981. {\em Atom3} forms the concatenation of {\em Atom1} and {\em Atom2}.  At
  982. least two of the arguments must be instantiated to atoms, intergers or
  983. floating point numbers.
  984. .C concat_atom 2 +List, -Atom
  985. {\em List} is a list of atoms, integers or floating point numbers. Succeeds
  986. if {\em Atom} can be unified with the concatenated elements of {\em List}. If
  987. {\em List} has exactly 2 elements it is equivalent to concat/3, allowing
  988. for variables in the list.
  989. .C atom_length 2 +Atom, -Length
  990. Succeeds if {\em Atom} is an atom of {\em Length} characters long. This
  991. predicate also works for integers and floats, expressing the number of
  992. characters output when given to write/1.
  993. .S Representing Text in Strings
  994. \label{sec:strings}
  995. SWI-Prolog supports the data type {\em string}.  Strings are a time
  996. and space efficient mechanism to handle text in Prolog.  Atoms are
  997. under some circumstances not suitable because garbage collection on
  998. them is next to impossible (Although it is possible: BIM_prolog does
  999. it).  Representing text as a list of ASCII values is, from the logical
  1000. point of view, the cleanest solution.  It however has two drawbacks:
  1001. 1) they cannot be distinguished from a list of (small) integers; and
  1002. 2) they consume (in SWI-Prolog) 12 bytes for each character stored.
  1003. Within strings each character only requires 1 byte storage. Strings
  1004. live on the global stack and their storage is thus reclaimed on
  1005. backtracking.  Garbage collection can easily deal with strings.
  1006. The ISO standard proposes \verb$"..."$ is transformed into a string
  1007. object by read/1 and derivates. This poses problems as in the old
  1008. convention \verb$"..."$ is transformed into a list of ascii characters.
  1009. For this reason the style check option `{\em string}' is available
  1010. (see style_check/2).
  1011. The set of predicates associated with strings is incomplete and
  1012. tentative.  Names and definitions might change in the future to
  1013. confirm to the emerging standard.
  1014. .C string_to_atom 2 ?String, ?Atom
  1015. Logical conversion between a string and an atom. At least one of the
  1016. two arguments must be instantiated. {\em Atom} can also be an integer
  1017. or floating point number.
  1018. .C string_to_list 2 ?String, ?List
  1019. Logical conversion between a string and a list of ASCII characters. At
  1020. least one of the two arguments must be instantiated.
  1021. .C string_length 2 +String, -Length
  1022. Unify {\em Length} with the number of characters in {\em String}. This
  1023. predicate is functonally equivalent to atom_length/2 and also accepts
  1024. atoms, integers and floats as its first argument.
  1025. .C substring 4 +String, +Start, +Length, -Sub
  1026. Create a substring of {\em String} that starts at character {\em Start}
  1027. (1 base) and has {\em Length} characters. Unify this substring with
  1028. {\em Sub}.%
  1029.     \footnote{Future versions probably will provide a more logical
  1030.           variant of this predicate.}
  1031. .S Operators
  1032. .C op 3 +Precedence, +Type, +Name
  1033. Declare {\em Name} to be an operator of type {\em Type} with precedence
  1034. {\em Precedence}.  {\em Name} can also be a list of names, in which case
  1035. all elements of the list are declared to be identical operators.  {\em
  1036. Precedence} is an integer between 0 and 1200.  Precedence 0 removes
  1037. the declaration.  {\em Type} is one of: \tty{xf}, \tty{yf}, 
  1038. \tty{xfx}, \tty{xfy}, \tty{yfx}, \tty{yfy}, \tty{fy} or \tty{fx}.  The
  1039. `\tty{f}' indicates the position of the functor, while \tty{x} and \tty{y}
  1040. indicate the position of the arguments.  `\tty{y}' should be interpreted
  1041. as ``on this position a term with precedence lower or equal to the
  1042. precedence of the functor should occur''.  For `\tty{x}' the precedence of
  1043. the argument must be strictly lower.
  1044. The precedence of a term is 0, unless its principal functor
  1045. is an operator, in which case the precedence is the precedence of this
  1046. operator. A term enclosed in brackets (\tty{(...)}) has precedence 0.
  1047. The predefined operators are shown in table~\ref{operators}. Note that
  1048. all operators can be redefined by the user.
  1049. \begin{table}
  1050. \begin{center}
  1051. \begin{tabular}{|r|c|p{3in}|}
  1052. \hline
  1053. 1200 & xfx & \tty{-->}, \tty{:-} \\
  1054. 1200 & fx & \tty{:-}, \tty{?-} \\
  1055. 1150 & fx & \tty{dynamic}, \tty{multifile}, \verb$module_transparent$,
  1056.         \verb$discontiguous$ \\
  1057. 1100 & xfy & \tty{;}, \tty{|} \\
  1058. 1050 & xfy & \tty{->} \\
  1059. 1000 & xfy & \tty{, } \\
  1060. 954 & xfy & \verb@\\@ \\
  1061. 900 & fy & \verb@\+@, \tty{not} \\
  1062. 700 & xfx & \tty{<}, \tty{=}, \tty{=..}, \verb+=@=+, \tty{=:=}, \tty{=<}, \tty{==}, 
  1063.             \verb+=\=+, \verb+>+, \verb+>=+, \verb+@<+, \verb+@=<+, \verb+@>+, 
  1064.         \verb+@>=+, \verb+\=+, \verb+\==+, \tty{is} \\
  1065. 600 & xfy & \tty{:} \\
  1066. 500 & yfx & \tty{+}, \tty{-}, \verb+/\+, \verb+\/+, \verb+xor+ \\
  1067. 500 & fx & \tty{+}, \tty{-}, \tty{?}, \verb+\+ \\
  1068. 400 & yfx & \verb+*+, \tty{/}, \tty{//}, \tty{<<}, \tty{>>} \\
  1069. 300 & xfx & \tty{mod} \\
  1070. 200 & xfy & \verb+^+ \\
  1071. \hline
  1072. \end{tabular}
  1073. \end{center}
  1074.     \caption{System operators}
  1075.     \label{operators}
  1076. \end{table}
  1077. .C current_op 3 ?Precedence, ?Type, ?Name
  1078. Succeeds when {\em Name} is currently defined as an operator of type {\em Type}
  1079. with precedence {\em Precedence}. See also op/3.
  1080. .S Arithmetic
  1081. \label{sec:arith}
  1082. Arithmetic can be divided into some special purpose integer predicates
  1083. and a series of general predicates for floating point and integer
  1084. arithmetic as appropriate.  The integer predicates are as ``logical'' as
  1085. possible.  Their usage is recommended whenever applicable, resulting in
  1086. faster and more ``logical'' programs.
  1087. The general arithmic predicates are optionaly compiled now (see
  1088. please/3 and the \tty{-O} command line option).  Compiled arithmetic
  1089. reduces global stack requirements and improves performance.
  1090. Unfortunately compiled arithmetic cannot be traced, which is why it is
  1091. optional.
  1092. The general arithmetic predicates all handle {\em expressions}.  An
  1093. expression is either a simple number or a {\em function}.  The arguments
  1094. of a function are expressions.  The functions are described in
  1095. section~\ref{functions}.
  1096. .C between 3 +Low, +High, ?Value
  1097. {\em Low} and {\em High} are integers, ${\em High} \geq {\em Low}$. If
  1098. {\em Value} is an integer, ${\it Low} \leq {\it Value} \leq {\it High}$.
  1099. When {\em Value} is a variable it is successively  bound to all
  1100. integers between {\em Low} and {\em High}.
  1101. .C succ 2 ?Int1, ?Int2
  1102. Succeeds if ${\em Int2} = {\em Int1} + 1$. At least one of the arguments
  1103. must be instantiated to an integer.
  1104. .C plus 3 ?Int1, ?Int2, ?Int3
  1105. Succeeds if ${\em Int3} = {\em Int1} + {\em Int2}$. At least two of the
  1106. three arguments must be instantiated to integers.
  1107. .IT +Expr1 > +Expr2
  1108. Succeeds when expression {\em Expr1} evaluates to a larger number than {\em Expr2}.
  1109. .IT +Expr1 < +Expr2
  1110. Succeeds when expression {\em Expr1} evaluates to a smaller number than {\em Expr2}.
  1111. .IT +Expr1 =< +Expr2
  1112. Succeeds when expression {\em Expr1} evaluates to a smaller or equal number
  1113. to {\em Expr2}.
  1114. .IT +Expr1 >= +Expr2
  1115. Succeeds when expression {\em Expr1} evaluates to a larger or equal number
  1116. to {\em Expr2}.
  1117. .IT +Expr1 =\= +Expr2
  1118. Succeeds when expression {\em Expr1} evaluates to a number non-equal to
  1119. {\em Expr2}.
  1120. .IT +Expr1 =:= +Expr2
  1121. Succeeds when expression {\em Expr1} evaluates to a number equal to {\em
  1122. Expr2}.
  1123. .I -Number is +Expr
  1124. Succeeds when {\em Number} has successfully been unified with the number
  1125. {\em Expr} evaluates to.
  1126. .S Arithmetic Functions
  1127. \label{functions}
  1128. Arithmetic functions are terms which are evaluated by the arithmetic
  1129. predicates described above.  SWI-Prolog tries to hide the difference
  1130. between integer arithmetic and floating point arithmetic from the Prolog
  1131. user.  Arithmetic is done as integer arithmetic as long as possible and
  1132. converted to floating point arithmetic whenever one of the arguments or
  1133. the combination of them requires it.  If a function returns a floating
  1134. point value which is whole it is automatically transformed into an
  1135. integer.  There are three types of arguments to functions:
  1136. \begin{center}\begin{tabular}{lp{4in}}
  1137. \it Expr & Arbitrary expression, returning either a floating
  1138.            point value or an integer. \\
  1139. \it IntExpr & Arbitrary expression that should evaluate into
  1140.           an integer. \\
  1141.     \it Int & An integer.
  1142. \end{tabular}\end{center}
  1143. In case integer addition, subtraction and multiplication would lead to
  1144. an integer overflow the operands are automatically converted to
  1145. floating point numbers.  The floating point functions (sin/1, exp/1,
  1146. etc.)  form a direct interface to the corresponding C library
  1147. functions used to compile SWI-Prolog.  Please refer to the C library
  1148. documentation for details on percision, error handling, etc.
  1149. .PT - +Expr
  1150. ${\em Result} = -{\em Expr}$
  1151. .IT +Expr1 + +Expr2
  1152. ${\em Result} = {\em Expr1} + {\em Expr2}$
  1153. .IT +Expr1 - +Expr2
  1154. ${\em Result} = {\em Expr1} - {\em Expr2}$
  1155. .IT +Expr1 * +Expr2
  1156. ${\em Result} = {\em Expr1} \times {\em Expr2}$
  1157. .IT +Expr1 / +Expr2
  1158. ${\em Result} = \frac{\em Expr1}{\em Expr2}$
  1159. .I +IntExpr1 mod +IntExpr2
  1160. ${\em Result} = {\em Expr1}~mod~{\em Expr2}$ (remainder of division).
  1161. .IT +IntExpr1 // +IntExpr2
  1162. ${\em Result} = {\em Expr1}~div~{\em Expr2}$ (integer division).
  1163. .C abs 1 +Expr
  1164. Evaluate {\em Expr} and return the absolute value of it.
  1165. .C max 2 +Expr1, +Expr2
  1166. Evaluates to the largest of both {\em Expr1} and {\em Expr2}.
  1167. .C min 2 +Expr1, +Expr2
  1168. Evaluates to the smallest of both {\em Expr1} and {\em Expr2}.
  1169. .C . 2 +Int, []
  1170. A list of one element evaluates to the element.  This implies \tty{"a"}
  1171. evaluates to the ASCII value of the letter \tty{a} (97). This option is
  1172. available for compatibility only.  It will not work if
  1173. `style_check(+string)' is active as \tty{"a"} will then be tranformed
  1174. into a string object. The recommended way to specify the ASCII value of
  1175. the letter `a' is \tty{0'a}.
  1176. .C random 1 +Int
  1177. Evaluates to a random integer {\em i} for which $0 \leq i < {\it Int}$.
  1178. The seed of this random generator is determined by the system clock when
  1179. SWI-Prolog was started.
  1180. .C integer 1 +Expr
  1181. Evaluates {\em Expr} and rounds the result to the nearest integer.
  1182. .C floor 1 +Expr
  1183. Evaluates {\em Expr} and returns the largest integer smaller or equal
  1184. to the result of the evaluation.
  1185. .C ceil 1 +Expr
  1186. Evaluates {\em Expr} and returns the smallest integer larger or equal
  1187. to the result of the evaluation.
  1188. .IT +IntExpr >> +IntExpr
  1189. Bitwise shift {\em IntExpr1} by {\em IntExpr2} bits to the right. Note
  1190. that integers are only 27 bits.
  1191. .IT +IntExpr << +IntExpr
  1192. Bitwise shift {\em IntExpr1} by {\em IntExpr2} bits to the left.
  1193. .IT +IntExpr \/ +IntExpr
  1194. Bitwise `or' {\em IntExpr1} and {\em IntExpr2}.
  1195. .IT +IntExpr /\ +IntExpr
  1196. Bitwise `and' {\em IntExpr1} and {\em IntExpr2}.
  1197. .I +IntExpr xor +IntExpr
  1198. Bitwise `exclusive or' {\em IntExpr1} and {\em IntExpr2}.
  1199. .PT \ +IntExpr
  1200. Bitwise negation.
  1201. .C sqrt 1 +Expr
  1202. ${\em Result} = \sqrt{{\em Expr}}$
  1203. .C sin 1 +Expr
  1204. ${\em Result} = \sin{{\em Expr}}$. {\em Expr} is the angle in radials.
  1205. .C cos 1 +Expr
  1206. ${\em Result} = \cos{{\em Expr}}$. {\em Expr} is the angle in radials.
  1207. .C tan 1 +Expr
  1208. ${\em Result} = \tan{{\em Expr}}$. {\em Expr} is the angle in radials.
  1209. .C asin 1 +Expr
  1210. ${\em Result} = \arcsin{{\em Expr}}$. {\em Result} is the angle in radials.
  1211. .C acos 1 +Expr
  1212. ${\em Result} = \arccos{{\em Expr}}$. {\em Result} is the angle in radials.
  1213. .C atan 1 +Expr
  1214. ${\em Result} = \arctan{{\em Expr}}$. {\em Result} is the angle in radials.
  1215. .C atan 2 +YExpr, +XExpr
  1216. ${\em Result} = \arctan{\frac{\em YExpr}{\em XExpr}}$. {\em Result} is the
  1217. angle in radials.  The return value is in the range $-\pi ... \pi$.
  1218. Used to convert between rectangular and polar coordinate system.
  1219. .C log 1 +Expr
  1220. ${\em Result} = \ln{{\em Expr}}$
  1221. .C log10 1 +Expr
  1222. ${\em Result} = \lg{{\em Expr}}$
  1223. .C exp 1 +Expr
  1224. ${\it Result} = \pow{e}{\it Expr}$
  1225. .IT +Expr1 ^ +Expr2
  1226. ${\em Result} = \pow{\em Expr1}{\em Expr2}$
  1227. .C pi 0
  1228. Evaluates to the mathematical constant $\pi$ (3.141593...).
  1229. .C e 0
  1230. Evaluates to the mathematical constant $e$ (2.718282...).
  1231. .C cputime 0
  1232. Evaluates to a floating point number expressing the cpu time (in seconds)
  1233. used by Prolog up till now. See also statistics/2 and time/1.
  1234. .S Adding Arithmetic Functions
  1235. Prolog predicates can be given the role of arithmetic function.  The
  1236. last argument is used to return the result, the arguments before the
  1237. last are the inputs.  Arithmetic functions are added using the
  1238. predicate arithmetic_function/1, which takes the head as its argument.
  1239. Arithmetic functions are module sensitive, that is they are only
  1240. visible from the module in which the function is defined and delared.
  1241. Global arithmetic functions should be defined and registered from
  1242. module {\tt user}.  Global definitions can be overruled locally in
  1243. modules.  The builtin functions described above can be redefined as
  1244. well.
  1245. .C arithmetic_function 1 +Head
  1246. Register a Prolog predicate as an arithmetic function (see is/2, \verb$>/2$,
  1247. etc.).  The Prolog predicate should have one more argument than
  1248. specified by {\em Head}, which it either a term {\em Name/Arity}, an
  1249. atom or a complex term.  This last argument is an unbound variable at
  1250. call time and should be instantiated to an integer or floating point
  1251. number. The other arguments are the parameters.  This predicate is
  1252. module sensitive and will declare the arithmetic function only for the
  1253. context module, unless declared from module {\tt user}.  Example: 
  1254. \begin{boxed}\begin{code}
  1255. 1 ?- [user].
  1256. :- arithmetic_function(mean/2).
  1257. mean(A, B, C) :-
  1258.     C is (A+B)/2.
  1259. user compiled, 0.07 sec, 440 bytes.
  1260. 2 ?- A is mean(4, 5).
  1261. A = 4.500000
  1262. \end{code}\end{boxed}
  1263. .C current_arithmetic_function 1 ?Head
  1264. Succesively unifies all arithmetic functions that are visible from
  1265. the context module with {\em Head}.
  1266. .S List Manipulation
  1267. .C is_list 1 +Term
  1268. Succeeds if {\em Term} is bound to the empty list (\tty{[]}) or a term with
  1269. functor `\tty{.}' and arity~2.
  1270. .C proper_list 1 +Term
  1271. Equivalent to is_list/1, but also requires the tail of the list to be
  1272. a list (recursively). Examples:
  1273. \begin{code}
  1274. is_list([x|A])        % true
  1275. proper_list([x|A])    % false
  1276. \end{code}
  1277. .C append 3 ?List1, ?List2, ?List3
  1278. Succeeds when {\em List3} unifies with the concatenation of {\em List1}
  1279. and {\em List2}. The predicate can be used with any instantiation
  1280. pattern (even three variables).
  1281. .C member 2 ?Elem, ?List
  1282. Succeeds when {\em Elem} can be unified with one of the members of {\em
  1283. List}. The predicate can be used with any instantiation
  1284. pattern.
  1285. .C memberchk 2 ?Elem, +List
  1286. Equivalent to member/2, but leaves no choice point.
  1287. .C delete 3 +List1, ?Elem, ?List2
  1288. Delete all members of {\em List1} that simultaneously unify with {\em
  1289. Elem} and unify the result with {\em List2}.
  1290. .C select 3 ?List1, ?Elem, ?List2
  1291. Select an element of {\em List1} that unifies with {\em Elem}. {\em
  1292. List2} is unified with the list remaining from {\em List1} after
  1293. deleting the selected element. Normally used with the instantiation
  1294. pattern {\em +List1, -Elem, -List2}, but can also be used to insert an
  1295. element in a list using {\em -List1, +Elem, +List2}.
  1296. .C nth0 3 ?Index, ?List, ?Elem
  1297. Succeeds when the {\em Index}-th element of {\em List} unifies with
  1298. {\em Elem}. Counting starts at 0.
  1299. .C nth1 3 ?Index, ?List, ?Elem
  1300. Succeeds when the {\em Index}-th element of {\em List} unifies with
  1301. {\em Elem}. Counting starts at 1.
  1302. .C last 2 ?Elem, ?List
  1303. Succeeds if {\em Elem} unifies with the last element of {\em List}.
  1304. .C reverse 2 +List1, -List2
  1305. Reverse the order of the elements in {\em List1} and unify the result
  1306. with the elements of {\em List2}.
  1307. .C flatten 2 +List1, -List2
  1308. Transform {\em List1}, possibly holding lists as elements into a `flat'
  1309. list by replacing each list with its elements (recursively). Unify the
  1310. resulting flat list with {\em List2}. Example:
  1311. \begin{code}
  1312. ?- flatten([a, [b, [c, d], e]], X).
  1313. X = [a, b, c, d, e]
  1314. \end{code}
  1315. .C length 2 ?List, ?Int
  1316. Succeeds if {\em Int} represents the number of elements of list {\em
  1317. List}. Can be used to create a list holding only variables.
  1318. .C merge 3 +List1, +List2, -List3
  1319. {\it List1} and {\it List2} are lists, sorted to the standard order of
  1320. terms (see section~\ref{sec:compare}).  {\it List3} will be unified with an
  1321. ordered list holding the both the elements of {\it List1} and {\it
  1322. List2}. Duplicates are {\bf not} removed.
  1323. .S Set Manipulation
  1324. .C is_set 1 +Set
  1325. Succeeds if set is a proper list (see proper_list/1) without duplicates.
  1326. .C list_to_set 2 +List, -Set
  1327. Succeeds if {\em Set} holds the same elements as {\em List} in the same
  1328. order, but has no duplicates. See also sort/1.
  1329. .C intersection 3 +Set1, +Set2, -Set3
  1330. Succeeds if {\em Set3} unifies with the intersection of {\em Set1} and
  1331. {\em Set2}. {\em Set1} and {\em Set2} are lists without duplicates.
  1332. They need not be ordered.
  1333. .C subtract 3 +Set, +Delete, -Result
  1334. Delete all elements of set `Delete' from `Set' and unify the resulting
  1335. set with `Result'.
  1336. .C union 3 +Set1, +Set2, -Set3
  1337. Succeeds if {\em Set3} unifies with the union of {\em Set1} and
  1338. {\em Set2}. {\em Set1} and {\em Set2} are lists without duplicates.
  1339. They need not be ordered.
  1340. .C subset 2 +Subset, +Set
  1341. Succeeds if all elements of {\em Subset} are elements of {\em Set} as well.
  1342. .C merge_set 3 +Set1, +Set2, -Set3
  1343. {\it Set1} and {\it Set2} are lists without duplicates, sorted to the
  1344. standard order of terms.  {\it Set3} is unified with an ordered
  1345. list without duplicates holding the union of the elements of {\it Set1}
  1346. and {\it Set2}.
  1347. .S Sorting Lists
  1348. .C sort 2 +List, -Sorted
  1349. Succeeds if {\em Sorted} can be unified with a list holding the
  1350. elements of {\em List}, sorted to the standard order of terms (see
  1351. section~\ref{sec:compare}). Duplicates are removed. 
  1352. .C msort 2 +List, -Sorted
  1353. Equivalent to sort/2, but does not remove duplicates.
  1354. .C keysort 2 +List, -Sorted
  1355. {\em List} is a list of \tty{Key-Value} pairs (e.g. terms of the
  1356. functor `\tty{-}' with arity 2). keysort/2 sorts {\em List} like msort/2, 
  1357. but only compares the keys. Can be used to sort terms not on standard
  1358. order, but on any criterion that can be expressed on a multi-dimensional
  1359. scale. Sorting on more than one criterion can be done using terms as
  1360. keys, putting the first criterion as argument 1, the second as argument
  1361. 2, etc.
  1362. .C predsort 3 +Pred, +List, -Sorted
  1363. Sorts similar to msort/2, but determines the order of two terms by
  1364. applying {\em Pred} to pairs of elements from {\em List} (see apply/2).
  1365. The predicate should succeed if the first element should be before the
  1366. second.
  1367. .S Finding all Solutions to a Goal
  1368. .C findall 3 +Var, +Goal, -Bag
  1369. Creates a list of the instantiations {\em Var} gets successively on
  1370. backtracking over {\em Goal} and unifies the result with {\em Bag}.
  1371. Succeeds with an empty list if {\em Goal} has no solutions. findall/3 is
  1372. equivalent to bagof/3 with all free variables bound with the existence
  1373. operator (\verb+^+), except that bagof/3 fails when goal has no
  1374. solutions.
  1375. .C bagof 3 +Var, +Goal, -Bag
  1376. Unify {\em Bag} with the alternatives of {\em Var}, if {\em Goal} has
  1377. free variables besides the one sharing with {\em Var} bagof will
  1378. backtrack over the alternatives of these free variables, unifying {\em
  1379. Bag} with the corresponding alternatives of {\em Var}. The construct
  1380. \verb+Var^Goal+ tells bagof not to bind {\em Var} in {\em Goal}.
  1381. Bagof/3 fails if {\em Goal} has no solutions.
  1382. The example below illustrates bagof/3 and the \verb+^+ operator. The
  1383. variable bindings are printed together on one line to save paper.
  1384. \begin{boxed}
  1385. \begin{code}
  1386. 2 ?- listing(foo).
  1387. foo(a, b, c).
  1388. foo(a, b, d).
  1389. foo(b, c, e).
  1390. foo(b, c, f).
  1391. foo(c, c, g).
  1392. 3 ?- bagof(C, foo(A, B, C), Cs).
  1393. A = a, B = b, C = G308, Cs = [c, d] ;
  1394. A = b, B = c, C = G308, Cs = [e, f] ;
  1395. A = c, B = c, C = G308, Cs = [g] ;
  1396. 4 ?- bagof(C, A^foo(A, B, C), Cs).
  1397. A = G324, B = b, C = G326, Cs = [c, d] ;
  1398. A = G324, B = c, C = G326, Cs = [e, f, g] ;
  1399. \end{code}
  1400. \end{boxed}
  1401. .C setof 3 +Var, +Goal, -Set
  1402. Equivalent to bagof/3, but sorts the result using sort/2 to get a sorted
  1403. list of alternatives without duplicates.
  1404. .S Invoking Predicates on all Members of a List
  1405. All the predicates in this section call a predicate on all members of a
  1406. list or until the predicate called fails.  The predicate is called via
  1407. apply/2, which implies common arguments can be put in front of the
  1408. arguments obtained from the list(s). For example:
  1409. \begin{code}
  1410. ?- maplist(plus(1), [0, 1, 2], X).
  1411. X = [1, 2, 3]
  1412. \end{code}
  1413. we will phrase this as ``{\em Predicate} is applied on ...''
  1414. .C checklist 2 +Pred, +List
  1415. {\em Pred} is applied successively on each element of {\em List} until
  1416. the end of the list or {\em Pred} fails. In the latter case the
  1417. checklist/2 fails.
  1418. .C maplist 3 +Pred, ?List1, ?List2
  1419. Apply {\em Pred} on all successive pairs of elements from {\em List1}
  1420. and {\em List2}. Fails if {\em Pred} can not be applied to a pair. See
  1421. the example above.
  1422. .C sublist 3 +Pred, +List1, ?List2
  1423. Unify {\em List2} with a list of all elements of {\em List1} to which
  1424. {\em Pred} applies.
  1425. .S Forall
  1426. .C forall 2 +Cond, +Action
  1427. For all alternative bindings of {\em Cond} {\em Action} can be proven.
  1428. The example verifies that all arithmic statements in the list {\em L}
  1429. are correct. It does not say which is wrong if one proves wrong.
  1430. \begin{boxed}\begin{code}
  1431. ?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]),
  1432.          Result =:= Formula).
  1433. \end{code}\end{boxed}
  1434. .S Formatted Write
  1435. The current version of SWI-Prolog provides two formatted
  1436. write predicates.  The first is writef/[1,2], which is compatible with
  1437. Edinburgh C-Prolog.  The second is format/[1,2], which is compatible
  1438. with Quintus Prolog.  We hope the Prolog community will once define a
  1439. standard formatted write predicate.  If you want performance use
  1440. format/[1,2] as this predicate is defined in C.  Otherwise
  1441. compatibility reasons might tell you which predicate to use.
  1442. .SS Writef
  1443. .C write_ln 1 +Term
  1444. Equivalent to \tty{write(Term), nl.}
  1445. .C writef 1 +Atom
  1446. Equivalent to \tty{writef(Atom, []).}
  1447. .C writef 2 +Format, +Arguments
  1448. Formatted write.  {\em Format} is an atom whose characters will be printed.
  1449. {\em Format} may contain certain special character sequences which specify
  1450. certain formatting and substitution actions.  {\em Arguments} then provides
  1451. all the terms required to be output.
  1452. Escape sequences to generate a single special character:
  1453. \begin{center}
  1454. \begin{tabular}{|l|p{3.5in}|}
  1455. \hline
  1456. \verb+\n+   &  \verb+<NL>+ is output \\
  1457. \verb+\l+   &  \verb+<LF>+ is output \\
  1458. \verb+\r+   &  \verb+<CR>+ is output \\
  1459. \verb+\t+   &  \verb+<TAB>+ is output \\
  1460. \verb+\\+   &  The character `\verb+\+' is output \\
  1461. \verb+\%+   &  The character `\verb+%+' is output \\
  1462. \verb+\nnn+ &  where \tty{nnn} is an integer (1-3 digits) the
  1463.            character with ASCII code \tty{nnn} is output
  1464.            (NB : \tty{nnn} is read as DECIMAL) \\
  1465. \hline
  1466. \end{tabular}
  1467. \end{center}
  1468. Escape sequences to include arguments from {\em Arguments}. Each time a
  1469. \% escape sequence is found in {\em Format} the next argument from {\em
  1470. Arguments} is formatted according to the specification.
  1471. \begin{center}
  1472. \begin{tabular}{|l|p{3.5in}|}
  1473. \hline
  1474. \verb+%t+  &  print/1 the next item (mnemonic: term) \\
  1475. \verb+%w+  &  write/1 the next item \\
  1476. \verb+%q+  &  writeq/1 the next item \\
  1477. \verb+%d+  &  display/1 the next item \\
  1478. \verb+%p+  &  print/1 the next item (identical to \verb+%t+) \\
  1479. \verb+%n+  &  put the next item as a character (i.e. it is
  1480.           an ASCII value) \\
  1481. \verb+%r+  &  write the next item N times where N is the
  1482.           second item (an integer) \\
  1483. \verb+%s+  &  write the next item as a String (so it must
  1484.           be a list of characters) \\
  1485. \verb+%f+  &  perform a ttyflush/0 (no items used) \\
  1486. \verb+%Nc+ &  write the next item Centered in N columns. \\
  1487. \verb+%Nl+ &  write the next item Left justified in N columns. \\
  1488. \verb+%Nr+ &  write the next item Right justified in N columns.
  1489.           N is a decimal number with at least one digit.
  1490.           The item must be an atom, integer, float or string. \\
  1491. \hline
  1492. \end{tabular} 
  1493. \end{center}
  1494. .C swritef 3 -String, +Format, +Arguments
  1495. Equivalent to writef/3, but ``writes'' the result on {\em String} instead
  1496. of the current output stream. Example:
  1497. \begin{code}
  1498. ?- swritef(S, '%15L%w', ['Hello', 'World']).
  1499. S = "Hello          World"
  1500. \end{code}
  1501. .C swritef 2 -String, +Format
  1502. Equivalent to \verb+swritef(String, Format, []).+
  1503. .SS Format
  1504. .C format 1 +Format
  1505. Defined as `\verb$format(Format) :- format(Format, []).$'
  1506. .C format 2 +Format, +Arguments
  1507. {\em Format} is an atom, list of ASCII values, or a Prolog string.
  1508. {\em Arguments} provides the arguments required by the format
  1509. specification.  If only one argument is required and this is not a list
  1510. of ASCII values the argument need not be put in a list.  Otherwise the
  1511. arguments are put in a list.
  1512. Special sequences start with the tilde (\verb$~$), followed by an optional
  1513. numeric argument, followed by a character describing the action to be
  1514. undertaken.  A numeric argument is either a sequence of digits,
  1515. representing a positive decimal number, a sequence \verb$`<character>$,
  1516. representing the ASCII value of the character (only useful for
  1517. \verb$~t$) or a asterisk (*), in when the numeric argument is taken
  1518. from the next argument of the argument list, which should be a positive
  1519. integer.  Actions are:
  1520. \begin{itemize}
  1521.     \item[\Large\bf\raisebox{-1ex}{$\tilde{\mbox{}}$}]
  1522. Output the tilde itself.
  1523.     \item[\bf a]
  1524. Output the next argument, which should be an atom. This option is
  1525. equivalent to {\bf w}. Compatibility reasons only.
  1526.     \item[\bf c]
  1527. Output the next argument as an ASCII value. This argument should be an
  1528. integer in the range [0, ..., 255] (including 0 and 255).
  1529.     \item[\bf d]
  1530. Output next argument as a decimal number.  It should be an integer.  If
  1531. a numeric argument is specified a dot is inserted {\em argument}
  1532. positions from the right (useful for doing fixed point arithmetic with
  1533. integers, such as handling amounts of money).
  1534.     \item[\bf D]
  1535. Same as {\bf d}, but makes large values easier to read by inserting a
  1536. comma every three digits left to the dot or right.
  1537.     \item[\bf e]
  1538. Output next argument as a floating point number in exponentional
  1539. notation.  The numeric argument specifies the precission.  Default is 6
  1540. digits.  Exact representation depends on the C library function
  1541. printf(). This function is invoked with the format
  1542. \verb$%.<percission>e$.
  1543.     \item[\bf E]
  1544. Equivalent to {\bf e}, but outputs a capital E to indicate the exponent.
  1545.     \item[\bf f]
  1546. Floating point in non-exponentional notation. See C library function
  1547. printf().
  1548.     \item[\bf g]
  1549. Floating point in {\bf e} or {\bf f} notation, whichever is shorter.
  1550.     \item[\bf G]
  1551. Floating point in {\bf E} or {\bf f} notation, whichever is shorter.
  1552.     \item[\bf i]
  1553. Ignore next argument of the argument list. Produces no output.
  1554.     \item[\bf k]
  1555. Give the next argument to displayq/1 (canonical write).
  1556.     \item[\bf n]
  1557. Output a newline character.
  1558.     \item[\bf N]
  1559. Only output a newline if the last character output on this stream was
  1560. not a newline. Not properly implemented yet.
  1561.     \item[\bf p]
  1562. Give the next argument to print/1.
  1563.     \item[\bf q]
  1564. Give the next argument to writeq/1.
  1565.     \item[\bf r]
  1566. Print integer in radix the numeric argument notation. Thus \verb$~16r$
  1567. prints its argument hexadecimal. The argument should be in the range
  1568. \mbox{[2, ... 36]}. Lower case letters are used for digits above 9.
  1569.     \item[\bf R]
  1570. Same as {\bf r}, but uses upper case letters for digits above 9.
  1571.     \item[\bf s]
  1572. Output a string of ASCII characters from the next argument.
  1573.     \item[\bf t]
  1574. All remaining space between 2 tabstops is distributed equaly over
  1575. \verb$~t$ statements between the tabstops.  This space is padded with
  1576. spaces by default.  If an argument is supplied this is taken to be the
  1577. ASCII value of the character used for padding.  This can be used to do
  1578. left or right alignment, centering, distributing, etc.  See also
  1579. \verb$~|$ and \verb$~+$ to set tab stops.  A tabstop is assumed at the
  1580. start of each line.
  1581.     \item[\rule{1pt}{2ex}]
  1582. Set a tabstop on the current position. If an argument is supplied set a
  1583. tabstop on the position of that argument. This will cause all \verb$~t$'s
  1584. to be distributed between the previous and this tabstop.
  1585.     \item[\bf +]
  1586. Set a tabstop relative to the current position. Further the same as
  1587. \verb$~|$.
  1588.     \item[\bf w]
  1589. Give the next argument to write/1.
  1590. \end{itemize}
  1591. Example:
  1592. \begin{boxed}\begin{code}
  1593. simple_statistics :-
  1594.     <obtain statistics>        % left to the user
  1595.     format('~tStatistics~t~72|~n~n'),
  1596.     format('Runtime: ~`.t ~2f~34|  Inferences: ~`.t ~D~72|~n',
  1597.                         [RunT, Inf]),
  1598.     ....
  1599. \end{code}\end{boxed}
  1600. Will output
  1601. \begin{boxed}\begin{code}
  1602.                  Statistics
  1603. Runtime: .................. 3.45  Inferences: .......... 60,345
  1604. \end{code}\end{boxed}
  1605. .C sformat 3 -String, +Format, +Arguments
  1606. Equivalent to format/3, but ``writes'' the result on {\em String} instead
  1607. of the current output stream. Example:
  1608. \begin{code}
  1609. ?- sformat(S, '~w~t~15|~w', ['Hello', 'World']).
  1610. S = "Hello          World"
  1611. \end{code}
  1612. .C sformat 2 -String, +Format
  1613. Equivalent to `\verb+sformat(String, Format, []).+'
  1614. .SS Programming Format
  1615. .C format_predicate 2 +Char, +Head
  1616. If a sequence \verb@~c@ (tilde, followed by some character) is
  1617. found, the format derivates will first check whether the user has
  1618. defined a predicate to handle the format. If not, the built in
  1619. formatting rules described above are used. {\em Char} is either an
  1620. ascii value, or a one character atom, specifying the letter to be
  1621. (re)defined.  {\em Head} is a term, whose name and arity are used
  1622. to determine the predicate to call for the redefined formatting
  1623. character.  The first argument to the predicate is the numeric
  1624. argument of the format command, or the atom \tty{default} if no
  1625. argument is specified.  The remaining arguments are filled from the
  1626. argument list.  The example below redefines \verb@~n@ to produce {
  1627. \em Arg} times return followed by linefeed (so a (Grr.) DOS machine is 
  1628. happy with the output).
  1629. \begin{boxed}\begin{code}
  1630. :- format_predicate(n, dos_newline(_Arg)).
  1631. dos_newline(Arg) :-
  1632.     between(1, Ar, _), put(13), put(10), fail ; true.
  1633. \end{code}\end{boxed}
  1634. .S Terminal Control
  1635. The following predicates form a simple access mechanism to the Unix termcap
  1636. library to provide terminal independant I/O for screen terminals.  The
  1637. library package \tty{tty} builds on top of these predicates.
  1638. .C tty_get_capability 3 +Name, +Type, -Result
  1639. Get the capability named {\em Name} from the termcap library.  See
  1640. termcap(5) for the capability names. {\em Type} specifies the type of
  1641. the expected result, and is one of \tty {string}, \tty{number} or
  1642. \tty{bool}.  String results are returned as an atom, number result as
  1643. an integer and bool results as the atom \tty{on} or \tty{off}.  If
  1644. an option cannot be found this predicate fails silently.  The
  1645. results are only computed once. Succesive queries on the same
  1646. capability are fast. 
  1647. .C tty_goto 2 +X, +Y
  1648. Goto position {\em(X, Y)} on the screen.  Note that the predicates
  1649. line_count/2 and line_position/2 will not have a well defined
  1650. behaviour while using this predicate.
  1651. .C tty_put 2 +Atom, +Lines
  1652. Put an atom via the termcap library function tputs().  This function
  1653. decodes padding information in the strings returned by tty_get_capability/3
  1654. and should be used to output these strings. {\em Lines} is the
  1655. number of lines affected by the operation, or 1 if not applicable (as
  1656. in almost all cases).
  1657. .C set_tty 2 -OldStream, +NewStream
  1658. Set the output stream, used by tty_put/2 and tty_goto/2 to a
  1659. specific stream. Default is user_output.
  1660. .S Unix Interaction
  1661. .C shell 2 +Command, -Status
  1662. Execute {\em Command} on the operating system. {\em Command} is given to the
  1663. bourne shell (/bin/sh). {\em Status} is unified with the exit status of
  1664. the command.
  1665. .C shell 1 +Command
  1666. Equivalent to `\tty{shell(Command, 0)}'.
  1667. .C shell 0
  1668. Start an interactive Unix shell.  Default is \tty{/bin/sh}, the
  1669. environment variable \tty{SHELL} overrides this default.
  1670. .C getenv 2 +Name, -Value
  1671. Get Unix environment variable (see csh(1) and sh(1)). Fails if the
  1672. variable does not exist.
  1673. .C setenv 2 +Name, +Value
  1674. Set Unix environment variable.  {\em Name} and {\em Value} should be
  1675. instantiated to atoms or integers.  The environment variable will be
  1676. passed to shell/[0-2] and can be requested using getenv/2.
  1677. .C unsetenv 1 +Name
  1678. Remove Unix environment variable from the environment.
  1679. .C get_time 1 -Time
  1680. Return the number of seconds that elapsed since the epoch of Unix,
  1681. 1 January 1970, 0 hours.  {\em Time} is a floating point number. Its
  1682. granularity is system dependant.  On SUN, this is 1/60 of a second.
  1683. .C convert_time 8 +Time, -Year, -Month, -Day, -Hour, -Minute, -Second, -MilliSeconds
  1684. Convert a time stamp, provided by get_time/1, file_time/2, etc.  {\em
  1685. Year} is unified with the year, {\em Month} with the month number
  1686. (January is 1), {\em Day} with the day of the month (starting with 1),
  1687. {\em Hour} with the hour of the day (0--23), {\em Minute} with the
  1688. minute (0--59). {\em Second} with the second (0--59) and {\em
  1689. MilliSecond} with the milli seconds (0--999).  Note that the latter
  1690. might not be acurate or might always be 0, depending on the timing
  1691. capabilities of the system.
  1692. .S Unix File System Interaction
  1693. .C access_file 2 +File, +Mode
  1694. Succeeds when {\em File} exists and can be accessed by this prolog
  1695. process under mode {\em Mode}.  {\em Mode} is one of the atoms
  1696. \tty{read}, \tty{write} or \tty{execute}.  {\em File} may also be
  1697. the name of a directory.  Fails silently otherwise.
  1698. .C exists_file 1 +File
  1699. Succeeds when {\em File} exists. This does not imply the user has read
  1700. and/or write permission for the file.
  1701. .C same_file 2 +File1, +File2
  1702. Succeeds if both filenames refer to the same physical file.  That is,
  1703. if {\em File1} and {\em File2} are the same string or both names exist
  1704. and point to the same file (due to hard or symbolic links and/or
  1705. relative vs. absolute paths).
  1706. .C exists_directory 1 +Directory
  1707. Succeeds if {\em Directory} exists. This does not imply the user has read,
  1708. search and or write permission for the directory.
  1709. .C delete_file 1 +File
  1710. Unlink {\em File} from the Unix file system.
  1711. .C rename_file 2 +File1, +File2
  1712. Rename {\em File1} into {\em File2}. Currently files cannot be moved
  1713. across devices.
  1714. .C size_file 2 +File, -Size
  1715. Unify {\em Size} with the size of {\em File} in characters.
  1716. .C time_file 2 +File, -Time
  1717. Unify the last modification time of {\em File} with {\em Time}. {\em
  1718. Time} is a floating point number expressing the seconds elapsed since
  1719. Jan~1, 1970.
  1720. .C absolute_file_name 2 +File, -Absolute
  1721. Expand Unix file specification into an absolute path.  User home
  1722. directory expansion (\verb+~+ and \verb+~user+) and variable expansion
  1723. is done.  The absolute path is canonised: references to `.' and `..' are
  1724. deleted.  SWI-Prolog uses absolute file names to register source files
  1725. independant of the current working directory.
  1726. .C expand_file_name 2 +WildChart, -List
  1727. Unify {\em List} with a sorted list of files or directories matching
  1728. {\em WildChart}.  The normal Unix wildchart constructs `\verb+?+',
  1729. `\verb+*+', `\verb+[...]+' and `\verb+{...}+' are recognised.  The
  1730. interpretation of `\verb+{...}+' is interpreted slightly different from
  1731. the C shell (csh(1)).  The comma separated argument can be arbitrary
  1732. patterns, including `\verb+{...}+' patterns.  The empty pattern is legal
  1733. as well: `\verb+{.pl,}+' matches either `\verb+.pl+' or the empty
  1734. string.
  1735. .C chdir 1 +Path
  1736. Change working directory to {\em Path}.
  1737. .S User Toplevel Manipulation
  1738. .C break 0
  1739. Recursively start a new Prolog top level. This Prolog top level has
  1740. it's own stacks, but shares the heap with all break environments and
  1741. the top level. Debugging is switched off on entering a break and
  1742. restored on leaving one. The break environment is terminated by typing
  1743. the system's \mbox{end-of-file} character (control-D). If the \tty{-t
  1744. toplevel} command line option is given this goal is started instead of
  1745. entering the default interactive top level (prolog/0).
  1746. .C abort 0
  1747. Abort the Prolog execution and start a new top level.  If the
  1748. \tty{-t toplevel} command line options is given this goal is started
  1749. instead of entering the default interactive top level.  Break
  1750. environments are aborted as well.  All open files except for the
  1751. terminal related files are closed.  The input- and output stream again refers
  1752. to {\em user}.%
  1753. \bug{Erased clauses which could not actually be removed from the
  1754. database, because they are active in the interpreter, will never be
  1755. garbage collected after an abort.}
  1756. .C halt 0
  1757. Terminate Prolog execution.  Open files are closed and if the command
  1758. line option \tty{-tty} is not active the terminal status (see Unix
  1759. stty(1)) is restored.
  1760. .C prolog 0
  1761. This goal starts the default interactive top level. prolog/0
  1762. is terminated (succeeds) by typing control-D.
  1763. .S Creating a Protocol of the User Interaction
  1764. SWI-Prolog offers the possibility to log the interaction with the user
  1765. on a file.%
  1766.     \footnote{A similar facility was added to Edinburgh C-Prolog by
  1767.           Wouter Jansweijer.}
  1768. All Prolog interaction, including warnings and tracer output, are written
  1769. on the protocol file.
  1770. .C protocol 1 +File
  1771. Start protocolling on file {\em File}. If there is already a protocol
  1772. file open then close it first. If {\em File} exists it is truncated.
  1773. .C protocola 1 +File
  1774. Equivalent to protocol/1, but does not truncate the {\em File} if it
  1775. exists.
  1776. .C noprotocol 0
  1777. Stop making a protocol of the user interaction.  Pending output is
  1778. flushed on the file.
  1779. .C protocolling 1 -File
  1780. Succeeds if a protocol was started with protocol/1 or protocola/1 and
  1781. unifies {\em File} with the current protocol output file.
  1782. .S Debugging and Tracing Programs
  1783. \label{sec:debugger}
  1784. .C trace 0
  1785. Start the tracer. trace/0 itself cannot be seen in the tracer.  Note that
  1786. the Prolog toplevel treats trace/0 special; it means `trace the next goal'.
  1787. .C tracing 0
  1788. Succeeds when the tracer is currently switched on.  tracing/0 itself can
  1789. not be seen in the tracer.
  1790. .C notrace 0
  1791. Stop the tracer. notrace/0 itself cannot be seen in the tracer.
  1792. .C debug 0
  1793. Start debugger (stop at spy points).
  1794. .C nodebug 0
  1795. Stop debugger (do not trace, nor stop at spy points).
  1796. .C debugging 0
  1797. Print debug status and spy points on current output stream.
  1798. .C spy 1 +Pred
  1799. Put a spy point on all predicates meeting the predicate specification
  1800. {\em Pred}. See section~\ref{listing}.
  1801. .C nospy 1 +Pred
  1802. Remove spy point from all predicates meeting the predicate specification
  1803. {\em Pred}.
  1804. .C nospyall 0
  1805. Remove all spy points from the entire program.
  1806. .C leash 1 ?Ports
  1807. Set/query leashing (ports which allow for user interaction). {\em Ports} is
  1808. one of \tty{+Name}, \tty{-Name}, \tty{?Name} or a list of these.
  1809. \tty{+Name} enables leashing on that port, \tty{-Name} disables it and
  1810. \tty{?Name} succeeds or fails according to the current setting.
  1811. Recognised ports are: \tty{call}, \tty{redo}, \tty{exit}, \tty{fail} and
  1812. \tty{unify}. The special shorthand \tty{all} refers to all ports, 
  1813. \tty{full} refers to all ports except for the unify port (default).
  1814. \tty{half} refers to the \tty{call}, \tty{redo} and \tty{fail}
  1815. port.
  1816. .C visible 1 +Ports
  1817. Set the ports shown by the debugger. See leash/1 for a description of
  1818. the port specification. Default is \tty{full}.
  1819. .C unknown 2 -Old, +New
  1820. Unify {\em Old} with the current value of the unknown system flag.  On
  1821. success {\em New} will be used to specify the new value. {\em New} should be
  1822. instantiated to either \tty{fail} or \tty{trace} and determines the
  1823. interpreter's action when an undefined predicate which is not declared
  1824. dynamic is encountered (see dynamic/1). \tty{fail} implies the predicate
  1825. just fails silently. \tty{trace} implies the tracer is started. Default is
  1826. \tty{trace}.  The unknown flag is local to each module and unknown/2
  1827. is module transparent.  Using it as a directive in a module file will
  1828. only change the unknown flag for that module.  Using the :/2 construct
  1829. the behaviour on trapping an undefined predicate can be changed for
  1830. any module.  Note that if the unknown flag for a module equals \tty
  1831. {fail} the system will not call exception/3 and will {\bf not} try
  1832. to resolve the predicate via the dynamic library system.  The system
  1833. will still try to import the predicate from the public module.
  1834. .C style_check 1 +Spec
  1835. Set style checking options.  {\em Spec} is either \verb@+<option>@, 
  1836. \verb@-<option>@, \verb@?<option>@ or a list of such options.
  1837. \verb@+<option>@ sets a style checking option, \verb@-<option>@ clears
  1838. it and \verb@?<option>@ succeeds or fails according to the current
  1839. setting. consult/1 and derivates resets the style checking options to
  1840. their value before loading the file. If --for example-- a file containing
  1841. long atoms should be loaded the user can start the file with:
  1842. \begin{code}
  1843. :- style_check(-atom).
  1844. \end{code}
  1845. Currently available options are:
  1846. \begin{center}
  1847. \begin{tabular}{|l|c|p{3.5in}|}
  1848. \hline
  1849. Name & Default & Description \\
  1850. \hline
  1851. \tty{singleton}  & on & read_clause/1 (used by consult/1) warns
  1852.                 on variables only appearing once in a term (clause)
  1853.                 which have a name not starting with an underscore. \\
  1854. \tty{atom}     & on & read/1 and derivates will produce an
  1855.                 error message on quoted atoms or strings longer
  1856.                 than 5 lines. \\
  1857. \tty{dollar}     & off & Accept dollar as a lower case character, thus
  1858.                 avoiding the need for quoting atoms with dollar signs.
  1859.                 System maintenance use only. \\        
  1860. \tty{discontiguous} & on & Warn if the clauses for a predicate are not
  1861.                 together in the same source file. \\
  1862. \tty{string}     & off & Read and derivates transform \verb$"..."$ into
  1863.             a prolog string instead of a list of ASCII
  1864.             characters. \\
  1865. \hline
  1866. \end{tabular}
  1867. \end{center}
  1868. .S Obtaining Runtime Statistics
  1869. .C statistics 2 +Key, -Value
  1870. Unify system statistics determined by {\em Key} with {\em Value}. The
  1871. possible keys are given in the table~\ref{tab:statistics}.
  1872. \begin{table}
  1873. \begin{center}
  1874. \begin{tabular}{|l|p{4in}|}
  1875. \hline
  1876. cputime        & (User) cpu time since Prolog was started in seconds \\
  1877. inferences    & Total number of passes via the call and redo ports
  1878.           since Prolog was started. \\
  1879. heapused    & Bytes heap in use. \\
  1880. local        & Allocated size of the local stack in bytes. \\
  1881. localused    & Number of bytes in use on the local stack. \\
  1882. locallimit    & Size to which the local stack is allowed to grow \\
  1883. global        & Allocated size of the global stack in bytes. \\
  1884. globalused    & Number of bytes in use on the global stack. \\
  1885. globallimit    & Size to which the global stack is allowed to grow \\
  1886. trail        & Allocated size of the trail stack in bytes. \\
  1887. trailused    & Number of bytes in use on the trail stack. \\
  1888. traillimit    & Size to which the trail stack is allowed to grow \\
  1889. atoms        & Total number of defined atoms. \\
  1890. functors    & Total number of defined name/arity pairs. \\
  1891. predicates    & Total number of predicate definitions. \\
  1892. modules        & Total number of module definitions. \\
  1893. externals    & Total number of {\em external references} in all
  1894.           clauses. \\
  1895. codes        & Total amount of byte codes in all clauses. \\
  1896. \hline
  1897. \end{tabular}
  1898. \end{center}
  1899.     \caption{Keys for statistics/2}
  1900.     \label{tab:statistics}
  1901. \end{table}
  1902. .C statistics 0
  1903. Display a table of system statistics on the current output stream.
  1904. .C time 1 +Goal
  1905. Execute {\em Goal} just like once/1 (i.e. leaving no choice points),
  1906. but print used time, number of logical inferences and the average
  1907. number of {\em lips} (logical inferences per second).  Note that
  1908. SWI-Prolog counts the actual executed number of inferences rather than
  1909. the number of passes through the call- and redo ports of the
  1910. theoretical 4-port model.
  1911. .S Finding Performance Bottlenecks
  1912. SWI-Prolog offers a statistical program profiler similar to Unix prof(1)
  1913. for C and some other languages.  A profiler is used as an aid to find
  1914. performance pigs in programs.  It provides information on the time spent
  1915. in the various Prolog predicates.
  1916. The profiler is based on the assumption that if we monitor the functions
  1917. on the execution stack on time intervals not correlated to the program's
  1918. execution the number of times we find a procedure on the environment
  1919. stack is a measure of the time spent in this procedure.  It is
  1920. implemented by calling a procedure each time slice Prolog is active.
  1921. This procedure scans the local stack and either just counts the
  1922. procedure on top of this stack (\tty{plain} profiling) or all procedures
  1923. on the stack (\tty{cummulative} profiling).  To get accurate results
  1924. each procedure one is interested in should have a reasonable number of
  1925. counts.  Typically a minute runtime will suffice to get a rough overview
  1926. of the most expensive procedures.
  1927. .C profile 3 +Goal, +Style, +Number
  1928. Execute {\em Goal} just like time/1. Collect profiling statistics
  1929. according to style (see profiler/2) and show the top {\em Number}
  1930. procedures on the current output stream (see show_profile/1). The
  1931. results are kept in the database until reset_profiler/0 or profile/3
  1932. is called and can be displayed again with show_profile/1. profile/3
  1933. is the normal way to invoke the profiler. The predicates below
  1934. are low-level predicates that can be used for special cases.
  1935. .C show_profile 1 +Number
  1936. Show the collected results of the profiler. Stops the profiler first to
  1937. avoid interference from show_profile/1. It shows the top {\em Number}
  1938. predicates according the percentage cpu-time used%
  1939.     \footnote{show_profile/1 is defined in Prolog and takes a
  1940.           considerable amount of memory.}.
  1941. .C profiler 2 -Old, +New
  1942. Query or change the status of the profiler. The status is one of
  1943. \tty{off}, \tty{plain} or \tty{cummulative}. \tty{plain} implies the
  1944. time used by childs of a predicate is not added to the time of the
  1945. predicate. For status \tty{cummulative} the time of childs is added
  1946. (except for recursive calls). Cummulative profiling implies the stack
  1947. is scanned upto the top on each time slice to find all active
  1948. predicates.  This implies the overhead grows with the number of active
  1949. frames on the stack.  Cummulative profiling starts debugging mode
  1950. to disable tail recursion optimisation, which would otherwise
  1951. remove the necessary parent environments.  Switching status from
  1952. \tty{plain} to \tty{cummulative} resets the profiler.  Switching to and
  1953. from status \tty{off} does not reset the collected statistics, thus
  1954. allowing to suspend profiling for certain parts of the program.
  1955. .C reset_profiler 0
  1956. Switches the profiler to \tty{off} and clears all collected statistics.
  1957. .C profile_count 3 +Head, -Calls, -Promilage
  1958. Obtain profile statistics of the predicate specified by {\em Head}.
  1959. {\em Head} is an atom for predicates with arity 0 or a term with the
  1960. same name and arity as the predicate required (see
  1961. current_predicate/2). {\em Calls} is unified with the number of `calls'
  1962. and `redos' while the profiler was active. {\em Promilage} is unified
  1963. with the relative number of counts the predicate was active
  1964. (\tty{cummulative}) or on top of the stack (\tty{plain}). {\em Promilage}
  1965. is an integer between 0 and 1000.
  1966. .S Memory Management
  1967. Note: limit_stack/2 and trim_stacks/0 have no effect on machines that do
  1968. not offer dynamic stack expansion.  On these machines these predicates
  1969. simply succeed to improve portability.
  1970. .C garbage_collect 0
  1971. Invoke the global- and trail stack garbage collector.  Normally the
  1972. garbage collector is invoked automatically if necessary.  Explicit
  1973. invokation might be useful to reduce the need for garbage collections in
  1974. time critical segments of the code.  After the garbage collection
  1975. trim_stacks/0 is invoked to release the collected memory resources.
  1976. .C limit_stack 2 +Key, +Kbytes
  1977. Limit one of the stack areas to the specified value. {\em Key} is one
  1978. of \tty{local}, \tty{global} or \tty{trail}. The limit is an integer,
  1979. expressing the desired stack limit in K bytes.  If the desired limit is
  1980. smaller than the currently used value, the limit is set to the
  1981. nearest legal value above the currently used value.  If the desired
  1982. value is larger than the maximum, the maximum is taken.  Finally, if
  1983. the desired value is either 0 or the atom \tty{unlimited} the limit
  1984. is set to its maximum.  The maximum and initial limit is determined
  1985. by the command line options \tty{-L}, \tty{-G} and \tty{-T}.
  1986. .C trim_stacks 0
  1987. Release stack memory resources that are not in use at this moment,
  1988. returning them to the operating system.  Trim stack is a relatively
  1989. cheap call.  It can be used to release memory resources in a
  1990. backtracking loop, where the iterations require typically seconds of
  1991. execution time and very different, potentionally large, amounts of
  1992. stack space.  Such a loop should be written as follows:
  1993. \begin{boxed}\begin{code}
  1994. loop :-
  1995.     generator,
  1996.         trim_stacks,
  1997.         potentionally_expensive_operation,
  1998.     stop_condition, !.
  1999. \end{code}\end{boxed}
  2000. The prolog top level loop is written this way, reclaiming memory
  2001. resources after every user query.
  2002. .S Miscellaneous
  2003. .C dwim_match 2 +Atom1, +Atom2
  2004. Succeeds if {\em Atom1} matches {\em Atom2} in `Do What I Mean' sence.
  2005. Both {\em Atom1} and {\em Atom2} may also be integers or floats.
  2006. The two atoms match if:
  2007. \begin{shortlist}
  2008.     \item They are identical
  2009.     \item They differ by one character (spy $\equiv$ spu)
  2010.     \item One character is insterted/deleted (debug $\equiv$ deug)
  2011.     \item Two characters are transposed (trace $\equiv$ tarce)
  2012.     \item `Sub-words' are glued differently (existsfile $\equiv$ existsFile $\equiv$ exists_file)
  2013.     \item Two adjacent sub words are transposed (existsFile $\equiv$ fileExists)
  2014. \end{shortlist}
  2015. .C dwim_match 3 +Atom1, +Atom2, -Difference
  2016. Equivalent to dwim_match/2, but unifies {\em Difference} with an atom
  2017. identifying the the difference between {\em Atom1} and {\em Atom2}.  The
  2018. return values are (in the same order as above): \tty{equal},
  2019. \tty{mismatched_char}, \tty{inserted_char}, \tty{transposed_char},
  2020. \tty{separated} and \tty{transposed_word}.
  2021. .C wildcard_match 2 +Pattern, +String
  2022. Succeeds if {\em String} matches the wildcard pattern {\em Pattern}. {\em
  2023. Pattern} is very similar the the Unix csh pattern matcher.  The patterns
  2024. are given below:
  2025. \begin{center}\begin{tabular}{ll}
  2026. \tt ?        & Matches one arbitrary character \\
  2027. \tt *        & Matches any number of arbitrary characters \\
  2028. \tt [...]    & Matches one of the characters specified at \verb@...@
  2029.           \verb@<char>-<char>@ indicates a range. \\
  2030. \tt \{...\}    & Matches any of the patterns of the comma separated list
  2031.           between the brackets.
  2032. \end{tabular}\end{center}
  2033. Example:
  2034. \begin{code}
  2035. ?- wildcard_match('[a-z]*.{pro,pl}[%~]', 'a_hello.pl%').
  2036. \end{code}
  2037. .C gensym 2 +Base, -Unique
  2038. Generate a unique atom from base {\em Base} and unify it with {\em Unique}.
  2039. {\em Base} should be an atom. The first call will return \verb+<base>1+, 
  2040. the next \verb+<base>2+, etc. Note that this is no warrant that the atom
  2041. is unique in the system.%
  2042. \bug{I plan to supply a real gensym/2 which does give this warrant for
  2043. future versions.}
  2044. .C sleep 1 +Time
  2045. Suspend execution {\em Time} seconds.  {\em Time} is either a floating
  2046. point number or an integer.  Granularity is dependent on the system's
  2047. timer granularity (1/60 seconds on most Unix systems).  A negative
  2048. time causes the timer to return immediately.  As Unix is a multi-tasking
  2049. environment we can only ensure execution is suspended for {\sl at least}
  2050. {\em Time} seconds.
  2051.