diff --git a/docs/builtins.tex b/docs/builtins.tex new file mode 100644 index 000000000..e8905ecd2 --- /dev/null +++ b/docs/builtins.tex @@ -0,0 +1,6150 @@ +@c -*- mode: texinfo; coding: utf-8; -* + +@node Built-ins, Library, Modules, Top + +@chapter Built-In Predicates + +@menu + +Built-ins, Debugging, Syntax, Top +* Control:: Controlling the Execution of Prolog Programs +* Undefined Procedures:: Handling calls to Undefined Procedures +* Messages:: Message Handling in YAP +* Testing Terms:: Predicates on Terms +* Predicates on Atoms:: Manipulating Atoms +* Predicates on Characters:: Manipulating Characters +* Comparing Terms:: Comparison of Terms +* Arithmetic:: Arithmetic in YAP +* I/O:: Input/Output with YAP +* Database:: Modifying Prolog's Database +* Sets:: Finding All Possible Solutions +* Grammars:: Grammar Rules +* Preds:: Predicate Information +* OS:: Access to Operating System Functionality +* Term Modification:: Updating Prolog Terms +* Global Variables:: Manipulating Global Variables +* Profiling:: Profiling Prolog Execution +* Call Counting:: Limiting the Maximum Number of Reductions +* Arrays:: Supporting Global and Local Arrays +* Preds:: Information on Predicates +* Misc:: Miscellaneous Predicates + +@end menu + +@node Control, Undefined Procedures, , Top +@section Control Predicates + + +This chapter describes the predicates for controlling the execution of +Prolog programs. + +In the description of the arguments of functors the following notation +will be used: + +@itemize @bullet +@item +a preceding plus sign will denote an argument as an "input argument" - +it cannot be a free variable at the time of the call; +@item + a preceding minus sign will denote an "output argument"; +@item +an argument with no preceding symbol can be used in both ways. +@end itemize + + +@table @code + +@item +@var{P}, +@var{Q} [ISO] +@findex ,/2 +@syindex ,/2 +@cyindex ,/2 +Conjunction of goals (and). + +@noindent +Example: +@example + p(X) :- q(X), r(X). +@end example + +@noindent +should be read as "p(@var{X}) if q(@var{X}) and r(@var{X})". + +@item +@var{P} ; +@var{Q} [ISO] +@findex ;/2 +@syindex ;/2 +@cyindex ;/2 +Disjunction of goals (or). + +@noindent +Example: +@example + p(X) :- q(X); r(X). +@end example +@noindent +should be read as "p(@var{X}) if q(@var{X}) or r(@var{X})". + +@item true [ISO] +@findex true/0 +@syindex true/0 +@cyindex true/0 +Succeeds once. + +@item fail [ISO] +@findex fail/0 +@syindex fail/0 +@cyindex fail/0 +Fails always. + +@item false [ISO] +@findex false/0 +@syindex false/0 +@cnindex false/0 +The same as fail + +@item ! [ISO] +@findex !/0 +@syindex !/0 +@cyindex !/0 + Read as "cut". Cuts any choices taken in the current procedure. +When first found "cut" succeeds as a goal, but if backtracking should +later return to it, the parent goal (the one which matches the head of +the clause containing the "cut", causing the clause activation) will +fail. This is an extra-logical predicate and cannot be explained in +terms of the declarative semantics of Prolog. + +example: + +@example + member(X,[X|_]). + member(X,[_|L]) :- member(X,L). +@end example + +@noindent +With the above definition + +@example + ?- member(X,[1,2,3]). +@end example + +@noindent +will return each element of the list by backtracking. With the following +definition: + +@example + member(X,[X|_]) :- !. + member(X,[_|L]) :- member(X,L). +@end example + +@noindent +the same query would return only the first element of the +list, since backtracking could not "pass through" the cut. + +@item \+ +@var{P} [ISO] +@findex \+/1 +@syindex \+/1 +@cyindex \+/1 +Goal @var{P} is not provable. The execution of this predicate fails if +and only if the goal @var{P} finitely succeeds. It is not a true logical +negation, which is impossible in standard Prolog, but +"negation-by-failure". + +@noindent +This predicate might be defined as: +@example + \+(P) :- P, !, fail. + \+(_). +@end example +@noindent +if @var{P} did not include "cuts". + +@item not +@var{P} +@findex not/1 +@snindex not/1 +@cyindex not/1 +Goal @var{P} is not provable. The same as @code{'\+ @var{P}'}. + +This predicate is kept for compatibility with C-Prolog and previous +versions of YAP. Uses of @code{not/1} should be replace by +@code{(\+)/1}, as YAP does not implement true negation. + +@item +@var{P} -> +@var{Q} [ISO] +@findex ->/2 +@syindex ->/2 +@cnindex ->/2 +Read as "if-then-else" or "commit". This operator is similar to the +conditional operator of imperative languages and can be used alone or +with an else part as follows: + +@table @code +@item +P -> +Q +"if P then Q". +@item +P -> +Q; +R +"if P then Q else R". +@end table + +@noindent +These two predicates could be defined respectively in Prolog as: +@example + (P -> Q) :- P, !, Q. +@end example +@noindent +and +@example + (P -> Q; R) :- P, !, Q. + (P -> Q; R) :- R. +@end example +@noindent +if there were no "cuts" in @var{P}, @var{Q} and @var{R}. + +Note that the commit operator works by "cutting" any alternative +solutions of @var{P}. + +Note also that you can use chains of commit operators like: +@example + P -> Q ; R -> S ; T. +@end example +@noindent +Note that @code{(->)/2} does not affect the scope of cuts in its +arguments. + +@item +@var{Condition} *-> +@var{Action} ; +@var{Else} +@findex ->*/2 +@snindex ->*/2 +@cnindex ->*/2 +This construct implements the so-called @emph{soft-cut}. The control is + defined as follows: If @var{Condition} succeeds at least once, the + semantics is the same as (@var{Condition}, @var{Action}). If + @var{Condition} does not succeed, the semantics is that of (\+ + @var{Condition}, @var{Else}). In other words, If @var{Condition} + succeeds at least once, simply behave as the conjunction of + @var{Condition} and @var{Action}, otherwise execute @var{Else}. + + The construct @var{A *-> B}, i.e. without an @var{Else} branch, is +translated as the normal conjunction @var{A}, @var{B}. + +@item repeat [ISO] +@findex repeat/0 +@syindex repeat/0 +@cyindex repeat/0 +Succeeds repeatedly. + +In the next example, @code{repeat} is used as an efficient way to implement +a loop. The next example reads all terms in a file: + +@example + a :- repeat, read(X), write(X), nl, X=end_of_file, !. +@end example +@noindent +the loop is effectively terminated by the cut-goal, when the test-goal +@code{X=end} succeeds. While the test fails, the goals @code{read(X)}, +@code{write(X)}, and @code{nl} are executed repeatedly, because +backtracking is caught by the @code{repeat} goal. + +The built-in @code{repeat/1} could be defined in Prolog by: +@example + repeat. + repeat :- repeat. +@end example + +@item call(+@var{P}) [ISO] +@findex call/1 +@syindex call/1 +@cyindex call/1 + If @var{P} is instantiated to an atom or a compound term, the goal +@code{call(@var{P})} is executed as if the value of @code{P} was found +instead of the call to @code{call/1}, except that any "cut" occurring in +@var{P} only cuts alternatives in the execution of @var{P}. + +@item incore(+@var{P}) +@findex incore/1 +@syindex incore/1 +@cnindex incore/1 +The same as @code{call/1}. + +@item call(+@var{Closure},...,?@var{Ai},...) [ISO] +@findex call/n +@snindex call/n +@cnindex call/n +Meta-call where @var{Closure} is a closure that is converted into a goal by +appending the @var{Ai} additional arguments. The number of arguments varies +between 0 and 10. + +@item call_with_args(+@var{Name},...,?@var{Ai},...) +@findex call_with_args/n +@snindex call_with_args/n +@cnindex call_with_args/n +Meta-call where @var{Name} is the name of the procedure to be called and +the @var{Ai} are the arguments. The number of arguments varies between 0 +and 10. New code should use @code{call/N} for better portability. + +If @var{Name} is a complex term, then @code{call_with_args/n} behaves as +@code{call/n}: + +@example +call(p(X1,...,Xm), Y1,...,Yn) :- p(X1,...,Xm,Y1,...,Yn). +@end example + + +@item +@var{P} +@findex var_call/1 + The same as @code{call(@var{P})}. This feature has been kept to provide +compatibility with C-Prolog. When compiling a goal, YAP +generates a @code{call(@var{X})} whenever a variable @var{X} is found as +a goal. + +@example + a(X) :- X. +@end example +@noindent +is converted to: +@example + a(X) :- call(X). +@end example + +@item if(?@var{G},?@var{H},?@var{I}) +@findex if/3 +@syindex if/3 +@cnindex if/3 +Call goal @var{H} once per each solution of goal @var{H}. If goal +@var{H} has no solutions, call goal @var{I}. + +The built-in @code{if/3} is similar to @code{->/3}, with the difference +that it will backtrack over the test goal. Consider the following +small data-base: + +@example +a(1). b(a). c(x). +a(2). b(b). c(y). +@end example + +Execution of an @code{if/3} query will proceed as follows: + +@example + ?- if(a(X),b(Y),c(Z)). + +X = 1, +Y = a ? ; + +X = 1, +Y = b ? ; + +X = 2, +Y = a ? ; + +X = 2, +Y = b ? ; + +no +@end example + + +@noindent +The system will backtrack over the two solutions for @code{a/1} and the +two solutions for @code{b/1}, generating four solutions. + +Cuts are allowed inside the first goal @var{G}, but they will only prune +over @var{G}. + +If you want @var{G} to be deterministic you should use if-then-else, as +it is both more efficient and more portable. + +@item once(:@var{G}) [ISO] +@findex once/1 +@snindex once/1 +@cnindex once/1 +Execute the goal @var{G} only once. The predicate is defined by: + +@example + once(G) :- call(G), !. +@end example + +@noindent +Note that cuts inside @code{once/1} can only cut the other goals inside +@code{once/1}. + +@item forall(:@var{Cond},:@var{Action}) +@findex forall/2 +@snindex forall/2 +@cnindex forall/2 +For all alternative bindings of @var{Cond} @var{Action} can be +proven. The example verifies that all arithmetic statements in the list +@var{L} are correct. It does not say which is wrong if one proves wrong. + +@example +?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), + Result =:= Formula). +@end example + +@item ignore(:@var{Goal}) +@findex ignore/1 +@snindex ignore/1 +@cnindex ignore/1 +Calls @var{Goal} as @code{once/1}, but succeeds, regardless of whether +@code{Goal} succeeded or not. Defined as: + +@example +ignore(Goal) :- + Goal, !. +ignore(_). +@end example + +@item abort +@findex abort/0 +@syindex abort/0 +@cyindex abort/0 +Abandons the execution of the current goal and returns to top level. All +break levels (see @code{break/0} below) are terminated. It is mainly +used during debugging or after a serious execution error, to return to +the top-level. + + +@item break +@findex break/0 +@syindex break/0 +@cyindex break/0 +Suspends the execution of the current goal and creates a new execution +level similar to the top level, displaying the following message: + +@example + [ Break (level ) ] +@end example +@noindent +telling the depth of the break level just entered. To return to the +previous level just type the end-of-file character or call the +end_of_file predicate. This predicate is especially useful during +debugging. + +@item halt [ISO] +@findex halt/0 +@syindex halt/0 +@cyindex halt/0 +Halts Prolog, and exits to the calling application. In YAP, +@code{halt/0} returns the exit code @code{0}. + +@item halt(+ @var{I}) [ISO] +@findex halt/1 +@syindex halt/1 +@cnindex halt/1 +Halts Prolog, and exits to the calling application returning the code +given by the integer @var{I}. + +@item catch(+@var{Goal},+@var{Exception},+@var{Action}) [ISO] +@findex catch/3 +@snindex catch/3 +@cnindex catch/3 +The goal @code{catch(@var{Goal},@var{Exception},@var{Action})} tries to +execute goal @var{Goal}. If during its execution, @var{Goal} throws an +exception @var{E'} and this exception unifies with @var{Exception}, the +exception is considered to be caught and @var{Action} is executed. If +the exception @var{E'} does not unify with @var{Exception}, control +again throws the exception. + +The top-level of YAP maintains a default exception handler that +is responsible to capture uncaught exceptions. + +@item throw(+@var{Ball}) [ISO] +@findex throw/1 +@snindex throw/1 +@cnindex throw/1 +The goal @code{throw(@var{Ball})} throws an exception. Execution is +stopped, and the exception is sent to the ancestor goals until reaching +a matching @code{catch/3}, or until reaching top-level. + +@item garbage_collect +@findex garbage_collect/0 +@syindex garbage_collect/0 +@cnindex garbage_collect/0 +The goal @code{garbage_collect} forces a garbage collection. + +@item garbage_collect_atoms +@findex garbage_collect_atoms/0 +@syindex garbage_collect_atoms/0 +@cnindex garbage_collect_atoms/0 +The goal @code{garbage_collect} forces a garbage collection of the atoms +in the data-base. Currently, only atoms are recovered. + +@item gc +@findex gc/0 +@syindex gc/0 +@cnindex gc/0 +The goal @code{gc} enables garbage collection. The same as +@code{yap_flag(gc,on)}. + +@item nogc +@findex nogc/0 +@syindex nogc/0 +@cnindex nogc/0 +The goal @code{nogc} disables garbage collection. The same as +@code{yap_flag(gc,off)}. + +@item grow_heap(+@var{Size}) +@findex grow_heap/1 +@snindex grow_heap/1 +@cnindex grow_heap/1 +Increase heap size @var{Size} kilobytes. + +@item grow_stack(+@var{Size}) +@findex grow_stack/1 +@snindex grow_stack/1 +@cnindex grow_stack/1 +Increase stack size @var{Size} kilobytes. + +@end table + +@node Undefined Procedures, Messages, Control, Top +@section Handling Undefined Procedures + +A predicate in a module is said to be undefined if there are no clauses +defining the predicate, and if the predicate has not been declared to be +dynamic. What YAP does when trying to execute undefined predicates can +be specified in three different ways: +@itemize @bullet +@item By setting an YAP flag, through the @code{yap_flag/2} or +@code{set_prolog_flag/2} built-ins. This solution generalizes the +ISO standard. +@item By using the @code{unknown/2} built-in (this solution is +compatible with previous releases of YAP). +@item By defining clauses for the hook predicate +@code{user:unknown_predicate_handler/3}. This solution is compatible +with SICStus Prolog. +@end itemize + +In more detail: +@table @code +@item unknown(-@var{O},+@var{N}) +@findex unknown/2 +@saindex unknown/2 +@cnindex unknown/2 +Specifies an handler to be called is a program tries to call an +undefined static procedure @var{P}. + +The arity of @var{N} may be zero or one. If the arity is @code{0}, the +new action must be one of @code{fail}, @code{warning}, or +@code{error}. If the arity is @code{1}, @var{P} is an user-defined +handler and at run-time, the argument to the handler @var{P} will be +unified with the undefined goal. Note that @var{N} must be defined prior +to calling @code{unknown/2}, and that the single argument to @var{N} must +be unbound. + +In YAP, the default action is to @code{fail} (note that in the ISO +Prolog standard the default action is @code{error}). + +After defining @code{undefined/1} by: +@example +undefined(A) :- format('Undefined predicate: ~w~n',[A]), fail. +@end example +@noindent +and executing the goal: +@example +unknown(U,undefined(X)). +@end example +@noindent +a call to a predicate for which no clauses were defined will result in +the output of a message of the form: +@example +Undefined predicate: user:xyz(A1,A2) +@end example +@noindent +followed by the failure of that call. + +@item yap_flag(unknown,+@var{SPEC}) +@findex yap_flag_unknown/1 +Alternatively, one can use @code{yap_flag/2}, +@code{current_prolog_flag/2}, or @code{set_prolog_flag/2}, to set this +functionality. In this case, the first argument for the built-ins should +be @code{unknown}, and the second argument should be either +@code{error}, @code{warning}, @code{fail}, or a goal. + +@item user:unknown_predicate_handler(+G,+M,?NG) +@findex unknown_predicate_handler/3 +@syindex unknown_predicate_handler/3 +@cnindex unknown_predicate_handler/3 +The user may also define clauses for +@code{user:unknown_predicate_handler/3} hook predicate. This +user-defined procedure is called before any system processing for the +undefined procedure, with the first argument @var{G} set to the current +goal, and the second @var{M} set to the current module. The predicate +@var{G} will be called from within the user module. + +If @code{user:unknown_predicate_handler/3} succeeds, the system will +execute @var{NG}. If @code{user:unknown_predicate_handler/3} fails, the +system will execute default action as specified by @code{unknown/2}. + +@item exception(+@var{Exception}, +@var{Context}, -@var{Action}) +@findex exception/3 +@syindex exception/3 +@cnindex exception/3 + Dynamic predicate, normally not defined. Called by the Prolog system on run-time exceptions that can be repaired `just-in-time'. The values for @var{Exception} are described below. See also @code{catch/3} and @code{throw/1}. +If this hook predicate succeeds it must instantiate the @var{Action} argument to the atom @code{fail} to make the operation fail silently, @code{retry} to tell Prolog to retry the operation or @code{error} to make the system generate an exception. The action @code{retry} only makes sense if this hook modified the environment such that the operation can now succeed without error. + +@table @code +@item undefined_predicate +@var{Context} is instantiated to a predicate-indicator (@var{Module:Name/Arity}). If the predicate fails Prolog will generate an existence_error exception. The hook is intended to implement alternatives to the SWI built-in autoloader, such as autoloading code from a database. Do not use this hook to suppress existence errors on predicates. See also @code{unknown}. +@item undefined_global_variable +@var{Context} is instantiated to the name of the missing global variable. The hook must call @code{nb_setval/2} or @code{b_setval/2} before returning with the action retry. +@end table + +@end table + +@node Messages, Testing Terms, Undefined Procedures, Top +@section Message Handling + +The interaction between YAP and the user relies on YAP's ability to +portray messages. These messages range from prompts to error +information. All message processing is performed through the builtin +@code{print_message/2}, in two steps: + +@itemize @bullet +@item The message is processed into a list of commands +@item The commands in the list are sent to the @code{format/3} builtin +in sequence. +@end itemize + +The first argument to @code{print_message/2} specifies the importance of +the message. The options are: + +@table @code +@item error +error handling +@item warning +compilation and run-time warnings, +@item informational +generic informational messages +@item help +help messages (not currently implemented in YAP) +@item query +query used in query processing (not currently implemented in YAP) +@item silent +messages that do not produce output but that can be intercepted by hooks. +@end table + +The next table shows the main predicates and hooks associated to message +handling in YAP: +@table @code +@item print_message(+@var{Kind}, @var{Term}) +@findex print_message/2 +@syindex print_message/2 +@cnindex print_message/2 +The predicate print_message/2 is used to print messages, notably from +exceptions in a human-readable format. @var{Kind} is one of +@code{informational}, @code{banner}, @code{warning}, @code{error}, +@code{help} or @code{silent}. A human-readable message is printed to +the stream @code{user_error}. + +@c \index{silent}\index{quiet}% +If the Prolog flag @code{verbose} is @code{silent}, messages with +@var{Kind} @code{informational}, or @code{banner} are treated as +silent.@c See \cmdlineoption{-q}. + +This predicate first translates the @var{Term} into a list of `message +lines' (see @code{print_message_lines/3} for details). Next it will +call the hook @code{message_hook/3} to allow the user intercepting the +message. If @code{message_hook/3} fails it will print the message unless +@var{Kind} is silent. + +@c The print_message/2 predicate and its rules are in the file +@c \file{/boot/messages.pl}, which may be inspected for more +@c information on the error messages and related error terms. +If you need to report errors from your own predicates, we advise you to +stick to the existing error terms if you can; but should you need to +invent new ones, you can define corresponding error messages by +asserting clauses for @code{prolog:message/2}. You will need to declare +the predicate as multifile. + +@c See also message_to_string/2. + +@item print_message_lines(+@var{Stream}, +@var{Prefix}, +@var{Lines}) +@findex print_message_lines/3 +@syindex print_message_lines/3 +@cnindex print_message_lines/3 +Print a message (see @code{print_message/2}) that has been translated to +a list of message elements. The elements of this list are: + +@table @code + @item @code{}-@code{} + Where @var{Format} is an atom and @var{Args} is a list + of format argument. Handed to @code{format/3}. + @item @code{flush} + If this appears as the last element, @var{Stream} is flushed + (see @code{flush_output/1}) and no final newline is generated. + @item @code{at_same_line} + If this appears as first element, no prefix is printed for + the first line and the line-position is not forced to 0 + (see @code{format/1}, @code{~N}). + @item @code{} + Handed to @code{format/3} as @code{format(Stream, Format, [])}. + @item nl + A new line is started and if the message is not complete + the @var{Prefix} is printed too. +@end table + +@item user:message_hook(+@var{Term}, +@var{Kind}, +@var{Lines}) +@findex message_hook/3 +@syindex message_hook/3 +@cnindex message_hook/3 +Hook predicate that may be define in the module @code{user} to intercept +messages from @code{print_message/2}. @var{Term} and @var{Kind} are the +same as passed to @code{print_message/2}. @var{Lines} is a list of +format statements as described with @code{print_message_lines/3}. + +This predicate should be defined dynamic and multifile to allow other +modules defining clauses for it too. + +@item message_to_string(+@var{Term}, -@var{String}) +@findex message_to_string/2 +@snindex message_to_string/2 +@cnindex message_to_string/2 +Translates a message-term into a string object. Primarily intended for SWI-Prolog emulation. +@end table + +@node Testing Terms, Predicates on Atoms, Messages, Top +@section Predicates on terms + +@table @code + +@item var(@var{T}) [ISO] +@findex var/1 +@syindex var/1 +@cyindex var/1 +Succeeds if @var{T} is currently a free variable, otherwise fails. + +@item atom(@var{T}) [ISO] +@findex atom/1 +@syindex atom/1 +@cyindex atom/1 +Succeeds if and only if @var{T} is currently instantiated to an atom. + +@item atomic(T) [ISO] +@findex atomic/1 +@syindex atomic/1 +@cyindex atomic/1 +Checks whether @var{T} is an atomic symbol (atom or number). + +@item compound(@var{T}) [ISO] +@findex compound/1 +@syindex compound/1 +@cnindex compound/1 +Checks whether @var{T} is a compound term. + +@item db_reference(@var{T}) +@findex db_reference/1C +@syindex db_reference/1 +@cyindex db_reference/1 +Checks whether @var{T} is a database reference. + +@item float(@var{T}) [ISO] +@findex float/1 +@syindex float/1 +@cnindex float/1 +Checks whether @var{T} is a floating point number. + +@item rational(@var{T}) +@findex rational/1 +@syindex rational/1 +@cyindex rational/1 +Checks whether @code{T} is a rational number. + +@item integer(@var{T}) [ISO] +@findex integer/1 +@syindex integer/1 +@cyindex integer/1 +Succeeds if and only if @var{T} is currently instantiated to an integer. + +@item nonvar(@var{T}) [ISO] +@findex nonvar/1 +@syindex nonvar/1 +@cyindex nonvar/1 +The opposite of @code{var(@var{T})}. + +@item number(@var{T}) [ISO] +@findex number/1 +@syindex number/1 +@cyindex number/1 +Checks whether @code{T} is an integer, rational or a float. + +@item primitive(@var{T}) +@findex primitive/1 +@syindex primitive/1 +@cyindex primitive/1 +Checks whether @var{T} is an atomic term or a database reference. + +@item simple(@var{T}) +@findex simple/1 +@syindex simple/1 +@cnindex simple/1 +Checks whether @var{T} is unbound, an atom, or a number. + +@item callable(@var{T}) [ISO] +@findex callable/1 +@syindex callable/1 +@cnindex callable/1 +Checks whether @var{T} is a callable term, that is, an atom or a +compound term. + +@item numbervars(@var{T},+@var{N1},-@var{Nn}) +@findex numbervars/3 +@syindex numbervars/3 +@cnindex numbervars/3 +Instantiates each variable in term @var{T} to a term of the form: +@code{'$VAR'(@var{I})}, with @var{I} increasing from @var{N1} to @var{Nn}. + +@item unnumbervars(@var{T},+@var{NT}) +@findex unnumbervars/2 +@syindex unnumbervars/2 +@cnindex unnumbervars/2 +Replace every @code{'$VAR'(@var{I})} by a free variable. + +@item ground(@var{T}) [ISO] +@findex ground/1 +@syindex ground/1 +@cnindex ground/1 +Succeeds if there are no free variables in the term @var{T}. + +@item acyclic_term(@var{T}) [ISO] +@findex acyclic_term/1 +@snindex acyclic_term/1 +@cnindex acyclic_term/1 +Succeeds if there are loops in the term @var{T}, that is, it is an infinite term. + +@item arg(+@var{N},+@var{T},@var{A}) [ISO] +@findex arg/3 +@syindex arg/3 +@cnindex arg/3 +Succeeds if the argument @var{N} of the term @var{T} unifies with +@var{A}. The arguments are numbered from 1 to the arity of the term. + +The current version will generate an error if @var{T} or @var{N} are +unbound, if @var{T} is not a compound term, of if @var{N} is not a positive +integer. Note that previous versions of YAP would fail silently +under these errors. + +@item functor(@var{T},@var{F},@var{N}) [ISO] +@findex functor/3 +@syindex functor/3 +@cyindex functor/3 +The top functor of term @var{T} is named @var{F} and has arity @var{N}. + +When @var{T} is not instantiated, @var{F} and @var{N} must be. If +@var{N} is 0, @var{F} must be an atomic symbol, which will be unified +with @var{T}. If @var{N} is not 0, then @var{F} must be an atom and +@var{T} becomes instantiated to the most general term having functor +@var{F} and arity @var{N}. If @var{T} is instantiated to a term then +@var{F} and @var{N} are respectively unified with its top functor name +and arity. + +In the current version of YAP the arity @var{N} must be an +integer. Previous versions allowed evaluable expressions, as long as the +expression would evaluate to an integer. This feature is not available +in the ISO Prolog standard. + +@item @var{T} =.. @var{L} [ISO] +@findex =../2 +@syindex =../2 +@cyindex =../2 +The list @var{L} is built with the functor and arguments of the term +@var{T}. If @var{T} is instantiated to a variable, then @var{L} must be +instantiated either to a list whose head is an atom, or to a list +consisting of just a number. + +@item @var{X} = @var{Y} [ISO] +@findex =/2 +@syindex =/2 +@cnindex =/2 +Tries to unify terms @var{X} and @var{Y}. + +@item @var{X} \= @var{Y} [ISO] +@findex \=/2 +@snindex \=/2 +@cnindex \=/2 +Succeeds if terms @var{X} and @var{Y} are not unifiable. + +@item unify_with_occurs_check(?T1,?T2) [ISO] +@findex unify_with_occurs_check/2 +@syindex unify_with_occurs_check/2 +@cnindex unify_with_occurs_check/2 +Obtain the most general unifier of terms @var{T1} and @var{T2}, if there +is one. + +This predicate implements the full unification algorithm. An example:n +@example +unify_with_occurs_check(a(X,b,Z),a(X,A,f(B)). +@end example +@noindent +will succeed with the bindings @code{A = b} and @code{Z = f(B)}. On the +other hand: +@example +unify_with_occurs_check(a(X,b,Z),a(X,A,f(Z)). +@end example +@noindent +would fail, because @code{Z} is not unifiable with @code{f(Z)}. Note that +@code{(=)/2} would succeed for the previous examples, giving the following +bindings @code{A = b} and @code{Z = f(Z)}. + + +@item copy_term(?@var{TI},-@var{TF}) [ISO] +@findex copy_term/2 +@syindex copy_term/2 +@cnindex copy_term/2 +Term @var{TF} is a variant of the original term @var{TI}, such that for +each variable @var{V} in the term @var{TI} there is a new variable @var{V'} +in term @var{TF}. Notice that: + +@itemize @bullet +@item suspended goals and attributes for attributed variables in + @var{TI} are also duplicated; +@item ground terms are shared between the new and the old term. +@end itemize + +If you do not want any sharing to occur please use +@code{duplicate_term/2}. + +@item duplicate_term(?@var{TI},-@var{TF}) +@findex duplicate_term/2 +@syindex duplicate_term/2 +@cnindex duplicate_term/2 +Term @var{TF} is a variant of the original term @var{TI}, such that +for each variable @var{V} in the term @var{TI} there is a new variable +@var{V'} in term @var{TF}, and the two terms do not share any +structure. All suspended goals and attributes for attributed variables +in @var{TI} are also duplicated. + +Also refer to @code{copy_term/2}. + +@item is_list(+@var{List}) +@findex is_list/1 +@syindex is_list/1 +@cnindex is_list/1 +True when @var{List} is a proper list. That is, @var{List} +is bound to the empty list (nil) or a term with functor '.' and arity 2. + +@item ?@var{Term1} =@@= ?@var{Term2} +@findex =@=/2 +@syindex =@=/2 +@cnindex =@=/2 + +Same as @code{variant/2}, succeeds if @var{Term1} and @var{Term2} are variant terms. + + +@item subsumes_term(?@var{Subsumer}, ?@var{Subsumed}) +@findex subsumes_term/2 +@syindex subsumes_term/2 +@cnindex subsumes_term/2 + +Succeed if @var{Submuser} subsumes @var{Subsuned} but does not bind any +variable in @var{Subsumer}. + +@item term_subsumer(?@var{T1}, ?@var{T2}, ?@var{Subsumer}) +@findex term_subsumer/2 +@syindex term_subsumer/2 +@cnindex term_subsumer/2 + +Succeed if @var{Subsumer} unifies with the least general +generalization over @var{T1} and +@var{T2}. + +@item term_variables(?@var{Term}, -@var{Variables}) [ISO] +@findex term_variables/2 +@syindex term_variables/2 +@cnindex term_variables/2 + +Unify @var{Variables} with the list of all variables of term +@var{Term}. The variables occur in the order of their first +appearance when traversing the term depth-first, left-to-right. + +@item rational_term_to_tree(?@var{TI},-@var{TF}) +@findex rational_term_to_tree/2 +@syindex rational_term_to_term/2 +@cnindex rational_term_to_tree/2 +The term @var{TF} is a tree representation (without cycles) for the + Prolog term @var{TI}. Loops are replaced by terms of the form + @code{_LOOP_(@var{LevelsAbove})} where @var{LevelsAbove} is the size of + the loop. + +@item tree_to_rational_term(?@var{TI},-@var{TF}) +@findex tree_to_rational_term/2 +@syindex tree_to_rational_term/2 +@cnindex tree_to_rational_term/2 +Inverse of above. The term @var{TI} is a tree representation (without + cycles) for the Prolog term @var{TF}. Loops replace terms of the form + @code{_LOOP_(@var{LevelsAbove})} where @var{LevelsAbove} is the size of + the loop. + + +@end table + +@node Predicates on Atoms, Predicates on Characters, Testing Terms, Top +@section Predicates on Atoms + +The following predicates are used to manipulate atoms: + +@table @code +@item name(@var{A},@var{L}) +@findex name/2 +@syindex name/2 +@cyindex name/2 +The predicate holds when at least one of the arguments is ground +(otherwise, an error message will be displayed). The argument @var{A} will +be unified with an atomic symbol and @var{L} with the list of the ASCII +codes for the characters of the external representation of @var{A}. + +@example + name(yap,L). +@end example +@noindent +will return: +@example + L = [121,97,112]. +@end example +@noindent +and +@example + name(3,L). +@end example +@noindent +will return: +@example + L = [51]. +@end example + +@item atom_chars(?@var{A},?@var{L}) [ISO] +@findex atom_chars/2 +@saindex atom_chars/2 +@cnindex atom_chars/2 +The predicate holds when at least one of the arguments is ground +(otherwise, an error message will be displayed). The argument @var{A} must +be unifiable with an atom, and the argument @var{L} with the list of the +characters of @var{A}. + +@item atom_codes(?@var{A},?@var{L}) [ISO] +@findex atom_codes/2 +@syindex atom_codes/2 +@cnindex atom_codes/2 +The predicate holds when at least one of the arguments is ground +(otherwise, an error message will be displayed). The argument @var{A} will +be unified with an atom and @var{L} with the list of the ASCII +codes for the characters of the external representation of @var{A}. + +@item atom_concat(+@var{As},?@var{A}) +@findex atom_concat/2 +@syindex atom_concat/2 +@cnindex atom_concat/2 +The predicate holds when the first argument is a list of atoms, and the +second unifies with the atom obtained by concatenating all the atoms in +the first list. + +@item atomic_concat(+@var{As},?@var{A}) +@findex atomic_concat/2 +@snindex atomic_concat/2 +@cnindex atomic_concat/2 +The predicate holds when the first argument is a list of atomic terms, and +the second unifies with the atom obtained by concatenating all the +atomic terms in the first list. The first argument thus may contain +atoms or numbers. + +@item atomic_list_concat(+@var{As},?@var{A}) +@findex atomic_list_concat/2 +@snindex atomic_list_concat/2 +@cnindex atomic_list_concat/2 +The predicate holds when the first argument is a list of atomic terms, and +the second unifies with the atom obtained by concatenating all the +atomic terms in the first list. The first argument thus may contain +atoms or numbers. + +@item atomic_list_concat(?@var{As},+@var{Separator},?@var{A}) +@findex atomic_list_concat/3 +@snindex atomic_list_concat/3 +@cnindex atomic_list_concat/3 +Creates an atom just like @code{atomic_list_concat/2}, but inserts +@var{Separator} between each pair of atoms. For example: + +@example +?- atomic_list_concat([gnu, gnat], ', ', A). + +A = 'gnu, gnat' +@end example + +YAP emulates the SWI-Prolog version of this predicate that can also be +used to split atoms by instantiating @var{Separator} and @var{Atom} as +shown below. + +@example +?- atomic_list_concat(L, -, 'gnu-gnat'). + +L = [gnu, gnat] +@end example + +@item atom_length(+@var{A},?@var{I}) [ISO] +@findex atom_length/2 +@snindex atom_length/2 +@cnindex atom_length/2 +The predicate holds when the first argument is an atom, and the second +unifies with the number of characters forming that atom. + +@item atom_concat(?@var{A1},?@var{A2},?@var{A12}) [ISO] +@findex atom_concat/3 +@snindex atom_concat/3 +@cnindex atom_concat/3 +The predicate holds when the third argument unifies with an atom, and +the first and second unify with atoms such that their representations +concatenated are the representation for @var{A12}. + +If @var{A1} and @var{A2} are unbound, the built-in will find all the atoms +that concatenated give @var{A12}. + +@item number_chars(?@var{I},?@var{L}) [ISO] +@findex number_chars/2 +@saindex number_chars/2 +@cnindex number_chars/2 + +The predicate holds when at least one of the arguments is ground +(otherwise, an error message will be displayed). The argument @var{I} must +be unifiable with a number, and the argument @var{L} with the list of the +characters of the external representation of @var{I}. + +@item number_codes(?@var{A},?@var{L}) [ISO] +@findex number_codes/2 +@syindex number_codes/2 +@cnindex number_codes/2 +The predicate holds when at least one of the arguments is ground +(otherwise, an error message will be displayed). The argument @var{A} +will be unified with a number and @var{L} with the list of the ASCII +codes for the characters of the external representation of @var{A}. + +@item atom_number(?@var{Atom},?@var{Number}) +@findex atom_number/2 +@syindex atom_number/2 +@cnindex atom_number/2 +The predicate holds when at least one of the arguments is ground +(otherwise, an error message will be displayed). If the argument +@var{Atom} is an atom, @var{Number} must be the number corresponding +to the characters in @var{Atom}, otherwise the characters in +@var{Atom} must encode a number @var{Number}. + +@item number_atom(?@var{I},?@var{L}) +@findex number_atom/2 +@snindex number_atom/2 +@cnindex number_atom/2 + +The predicate holds when at least one of the arguments is ground +(otherwise, an error message will be displayed). The argument @var{I} must +be unifiable with a number, and the argument @var{L} must be unifiable +with an atom representing the number. + +@item sub_atom(+@var{A},?@var{Bef}, ?@var{Size}, ?@var{After}, ?@var{At_out}) [ISO] +@findex sub_atom/5 +@snindex sub_atom/5 +@cnindex sub_atom/5 +True when @var{A} and @var{At_out} are atoms such that the name of +@var{At_out} has size @var{Size} and is a sub-string of the name of +@var{A}, such that @var{Bef} is the number of characters before and +@var{After} the number of characters afterwards. + +Note that @var{A} must always be known, but @var{At_out} can be unbound when +calling this built-in. If all the arguments for @code{sub_atom/5} but @var{A} +are unbound, the built-in will backtrack through all possible +sub-strings of @var{A}. + +@end table + +@node Predicates on Characters, Comparing Terms, Predicates on Atoms, Top +@section Predicates on Characters + +The following predicates are used to manipulate characters: + +@table @code +@item char_code(?@var{A},?@var{I}) [ISO] +@findex char_code/2 +@syindex char_code/2 +@cnindex char_code/2 +The built-in succeeds with @var{A} bound to character represented as an +atom, and @var{I} bound to the character code represented as an +integer. At least, one of either @var{A} or @var{I} must be bound before +the call. + +@item char_type(?@var{Char}, ?@var{Type}) +@findex char_type/2 +@snindex char_type/2 +@cnindex char_type/2 + Tests or generates alternative @var{Types} or @var{Chars}. The + character-types are inspired by the standard @code{C} + @code{} primitives. + +@table @code +@item alnum + @var{Char} is a letter (upper- or lowercase) or digit. + +@item alpha + @var{Char} is a letter (upper- or lowercase). + +@item csym + @var{Char} is a letter (upper- or lowercase), digit or the underscore (_). These are valid C- and Prolog symbol characters. + +@item csymf + @var{Char} is a letter (upper- or lowercase) or the underscore (_). These are valid first characters for C- and Prolog symbols + +@item ascii + @var{Char} is a 7-bits ASCII character (0..127). + +@item white + @var{Char} is a space or tab. E.i. white space inside a line. + +@item cntrl + @var{Char} is an ASCII control-character (0..31). + +@item digit + @var{Char} is a digit. + +@item digit(@var{Weight}) + @var{Char} is a digit with value + @var{Weight}. I.e. @code{char_type(X, digit(6))} yields @code{X = + '6'}. Useful for parsing numbers. + +@item xdigit(@var{Weight}) + @var{Char} is a hexa-decimal digit with value @var{Weight}. I.e. char_type(a, xdigit(X) yields X = '10'. Useful for parsing numbers. + +@item graph + @var{Char} produces a visible mark on a page when printed. Note that the space is not included! + +@item lower + @var{Char} is a lower-case letter. + +@item lower(Upper) + @var{Char} is a lower-case version of @var{Upper}. Only true if + @var{Char} is lowercase and @var{Upper} uppercase. + +@item to_lower(Upper) + @var{Char} is a lower-case version of Upper. For non-letters, or letter without case, @var{Char} and Lower are the same. See also upcase_atom/2 and downcase_atom/2. + +@item upper + @var{Char} is an upper-case letter. + +@item upper(Lower) + @var{Char} is an upper-case version of Lower. Only true if @var{Char} is uppercase and Lower lowercase. + +@item to_upper(Lower) + @var{Char} is an upper-case version of Lower. For non-letters, or letter without case, @var{Char} and Lower are the same. See also upcase_atom/2 and downcase_atom/2. + +@item punct + @var{Char} is a punctuation character. This is a graph character that is not a letter or digit. + +@item space + @var{Char} is some form of layout character (tab, vertical-tab, newline, etc.). + +@item end_of_file + @var{Char} is -1. + +@item end_of_line + @var{Char} ends a line (ASCII: 10..13). + +@item newline + @var{Char} is a the newline character (10). + +@item period + @var{Char} counts as the end of a sentence (.,!,?). + +@item quote + @var{Char} is a quote-character (", ', `). + +@item paren(Close) + @var{Char} is an open-parenthesis and Close is the corresponding close-parenthesis. +@end table + +@item code_type(?@var{Code}, ?@var{Type}) +@findex code_type/2 +@snindex code_type/2 +@cnindex code_type/2 + As @code{char_type/2}, but uses character-codes rather than + one-character atoms. Please note that both predicates are as + flexible as possible. They handle either representation if the + argument is instantiated and only will instantiate with an integer + code or one-character atom depending of the version used. See also + the prolog-flag @code{double_quotes} and the built-in predicates + @code{atom_chars/2} and @code{atom_codes/2}. + +@end table + +@node Comparing Terms, Arithmetic, Predicates on Characters, Top +@section Comparing Terms + +The following predicates are used to compare and order terms, using the +standard ordering: + +@itemize @bullet +@item +variables come before numbers, numbers come before atoms which in turn +come before compound terms, i.e.: variables @@< numbers @@< atoms @@< +compound terms. +@item +Variables are roughly ordered by "age" (the "oldest" variable is put +first); +@item +Floating point numbers are sorted in increasing order; +@item +Rational numbers are sorted in increasing order; +@item +Integers are sorted in increasing order; +@item +Atoms are sorted in lexicographic order; +@item +Compound terms are ordered first by arity of the main functor, then by +the name of the main functor, and finally by their arguments in +left-to-right order. +@end itemize + +@table @code + +@item compare(@var{C},@var{X},@var{Y}) [ISO] +@findex compare/3 +@syindex compare/3 +@cyindex compare/3 +As a result of comparing @var{X} and @var{Y}, @var{C} may take one of +the following values: + +@itemize @bullet +@item +@code{=} if @var{X} and @var{Y} are identical; +@item +@code{<} if @var{X} precedes @var{Y} in the defined order; +@item +@code{>} if @var{Y} precedes @var{X} in the defined order; +@end itemize + +@item @var{X} == @var{Y} [ISO] +@findex ==/2 +@syindex ==/2 +@cyindex ==/2 +Succeeds if terms @var{X} and @var{Y} are strictly identical. The +difference between this predicate and @code{=/2} is that, if one of the +arguments is a free variable, it only succeeds when they have already +been unified. + +@example +?- X == Y. +@end example +@noindent +fails, but, +@example +?- X = Y, X == Y. +@end example +@noindent +succeeds. +@example +?- X == 2. +@end example +@noindent +fails, but, +@example +?- X = 2, X == 2. +@end example +@noindent +succeeds. + + +@item @var{X} \== @var{Y} [ISO] +@findex \==/2 +@syindex \==/2 +@cyindex \==/2 +Terms @var{X} and @var{Y} are not strictly identical. + +@item @var{X} @@< @var{Y} [ISO] +@findex @@ @var{Y} [ISO] +@findex @@>/2 +@syindex @@>/2 +@cyindex @@>/2 +Term @var{X} follows term @var{Y} in the standard order. + +@item @var{X} @@>= @var{Y} [ISO] +@findex @@>=/2 +@syindex @@>=/2 +@cyindex @@>=/2 +Term @var{X} does not precede term @var{Y} in the standard order. + +@item sort(+@var{L},-@var{S}) [ISO] +@findex sort/2 +@syindex sort/2 +@cyindex sort/2 +Unifies @var{S} with the list obtained by sorting @var{L} and merging +identical (in the sense of @code{==}) elements. + +@item keysort(+@var{L},@var{S}) [ISO] +@findex keysort/2 +@syindex keysort/2 +@cyindex keysort/2 +Assuming L is a list of the form @code{@var{Key}-@var{Value}}, +@code{keysort(+@var{L},@var{S})} unifies @var{S} with the list obtained +from @var{L}, by sorting its elements according to the value of +@var{Key}. +@example +?- keysort([3-a,1-b,2-c,1-a,1-b],S). +@end example +@noindent +would return: +@example +S = [1-b,1-a,1-b,2-c,3-a] +@end example + +@item predsort(+@var{Pred}, +@var{List}, -@var{Sorted}) +@findex predsort/3 +@snindex predsort/3 +@cnindex predsort/3 +Sorts similar to sort/2, but determines the order of two terms by +calling @var{Pred}(-@var{Delta}, +@var{E1}, +@var{E2}) . This call must +unify @var{Delta} with one of @code{<}, @code{>} or @code{=}. If +built-in predicate compare/3 is used, the result is the same as +sort/2. + +@item length(?@var{L},?@var{S}) +@findex length/2 +@syindex length/2 +@cyindex length/2 +Unify the well-defined list @var{L} with its length. The procedure can +be used to find the length of a pre-defined list, or to build a list +of length @var{S}. + +@end table + +@node Arithmetic, I/O, Comparing Terms, Top +@section Arithmetic + +YAP now supports several different numeric types: + +@table @code +@item integers + When YAP is built using the GNU multiple precision arithmetic + library (GMP), integer arithmetic is unbounded, which means that + the size of integers is limited by available memory only. Without + GMP, SWI-Prolog integers have the same size as an address. The + type of integer support can be detected using the Prolog flags + bounded, min_integer and max_integer. As the use of GMP is + default, most of the following descriptions assume unbounded + integer arithmetic. + + Internally, SWI-Prolog has three integer representations. Small + integers (defined by the Prolog flag max_tagged_integer) are + encoded directly. Larger integers are represented as cell values + on the global stack. Integers that do not fit in 64-bit are + represented as serialised GNU MPZ structures on the global stack. + +@item number + Rational numbers (Q) are quotients of two integers. Rational + arithmetic is only provided if GMP is used (see above). Rational + numbers that are returned from is/2 are canonical, which means M + is positive and N and M have no common divisors. Rational numbers + are introduced in the computation using the rational/1, + rationalize/1 or the rdiv/2 (rational division) function. + +@item float + Floating point numbers are represented using the C-type double. On most today platforms these are 64-bit IEEE floating point numbers. + +@end table + +Arithmetic functions that require integer arguments accept, in addition +to integers, rational numbers with denominator `1' and floating point +numbers that can be accurately converted to integers. If the required +argument is a float the argument is converted to float. Note that +conversion of integers to floating point numbers may raise an overflow +exception. In all other cases, arguments are converted to the same type +using the order integer to rational number to floating point number. + + +Arithmetic expressions in YAP may use the following operators or +@i{evaluable predicates}: + +@table @code + +@item +@var{X} [ISO] +The value of @var{X} itself. + +@item -@var{X} [ISO] +Symmetric value. + +@item @var{X}+@var{Y} [ISO] +Sum. + +@item @var{X}-@var{Y} [ISO] +Difference. + +@item @var{X}*@var{Y} [ISO] +Product. + +@item @var{X}/@var{Y} [ISO] +Quotient. + +@item @var{X}//@var{Y} [ISO] +Integer quotient. + +@item @var{X} mod @var{Y} [ISO] +Integer module operator, always positive. + +@item @var{X} rem @var{Y} [ISO] +Integer remainder, similar to @code{mod} but always has the same sign +@code{X}. + +@item @var{X} div @var{Y} [ISO] +Integer division, as if defined by @code{(@var{X} - @var{X} mod @var{Y}) +// @var{Y}}. + +@item exp(@var{X}) [ISO] +Natural exponential. + +@item log(@var{X}) [ISO] +Natural logarithm. + +@item log10(@var{X}) +Decimal logarithm. + +@item sqrt(@var{X}) [ISO] +Square root. + +@item sin(@var{X}) [ISO] +Sine. + +@item cos(@var{X}) [ISO] +Cosine. + +@item tan(@var{X}) [ISO] +Tangent. + +@item asin(@var{X}) [ISO] +Arc sine. + +@item acos(@var{X}) [ISO] +Arc cosine. + +@item atan(@var{X}) [ISO] +Arc tangent. + +@item atan(@var{X},@var{Y}) +Four-quadrant arc tangent. Also available as @code{atan2/2}. + +@item atan2(@var{X},@var{Y}) [ISO] +Four-quadrant arc tangent. + +@item sinh(@var{X}) +Hyperbolic sine. + +@item cosh(@var{X}) +Hyperbolic cosine. + +@item tanh(@var{X}) +Hyperbolic tangent. + +@item asinh(@var{X}) +Hyperbolic arc sine. + +@item acosh(@var{X}) +Hyperbolic arc cosine. + +@item atanh(@var{X}) +Hyperbolic arc tangent. + +@item lgamma(@var{X}) +Logarithm of gamma function. + +@item erf(@var{X}) +Gaussian error function. + +@item erfc(@var{X}) +Complementary gaussian error function. + +@item random(@var{X}) [ISO] +An integer random number between 0 and @var{X}. + +In @code{iso} language mode the argument must be a floating +point-number, the result is an integer and it the float is equidistant +it is rounded up, that is, to the least integer greater than @var{X}. + +@item integer(@var{X}) +If @var{X} evaluates to a float, the integer between the value of @var{X} +and 0 closest to the value of @var{X}, else if @var{X} evaluates to an +integer, the value of @var{X}. + +@item float(@var{X}) [ISO] +If @var{X} evaluates to an integer, the corresponding float, else the float +itself. + +@item float_fractional_part(@var{X}) [ISO] +The fractional part of the floating point number @var{X}, or @code{0.0} +if @var{X} is an integer. In the @code{iso} language mode, +@var{X} must be an integer. + +@item float_integer_part(@var{X}) [ISO] +The float giving the integer part of the floating point number @var{X}, +or @var{X} if @var{X} is an integer. In the @code{iso} language mode, +@var{X} must be an integer. + +@item abs(@var{X}) [ISO] +The absolute value of @var{X}. + +@item ceiling(@var{X}) [ISO] +The integer that is the smallest integral value not smaller than @var{X}. + +In @code{iso} language mode the argument must be a floating +point-number and the result is an integer. + +@item floor(@var{X}) [ISO] +The integer that is the greatest integral value not greater than @var{X}. + +In @code{iso} language mode the argument must be a floating +point-number and the result is an integer. + +@item round(@var{X}) [ISO] +The nearest integral value to @var{X}. If @var{X} is +equidistant to two integers, it will be rounded to the closest even +integral value. + +In @code{iso} language mode the argument must be a floating +point-number, the result is an integer and it the float is equidistant +it is rounded up, that is, to the least integer greater than @var{X}. + +@item sign(@var{X}) [ISO] +Return 1 if the @var{X} evaluates to a positive integer, 0 it if +evaluates to 0, and -1 if it evaluates to a negative integer. If @var{X} +evaluates to a floating-point number return 1.0 for a positive @var{X}, +0.0 for 0.0, and -1.0 otherwise. + +@item truncate(@var{X}) [ISO] +The integral value between @var{X} and 0 closest to +@var{X}. + +@item rational(@var{X}) +Convert the expression @var{X} to a rational number or integer. The +function returns the input on integers and rational numbers. For +floating point numbers, the returned rational number exactly represents +the float. As floats cannot exactly represent all decimal numbers the +results may be surprising. In the examples below, doubles can represent +@code{0.25} and the result is as expected, in contrast to the result of +@code{rational(0.1)}. The function @code{rationalize/1} gives a more +intuitive result. + +@example +?- A is rational(0.25). + +A is 1 rdiv 4 +?- A is rational(0.1). +A = 3602879701896397 rdiv 36028797018963968 +@end example + +@item rationalize(@var{X}) +Convert the Expr to a rational number or integer. The function is +similar to @code{rational/1}, but the result is only accurate within the +rounding error of floating point numbers, generally producing a much +smaller denominator. + +@example +?- A is rationalize(0.25). + +A = 1 rdiv 4 +?- A is rationalize(0.1). + +A = 1 rdiv 10 +@end example + + +@item max(@var{X},@var{Y}) [ISO] +The greater value of @var{X} and @var{Y}. + +@item min(@var{X},@var{Y}) [ISO] +The lesser value of @var{X} and @var{Y}. + +@item @var{X} ^ @var{Y} [ISO] +@var{X} raised to the power of @var{Y}, (from the C-Prolog syntax). + +@item exp(@var{X},@var{Y}) +@var{X} raised to the power of @var{Y}, (from the Quintus Prolog syntax). + +@item @var{X} ** @var{Y} [ISO] +@var{X} raised to the power of @var{Y} (from ISO). + +@item @var{X} /\ @var{Y} [ISO] +Integer bitwise conjunction. + +@item @var{X} \/ @var{Y} [ISO] +Integer bitwise disjunction. + +@item @var{X} # @var{Y} +@item @var{X} >< @var{Y} +@item xor(@var{X} , @var{Y}) [ISO] +Integer bitwise exclusive disjunction. + +@item @var{X} << @var{Y} +Integer bitwise left logical shift of @var{X} by @var{Y} places. + +@item @var{X} >> @var{Y} [ISO] +Integer bitwise right logical shift of @var{X} by @var{Y} places. + +@item \ @var{X} [ISO] +Integer bitwise negation. + +@item gcd(@var{X},@var{Y}) +The greatest common divisor of the two integers @var{X} and @var{Y}. + +@item msb(@var{X}) +The most significant bit of the non-negative integer @var{X}. + +@item lsb(@var{X}) +The least significant bit of the non-negative integer @var{X}. + +@item popcount(@var{X}) +The number of bits set to @code{1} in the binary representation of the +non-negative integer @var{X}. + +@item [@var{X}] +Evaluates to @var{X} for expression @var{X}. Useful because character +strings in Prolog are lists of character codes. + +@example +X is Y*10+C-"0" +@end example +@noindent +is the same as +@example +X is Y*10+C-[48]. +@end example +@noindent +which would be evaluated as: +@example +X is Y*10+C-48. +@end example + +@end table + +Besides numbers and the arithmetic operators described above, certain +atoms have a special meaning when present in arithmetic expressions: + +@table @code +@item pi [ISO] +The value of @emph{pi}, the ratio of a circle's circumference to its +diameter. + +@item e +The base of the natural logarithms. + +@item epsilon +The difference between the float @code{1.0} and the first larger floating point +number. + +@item inf +Infinity according to the IEEE Floating-Point standard. Note that +evaluating this term will generate a domain error in the @code{iso} +language mode. + +@item nan +Not-a-number according to the IEEE Floating-Point standard. Note that +evaluating this term will generate a domain error in the @code{iso} +language mode. + +@item cputime +CPU time in seconds, since YAP was invoked. + +@item heapused +Heap space used, in bytes. + +@item local +Local stack in use, in bytes. + +@item global +Global stack in use, in bytes. + +@item random +A "random" floating point number between 0 and 1. + +@end table + +The primitive YAP predicates involving arithmetic expressions are: + +@table @code + +@item @var{X} is +@var{Y} [2] +@findex is/2 +@syindex is/2 +@caindex is/2 +This predicate succeeds iff the result of evaluating the expression +@var{Y} unifies with @var{X}. This is the predicate normally used to +perform evaluation of arithmetic expressions: + +@example +X is 2+3*4 +@end example +@noindent +succeeds with @code{X = 14}. + +@item +@var{X} < +@var{Y} [ISO] +@findex +@var{Y} [ISO] +@findex >/2 +@syindex >/2 +@cyindex >/2 +The value of the expression @var{X} is greater than the value of +expression @var{Y}. + +@item +@var{X} >= +@var{Y} [ISO] +@findex >=/2 +@syindex >=/2 +@cyindex >=/2 +The value of the expression @var{X} is greater than or equal to the +value of expression @var{Y}. + +@item +@var{X} =:= +@var{Y} [ISO] +@findex =:=/2 +@syindex =:=/2 +@cyindex =:=/2 +The value of the expression @var{X} is equal to the value of expression +@var{Y}. + +@item +@var{X} =\= +@var{Y} [ISO] +@findex =\=/2 +@syindex =\=/2 +@cyindex =\=/2 +The value of the expression @var{X} is different from the value of +expression @var{Y}. + +@item srandom(+@var{X}) +@findex srandom/1 +@snindex srandom/1 +@cnindex srandom/1 +Use the argument @var{X} as a new seed for YAP's random number +generator. The argument should be an integer, but floats are acceptable. +@end table + +@noindent +@strong{Notes:} + +@itemize @bullet +@item +Since YAP4, YAP @emph{does not} convert automatically between integers +and floats. +@item +arguments to trigonometric functions are expressed in radians. +@item +if a (non-instantiated) variable occurs in an arithmetic expression YAP +will generate an exception. If no error handler is available, execution +will be thrown back to the top-level. +@end itemize + + +The following predicates provide counting: + +@table @code + +@item between(+@var{Low}, +@var{High}, ?@var{Value}) +@findex between/3 +@syindex between/3 +@cnindex between/3 + + @var{Low} and @var{High} are integers, @var{High} >=@var{Low}. If + @var{Value} is an integer, @var{Low} =<@var{Value} + =<@var{High}. When @var{Value} is a variable it is successively + bound to all integers between @var{Low} and @var{High}. If + @var{High} is inf or infinite @code{between/3} is true iff + @var{Value} >= @var{Low}, a feature that is particularly interesting + for generating integers from a certain value. + +@item succ(?@var{Int1}, ?@var{Int2}) +@findex succ/3 +@syindex succ/3 +@cnindex succ/3 + + True if @var{Int2} = @var{Int1} + 1 and @var{Int1} >= 0. At least + one of the arguments must be instantiated to a natural number. This + predicate raises the domain-error not_less_than_zero if called with + a negative integer. E.g. @code{succ(X, 0)} fails silently and succ(X, -1) + raises a domain-error. The behaviour to deal with natural numbers + only was defined by Richard O'Keefe to support the common + count-down-to-zero in a natural way. + +@item plus(?@var{Int1}, ?@var{Int2}, ?@var{Int3}) +@findex plus/3 +@syindex plus/3 +@cnindex plus/3 + True if @var{Int3} = @var{Int1} + @var{Int2}. At least two of the + three arguments must be instantiated to integers. + +@item logsum(+@var{Log1}, +@var{Log2}, -@var{Out} ) +@findex logsum/3 +@snindex logsum/3 +@cnindex logsum/3 + True if @var{Log1} is the logarithm of the positive number @var{A1}, + @var{Log2} is the logarithm of the positive number @var{A2}, and + @var{Out} is the logarithm of the sum of the numbers @var{A1} and + @var{A2}. Useful in probability computation. + +@item isnan(+@var{Float}) +@findex isnan/1 +@snindex isnan/1 +@cnindex isnan/1 + True if @var{Float} is not a number. + +@item isinf(+@var{Float}) +@findex isinf/1 +@snindex isinf/1 +@cnindex isinf/1 + True if floating point expression @var{Float} evaluates to infinity. + + +@end table + +@node I/O, Database, Arithmetic, Top +@section I/O Predicates + +Some of the I/O predicates described below will in certain conditions +provide error messages and abort only if the file_errors flag is set. +If this flag is cleared the same predicates will just fail. Details on +setting and clearing this flag are given under 7.7. + +@menu + +Subnodes of Input/Output +* Streams and Files:: Handling Streams and Files +* C-Prolog File Handling:: C-Prolog Compatible File Handling +* I/O of Terms:: Input/Output of terms +* I/O of Characters:: Input/Output of Characters +* I/O for Streams:: Input/Output using Streams +* C-Prolog to Terminal:: C-Prolog compatible Character I/O to terminal +* I/O Control:: Controlling your Input/Output +* Sockets:: Using Sockets from YAP + +@end menu + +@node Streams and Files, C-Prolog File Handling, , I/O +@subsection Handling Streams and Files + +@table @code + +@item open(+@var{F},+@var{M},-@var{S}) [ISO] +@findex open/3 +@syindex open/3 +@cnindex open/3 +Opens the file with name @var{F} in mode @var{M} ('read', 'write' or +'append'), returning @var{S} unified with the stream name. + +At most, there are 17 streams opened at the same time. Each stream is +either an input or an output stream but not both. There are always 3 +open streams: @code{user_input} for reading, @code{user_output} for writing +and @code{user_error} for writing. If there is no ambiguity, the atoms +@code{user_input} and @code{user_output} may be referred to as @code{user}. + +The @code{file_errors} flag controls whether errors are reported when in +mode 'read' or 'append' the file @var{F} does not exist or is not +readable, and whether in mode 'write' or 'append' the file is not +writable. + +@item open(+@var{F},+@var{M},-@var{S},+@var{Opts}) [ISO] +@findex open/4 +@saindex open/4 +@cnindex open/4 +Opens the file with name @var{F} in mode @var{M} ('read', 'write' or +'append'), returning @var{S} unified with the stream name, and following +these options: + +@table @code + +@item type(+@var{T}) [ISO] +Specify whether the stream is a @code{text} stream (default), or a +@code{binary} stream. + +@item reposition(+@var{Bool}) [ISO] +Specify whether it is possible to reposition the stream (@code{true}), or +not (@code{false}). By default, YAP enables repositioning for all +files, except terminal files and sockets. + +@item eof_action(+@var{Action}) [ISO] +Specify the action to take if attempting to input characters from a +stream where we have previously found an @code{end_of_file}. The possible +actions are @code{error}, that raises an error, @code{reset}, that tries to +reset the stream and is used for @code{tty} type files, and @code{eof_code}, +which generates a new @code{end_of_file} (default for non-tty files). + +@item alias(+@var{Name}) [ISO] +Specify an alias to the stream. The alias @t{Name} must be an atom. The +alias can be used instead of the stream descriptor for every operation +concerning the stream. + +The operation will fail and give an error if the alias name is already +in use. YAP allows several aliases for the same file, but only +one is returned by @code{stream_property/2} + +@item bom(+@var{Bool}) +If present and @code{true}, a BOM (@emph{Byte Order Mark}) was +detected while opening the file for reading or a BOM was written while +opening the stream. See @ref{BOM} for details. + +@item encoding(+@var{Encoding}) +Set the encoding used for text. See @ref{Encoding} for an overview of +wide character and encoding issues. + +@item representation_errors(+@var{Mode}) +Change the behaviour when writing characters to the stream that cannot +be represented by the encoding. The behaviour is one of @code{error} +(throw and I/O error exception), @code{prolog} (write @code{\u...\} +escape code or @code{xml} (write @code{&#...;} XML character entity). +The initial mode is @code{prolog} for the user streams and +@code{error} for all other streams. See also @ref{Encoding}. + +@item expand_filename(+@var{Mode}) +If @var{Mode} is @code{true} then do filename expansion, then ask Prolog +to do file name expansion before actually trying to opening the file: +this includes processing @code{~} characters and processing @code{$} +environment variables at the beginning of the file. Otherwise, just try +to open the file using the given name. + +The default behavior is given by the Prolog flag +@code{open_expands_filename}. + +@end table + +@item close(+@var{S}) [ISO] +@findex close/1 +@syindex close/1 +@cyindex close/1 +Closes the stream @var{S}. If @var{S} does not stand for a stream +currently opened an error is reported. The streams @code{user_input}, +@code{user_output}, and @code{user_error} can never be closed. + +@c By default, give a file name, @code{close/1} will also try to close a +@c corresponding open stream. This feature is not available in ISO or +@c SICStus languages mode and is deprecated. + +@item close(+@var{S},+@var{O}) [ISO] +@findex close/2 +@saindex close/2 +@cnindex close/2 +Closes the stream @var{S}, following options @var{O}. + +The only valid options are @code{force(true)} and @code{force(false)}. +YAP currently ignores these options. + +@item time_file(+@var{File},-@var{Time}) +@findex time_file/2 +@snindex time_file/2 +@cnindex time_file/2 +Unify the last modification time of @var{File} with +@var{Time}. @var{Time} is a floating point number expressing the seconds +elapsed since Jan 1, 1970. + +@item absolute_file_name(+@var{Name},+@var{Options}, -@var{FullPath}) absolute_file_name(+@var{Name}, -@var{FullPath},+@var{Options}) +@findex absolute_file_name/3 +@syindex absolute_file_name/3 +@cnindex absolute_file_name/3 + +Converts the given file specification into an absolute path. +@var{Option} is a list of options to guide the conversion: + +@table @code + @item extensions(+@var{ListOfExtensions}) +List of file-extensions to try. Default is @samp{''}. For each +extension, @code{absolute_file_name/3} will first add the extension and then +verify the conditions imposed by the other options. If the condition +fails, the next extension of the list is tried. Extensions may be +specified both as @code{.ext} or plain @code{ext}. + + @item relative_to(+@var{FileOrDir}) +Resolve the path relative to the given directory or directory the +holding the given file. Without this option, paths are resolved +relative to the working directory (see @code{working_directory/2}) or, +if @var{Spec} is atomic and @code{absolute_file_name/[2,3]} is executed +in a directive, it uses the current source-file as reference. + + @item access(+@var{Mode}) +Imposes the condition access_file(@var{File}, @var{Mode}). @var{Mode} +is on of @code{read}, @code{write}, @code{append}, @code{exist} or +@code{none} (default). +See also @code{access_file/2}. + + @item file_type(+@var{Type}) +Defines extensions. Current mapping: @code{txt} implies @code{['']}, +@code{prolog} implies @code{['.yap', '.pl', '.prolog', '']}, @code{executable} +implies @code{['.so', '']}, @code{qlf} implies @code{['.qlf', '']} and +@code{directory} implies @code{['']}. The file-type @code{source} +is an alias for @code{prolog} for compatibility to SICStus Prolog. +See also @code{prolog_file_type/2}. Notice also that this predicate only +returns non-directories, unless the option @code{file_type(directory)} is +specified, or unless @code{access(none)}. + + @item file_errors(@code{fail}/@code{error}) +If @code{error} (default), throw and @code{existence_error} exception +if the file cannot be found. If @code{fail}, stay silent. + + @item solutions(@code{first}/@code{all}) +If @code{first} (default), the predicates leaves no choice-point. +Otherwise a choice-point will be left and backtracking may yield +more solutions. + + @item expand(@code{true}/@code{false}) + If @code{true} (default is @code{false}) and @var{Spec} is atomic, + call @code{expand_file_name/2} followed by @code{member/2} on @var{Spec} before + proceeding. This is originally a SWI-Prolog extension. +@end table + +@c The Prolog flag @code{verbose_file_search} can be set to @code{true} +@c to help debugging Prolog's search for files. + +Compatibility considerations to common argument-order in ISO as well +as SICStus @code{absolute_file_name/3} forced us to be flexible here. +If the last argument is a list and the 2nd not, the arguments are +swapped, making the call @code{absolute_file_name}(+@var{Spec}, -@var{Path}, ++@var{Options}) valid as well. + +@item absolute_file_name(+@var{Name},-@var{FullPath}) +@findex absolute_file_name/2 +@syindex absolute_file_name/2 +@cnindex absolute_file_name/2 +Give the path a full path @var{FullPath} YAP would use to consult a file +named @var{Name}. Unify @var{FullPath} with @code{user} if the file +name is @code{user}. + +@item file_base_name(+@var{Name},-@var{FileName}) +@findex file_base_name/2 +@snindex file_base_name/2 +@cnindex file_base_name/2 +Give the path a full path @var{FullPath} extract the @var{FileName}. + +@item file_name_extension(?@var{Base},?@var{Extension}, ?@var{Name}) +@findex file_name_extension/3 +@snindex file_name_extension/3 +@cnindex file_name_extension/3 + +This predicate is used to add, remove or test filename extensions. The +main reason for its introduction is to deal with different filename +properties in a portable manner. If the file system is +case-insensitive, testing for an extension will be done +case-insensitive too. @var{Extension} may be specified with or +without a leading dot (.). If an @var{Extension} is generated, it +will not have a leading dot. + +@item current_stream(@var{F},@var{M},@var{S}) +@findex current_stream/3 +@syindex current_stream/3 +@cnindex current_stream/3 +Defines the relation: The stream @var{S} is opened on the file @var{F} +in mode @var{M}. It might be used to obtain all open streams (by +backtracking) or to access the stream for a file @var{F} in mode +@var{M}, or to find properties for a stream @var{S}. Notice that some +streams might not be associated to a file: in this case YAP tries to +return the file number. If that is not available, YAP unifies @var{F} +with @var{S}. + +@item is_stream(@var{S}) +@findex is_stream/1 +@snindex is_stream/1 +@cnindex is_stream/1 +Succeeds if @var{S} is a currently open stream. + +@item flush_output [ISO] +@findex flush_output/0 +@syindex flush_output/0 +@cnindex flush_output/0 +Send out all data in the output buffer of the current output stream. + +@item flush_output(+@var{S}) [ISO] +@findex flush_output/1 +@syindex flush_output/1 +@cnindex flush_output/1 +Send all data in the output buffer for stream @var{S}. + +@item set_input(+@var{S}) [ISO] +@findex set_input/1 +@syindex set_input/1 +@cnindex set_input/1 +Set stream @var{S} as the current input stream. Predicates like @code{read/1} +and @code{get/1} will start using stream @var{S}. + +@item set_output(+@var{S}) [ISO] +@findex set_output/1 +@syindex set_output/1 +@cnindex set_output/1 +Set stream @var{S} as the current output stream. Predicates like +@code{write/1} and @code{put/1} will start using stream @var{S}. + +@item stream_select(+@var{STREAMS},+@var{TIMEOUT},-@var{READSTREAMS}) +@findex stream_select/3 +@syindex stream_select/3 +@cnindex stream_select/3 +Given a list of open @var{STREAMS} opened in read mode and a @var{TIMEOUT} +return a list of streams who are now available for reading. + +If the @var{TIMEOUT} is instantiated to @code{off}, +@code{stream_select/3} will wait indefinitely for a stream to become +open. Otherwise the timeout must be of the form @code{SECS:USECS} where +@code{SECS} is an integer gives the number of seconds to wait for a timeout +and @code{USECS} adds the number of micro-seconds. + +This built-in is only defined if the system call @code{select} is +available in the system. + +@item current_input(-@var{S}) [ISO] +@findex current_input/1 +@syindex current_input/1 +@cnindex current_input/1 +Unify @var{S} with the current input stream. + +@item current_output(-@var{S}) [ISO] +@findex current_output/1 +@syindex current_output/1 +@cnindex current_output/1 +Unify @var{S} with the current output stream. + +@item at_end_of_stream [ISO] +@findex at_end_of_stream/0 +@syindex at_end_of_stream/0 +@cnindex at_end_of_stream/0 +Succeed if the current stream has stream position end-of-stream or +past-end-of-stream. + +@item at_end_of_stream(+@var{S}) [ISO] +@findex at_end_of_stream/1 +@syindex at_end_of_stream/1 +@cnindex at_end_of_stream/1 +Succeed if the stream @var{S} has stream position end-of-stream or +past-end-of-stream. Note that @var{S} must be a readable stream. + +@item set_stream_position(+@var{S}, +@var{POS}) [ISO] +@findex set_stream_position/2 +@syindex set_stream_position/2 +@cnindex set_stream_position/2 +Given a stream position @var{POS} for a stream @var{S}, set the current +stream position for @var{S} to be @var{POS}. + +@item stream_property(?@var{Stream},?@var{Prop}) [ISO] +@findex stream_property/2 +@snindex stream_property/2 +@cnindex stream_property/2 + +Obtain the properties for the open streams. If the first argument is +unbound, the procedure will backtrack through all open +streams. Otherwise, the first argument must be a stream term (you may +use @code{current_stream} to obtain a current stream given a file name). + +The following properties are recognized: + +@table @code + +@item file_name(@var{P}) +An atom giving the file name for the current stream. The file names are +@code{user_input}, @code{user_output}, and @code{user_error} for the +standard streams. + +@item mode(@var{P}) +The mode used to open the file. It may be one of @code{append}, +@code{read}, or @code{write}. + +@item input +The stream is readable. + +@item output +The stream is writable. + +@item alias(@var{A}) +ISO-Prolog primitive for stream aliases. @t{YAP} returns one of the +existing aliases for the stream. + +@item position(@var{P}) +A term describing the position in the stream. + +@item end_of_stream(@var{E}) +Whether the stream is @code{at} the end of stream, or it has found the +end of stream and is @code{past}, or whether it has @code{not} yet +reached the end of stream. + +@item eof_action(@var{A}) +The action to take when trying to read after reaching the end of +stream. The action may be one of @code{error}, generate an error, +@code{eof_code}, return character code @code{-1}, or @code{reset} the +stream. + +@item reposition(@var{B}) +Whether the stream can be repositioned or not, that is, whether it is +seekable. + +@item type(@var{T}) +Whether the stream is a @code{text} stream or a @code{binary} stream. + +@item bom(+@var{Bool}) +If present and @code{true}, a BOM (@emph{Byte Order Mark}) was +detected while opening the file for reading or a BOM was written while +opening the stream. See @ref{BOM} for details. + +@item encoding(+@var{Encoding}) +Query the encoding used for text. See @ref{Encoding} for an +overview of wide character and encoding issues in YAP. + +@item representation_errors(+@var{Mode}) +Behaviour when writing characters to the stream that cannot be +represented by the encoding. The behaviour is one of @code{error} +(throw and I/O error exception), @code{prolog} (write @code{\u...\} +escape code or @code{xml} (write @code{&#...;} XML character entity). +The initial mode is @code{prolog} for the user streams and +@code{error} for all other streams. See also @ref{Encoding} and +@code{open/4}. + +@end table + +@item current_line_number(-@var{LineNumber}) +@findex current_line_number/1 +@saindex current_line_number/1 +@cnindex current_line_number/1 +Unify @var{LineNumber} with the line number for the current stream. + +@item current_line_number(+@var{Stream},-@var{LineNumber}) +@findex current_line_number/2 +@saindex current_line_number/2 +@cnindex current_line_number/2 +Unify @var{LineNumber} with the line number for the @var{Stream}. + +@item line_count(+@var{Stream},-@var{LineNumber}) +@findex line_count/2 +@syindex line_count/2 +@cnindex line_count/2 +Unify @var{LineNumber} with the line number for the @var{Stream}. + +@item character_count(+@var{Stream},-@var{CharacterCount}) +@findex character_count/2 +@syindex character_count/2 +@cnindex character_count/2 +Unify @var{CharacterCount} with the number of characters written to or +read to @var{Stream}. + +@item line_position(+@var{Stream},-@var{LinePosition}) +@findex line_position/2 +@syindex line_position/2 +@cnindex line_position/2 +Unify @var{LinePosition} with the position on current text stream +@var{Stream}. + +@item stream_position(+@var{Stream},-@var{StreamPosition}) +@findex stream_position/2 +@syindex stream_position/2 +@cnindex stream_position/2 +Unify @var{StreamPosition} with the packaged information of position on +current stream @var{Stream}. Use @code{stream_position_data/3} to +retrieve information on character or line count. + +@item stream_position_data(+@var{Field},+@var{StreamPosition},-@var{Info}) +@findex stream_position_data/3 +@syindex stream_position_data/3 +@cnindex stream_position_data/3 +Given the packaged stream position term @var{StreamPosition}, unify +@var{Info} with @var{Field} @code{line_count}, @code{byte_count}, or +@code{char_count}. + +@end table + +@node C-Prolog File Handling, I/O of Terms, Streams and Files, I/O +@subsection Handling Streams and Files + +@table @code + +@item tell(+@var{S}) +@findex tell/1 +@syindex tell/1 +@cyindex tell/1 +If @var{S} is a currently opened stream for output, it becomes the +current output stream. If @var{S} is an atom it is taken to be a +filename. If there is no output stream currently associated with it, +then it is opened for output, and the new output stream created becomes +the current output stream. If it is not possible to open the file, an +error occurs. If there is a single opened output stream currently +associated with the file, then it becomes the current output stream; if +there are more than one in that condition, one of them is chosen. + +Whenever @var{S} is a stream not currently opened for output, an error +may be reported, depending on the state of the file_errors flag. The +predicate just fails, if @var{S} is neither a stream nor an atom. + +@item telling(-@var{S}) +@findex telling/1 +@syindex telling/1 +@cyindex telling/1 +The current output stream is unified with @var{S}. + +@item told +@findex told/0 +@syindex told/0 +@cyindex told/0 +Closes the current output stream, and the user's terminal becomes again +the current output stream. It is important to remember to close streams +after having finished using them, as the maximum number of +simultaneously opened streams is 17. + +@item see(+@var{S}) +@findex see/1 +@syindex see/1 +@cyindex see/1 +If @var{S} is a currently opened input stream then it is assumed to be +the current input stream. If @var{S} is an atom it is taken as a +filename. If there is no input stream currently associated with it, then +it is opened for input, and the new input stream thus created becomes +the current input stream. If it is not possible to open the file, an +error occurs. If there is a single opened input stream currently +associated with the file, it becomes the current input stream; if there +are more than one in that condition, then one of them is chosen. + +When @var{S} is a stream not currently opened for input, an error may be +reported, depending on the state of the @code{file_errors} flag. If +@var{S} is neither a stream nor an atom the predicates just fails. + +@item seeing(-@var{S}) +@findex seeing/1 +@syindex seeing/1 +@cyindex seeing/1 +The current input stream is unified with @var{S}. + +@item seen +@findex seen/0 +@syindex seen/0 +@cyindex seen/0 +Closes the current input stream (see 6.7.). + +@end table + +@node I/O of Terms, I/O of Characters, C-Prolog File Handling, I/O +@subsection Handling Input/Output of Terms + +@table @code + +@item read(-@var{T}) [ISO] +@findex read/1 +@syindex read/1 +@cyindex read/1 +Reads the next term from the current input stream, and unifies it with +@var{T}. The term must be followed by a dot ('.') and any blank-character +as previously defined. The syntax of the term must match the current +declarations for operators (see op). If the end-of-stream is reached, +@var{T} is unified with the atom @code{end_of_file}. Further reads from of +the same stream may cause an error failure (see @code{open/3}). + +@item read_term(-@var{T},+@var{Options}) [ISO] +@findex read_term/2 +@saindex read_term/2 +@cnindex read_term/2 +Reads term @var{T} from the current input stream with execution +controlled by the following options: + +@table @code + +@item term_position(-@var{Position}) +@findex term_position/1 (read_term/2 option) +Unify @var{Position} with a term describing the position of the stream +at the start of parse. Use @code{stream_position_data/3} to obtain extra +information. + +@item singletons(-@var{Names}) +@findex singletons/1 (read_term/2 option) +Unify @var{Names} with a list of the form @var{Name=Var}, where +@var{Name} is the name of a non-anonymous singleton variable in the +original term, and @code{Var} is the variable's representation in +YAP. +The variables occur in left-to-right traversal order. + +@item syntax_errors(+@var{Val}) +@findex syntax_errors/1 (read_term/2 option) +Control action to be taken after syntax errors. See @code{yap_flag/2} +for detailed information. + +@item variable_names(-@var{Names}) +@findex variable_names/1 (read_term/2 option) +Unify @var{Names} with a list of the form @var{Name=Var}, where @var{Name} is +the name of a non-anonymous variable in the original term, and @var{Var} +is the variable's representation in YAP. +The variables occur in left-to-right traversal order. + +@item variables(-@var{Names}) +@findex variables/1 (read_term/2 option) +Unify @var{Names} with a list of the variables in term @var{T}. +The variables occur in left-to-right traversal order. + +@end table + +@item char_conversion(+@var{IN},+@var{OUT}) [ISO] +@findex char_conversion/2 +@syindex char_conversion/2 +@cnindex char_conversion/2 +While reading terms convert unquoted occurrences of the character +@var{IN} to the character @var{OUT}. Both @var{IN} and @var{OUT} must be +bound to single characters atoms. + +Character conversion only works if the flag @code{char_conversion} is +on. This is default in the @code{iso} and @code{sicstus} language +modes. As an example, character conversion can be used for instance to +convert characters from the ISO-LATIN-1 character set to ASCII. + +If @var{IN} is the same character as @var{OUT}, @code{char_conversion/2} +will remove this conversion from the table. + +@item current_char_conversion(?@var{IN},?@var{OUT}) [ISO] +@findex current_char_conversion/2 +@syindex current_char_conversion/2 +@cnindex current_char_conversion/2 +If @var{IN} is unbound give all current character +translations. Otherwise, give the translation for @var{IN}, if one +exists. + +@item write(@var{T}) [ISO] +@findex write/1 +@syindex write/1 +@cyindex write/1 +The term @var{T} is written to the current output stream according to +the operator declarations in force. + +@item writeln(@var{T}) [ISO] +@findex writeln/1 +@snindex writeln/1 +@cnindex writeln/1 +Same as @code{write/1} followed by @code{nl/0}. + +@item display(+@var{T}) +@findex display/1 +@syindex display/1 +@cyindex display/1 +Displays term @var{T} on the current output stream. All Prolog terms are +written in standard parenthesized prefix notation. + +@item write_canonical(+@var{T}) [ISO] +@findex display/1 +@syindex display/1 +@cnindex display/1 +Displays term @var{T} on the current output stream. Atoms are quoted +when necessary, and operators are ignored, that is, the term is written +in standard parenthesized prefix notation. + +@item write_term(+@var{T}, +@var{Opts}) [ISO] +@findex write_term/2 +@syindex write_term/2 +@cnindex write_term/2 +Displays term @var{T} on the current output stream, according to the +following options: + +@table @code +@item quoted(+@var{Bool}) [ISO] +If @code{true}, quote atoms if this would be necessary for the atom to +be recognized as an atom by YAP's parser. The default value is +@code{false}. + +@item ignore_ops(+@var{Bool}) [ISO] +If @code{true}, ignore operator declarations when writing the term. The +default value is @code{false}. + +@item numbervars(+@var{Bool}) [ISO] +If @code{true}, output terms of the form +@code{'$VAR'(N)}, where @var{N} is an integer, as a sequence of capital +letters. The default value is @code{false}. + +@item portrayed(+@var{Bool}) +If @code{true}, use @t{portray/1} to portray bound terms. The default +value is @code{false}. + +@item portray(+@var{Bool}) +If @code{true}, use @t{portray/1} to portray bound terms. The default +value is @code{false}. + +@item max_depth(+@var{Depth}) +If @code{Depth} is a positive integer, use @t{Depth} as +the maximum depth to portray a term. The default is @code{0}, that is, +unlimited depth. + +@item priority(+@var{Piority}) +If @code{Priority} is a positive integer smaller than @code{1200}, +give the context priority. The default is @code{1200}. + +@item cycles(+@var{Bool}) +Do not loop in rational trees (default). +@end table + +@item writeq(@var{T}) [ISO] +@findex writeq/1 +@syindex writeq/1 +@cyindex writeq/1 + Writes the term @var{T}, quoting names to make the result acceptable to +the predicate 'read' whenever necessary. + +@item print(@var{T}) +@findex print/1 +@syindex print/1 +@cyindex print/1 +Prints the term @var{T} to the current output stream using @code{write/1} +unless T is bound and a call to the user-defined predicate +@code{portray/1} succeeds. To do pretty printing of terms the user should +define suitable clauses for @code{portray/1} and use @code{print/1}. + +@item format(+@var{T},+@var{L}) +@findex format/2 +@saindex format/2 +@cnindex format/2 +Print formatted output to the current output stream. The arguments in +list @var{L} are output according to the string or atom @var{T}. + +A control sequence is introduced by a @code{w}. The following control +sequences are available in YAP: + +@table @code + +@item '~~' +Print a single tilde. + +@item '~a' +The next argument must be an atom, that will be printed as if by @code{write}. + +@item '~Nc' +The next argument must be an integer, that will be printed as a +character code. The number @var{N} is the number of times to print the +character (default 1). + +@item '~Ne' +@itemx '~NE' +@itemx '~Nf' +@itemx '~Ng' +@itemx '~NG' +The next argument must be a floating point number. The float @var{F}, the number +@var{N} and the control code @code{c} will be passed to @code{printf} as: + +@example + printf("%s.Nc", F) + @end example + +As an example: + +@example +?- format("~8e, ~8E, ~8f, ~8g, ~8G~w", + [3.14,3.14,3.14,3.14,3.14,3.14]). +3.140000e+00, 3.140000E+00, 3.140000, 3.14, 3.143.14 +@end example + +@item '~Nd' +The next argument must be an integer, and @var{N} is the number of digits +after the decimal point. If @var{N} is @code{0} no decimal points will be +printed. The default is @var{N = 0}. + +@example +?- format("~2d, ~d",[15000, 15000]). +150.00, 15000 +@end example + +@item '~ND' +Identical to @code{'~Nd'}, except that commas are used to separate groups +of three digits. + +@example +?- format("~2D, ~D",[150000, 150000]). +1,500.00, 150,000 +@end example + +@item '~i' +Ignore the next argument in the list of arguments: + +@example +?- format('The ~i met the boregrove',[mimsy]). +The met the boregrove +@end example + +@item '~k' +Print the next argument with @code{write_canonical}: + +@example +?- format("Good night ~k",a+[1,2]). +Good night +(a,[1,2]) +@end example + +@item '~Nn' +Print @var{N} newlines (where @var{N} defaults to 1). + +@item '~NN' +Print @var{N} newlines if at the beginning of the line (where @var{N} +defaults to 1). + +@item '~Nr' +The next argument must be an integer, and @var{N} is interpreted as a +radix, such that @code{2 <= N <= 36} (the default is 8). + +@example +?- format("~2r, 0x~16r, ~r", + [150000, 150000, 150000]). +100100100111110000, 0x249f0, 444760 +@end example + +@noindent +Note that the letters @code{a-z} denote digits larger than 9. + +@item '~NR' +Similar to '~NR'. The next argument must be an integer, and @var{N} is +interpreted as a radix, such that @code{2 <= N <= 36} (the default is 8). + +@example +?- format("~2r, 0x~16r, ~r", + [150000, 150000, 150000]). +100100100111110000, 0x249F0, 444760 +@end example + +@noindent +The only difference is that letters @code{A-Z} denote digits larger than 9. + +@item '~p' +Print the next argument with @code{print/1}: + +@example +?- format("Good night ~p",a+[1,2]). +Good night a+[1,2] +@end example + +@item '~q' +Print the next argument with @code{writeq/1}: + +@example +?- format("Good night ~q",'Hello'+[1,2]). +Good night 'Hello'+[1,2] +@end example + +@item '~Ns' +The next argument must be a list of character codes. The system then +outputs their representation as a string, where @var{N} is the maximum +number of characters for the string (@var{N} defaults to the length of the +string). + +@example +?- format("The ~s are ~4s",["woods","lovely"]). +The woods are love +@end example + +@item '~w' +Print the next argument with @code{write/1}: + +@example +?- format("Good night ~w",'Hello'+[1,2]). +Good night Hello+[1,2] +@end example + +@end table +The number of arguments, @code{N}, may be given as an integer, or it +may be given as an extra argument. The next example shows a small +procedure to write a variable number of @code{a} characters: + +@example +write_many_as(N) :- + format("~*c",[N,0'a]). +@end example + +The @code{format/2} built-in also allows for formatted output. One can +specify column boundaries and fill the intermediate space by a padding +character: + +@table @code +@item '~N|' +Set a column boundary at position @var{N}, where @var{N} defaults to the +current position. + +@item '~N+' +Set a column boundary at @var{N} characters past the current position, where +@var{N} defaults to @code{8}. + + +@item '~Nt' +Set padding for a column, where @var{N} is the fill code (default is +@key{SPC}). + +@end table + +The next example shows how to align columns and padding. We first show +left-alignment: + +@example + +@code{ + ?- format("~n*Hello~16+*~n",[]). +*Hello * +} +@end example + +Note that we reserve 16 characters for the column. + +The following example shows how to do right-alignment: + + +@example +@code{ + ?- format("*~tHello~16+*~n",[]). +* Hello* +} + +@end example + + +The @code{~t} escape sequence forces filling before @code{Hello}. + +We next show how to do centering: + +@example +@code{ + ?- format("*~tHello~t~16+*~n",[]). +* Hello * +} +@end example + + +The two @code{~t} escape sequence force filling both before and after +@code{Hello}. Space is then evenly divided between the right and the +left sides. + + +@item format(+@var{T}) +@findex format/1 +@saindex format/1 +@cnindex format/1 +Print formatted output to the current output stream. + + +@item format(+@var{S},+@var{T},+@var{L}) +@findex format/3 +@saindex format/3 +@cnindex format/3 +Print formatted output to stream @var{S}. + +@item with_output_to(+@var{Ouput},:@var{Goal}) +@findex with_output_to/2 +@saindex with_output_to/2 +@cnindex with_output_to/2 +Run @var{Goal} as @code{once/1}, while characters written to the current +output are sent to @var{Output}. The predicate is SWI-Prolog +specific. + +Applications should generally avoid creating atoms by breaking and +concatenating other atoms as the creation of large numbers of +intermediate atoms generally leads to poor performance, even more so in +multi-threaded applications. This predicate supports creating +difference-lists from character data efficiently. The example below +defines the DCG rule @code{term/3} to insert a term in the output: + +@example + term(Term, In, Tail) :- + with_output_to(codes(In, Tail), write(Term)). + +?- phrase(term(hello), X). + +X = [104, 101, 108, 108, 111] +@end example + +@table @code +@item A Stream handle or alias + Temporary switch current output to the given stream. Redirection using with_output_to/2 guarantees the original output is restored, also if Goal fails or raises an exception. See also call_cleanup/2. +@item atom(-@var{Atom}) + Create an atom from the emitted characters. Please note the remark above. +@item string(-@var{String}) + Create a string-object (not supported in YAP). +@item codes(-@var{Codes}) + Create a list of character codes from the emitted characters, similar to atom_codes/2. +@item codes(-@var{Codes}, -@var{Tail}) + Create a list of character codes as a difference-list. +@item chars(-@var{Chars}) + Create a list of one-character-atoms codes from the emitted characters, similar to atom_chars/2. +@item chars(-@var{Chars}, -@var{Tail}) + Create a list of one-character-atoms as a difference-list. +@end table + +@end table + +@node I/O of Characters, I/O for Streams, I/O of Terms, I/O +@subsection Handling Input/Output of Characters + +@table @code + +@item put(+@var{N}) +@findex put/1 +@syindex put/1 +@cyindex put/1 +Outputs to the current output stream the character whose ASCII code is +@var{N}. The character @var{N} must be a legal ASCII character code, an +expression yielding such a code, or a list in which case only the first +element is used. + +@item put_byte(+@var{N}) [ISO] +@findex put_byte/1 +@snindex put_byte/1 +@cnindex put_byte/1 +Outputs to the current output stream the character whose code is +@var{N}. The current output stream must be a binary stream. + +@item put_char(+@var{N}) [ISO] +@findex put_char/1 +@snindex put_char/1 +@cnindex put_char/1 +Outputs to the current output stream the character who is used to build +the representation of atom @code{A}. The current output stream must be a +text stream. + +@item put_code(+@var{N}) [ISO] +@findex put_code/1 +@snindex put_code/1 +@cnindex put_code/1 +Outputs to the current output stream the character whose ASCII code is +@var{N}. The current output stream must be a text stream. The character +@var{N} must be a legal ASCII character code, an expression yielding such +a code, or a list in which case only the first element is used. + +@item get(-@var{C}) +@findex get/1 +@syindex get/1 +@cyindex get/1 +The next non-blank character from the current input stream is unified +with @var{C}. Blank characters are the ones whose ASCII codes are not +greater than 32. If there are no more non-blank characters in the +stream, @var{C} is unified with -1. If @code{end_of_stream} has already +been reached in the previous reading, this call will give an error message. + +@item get0(-@var{C}) +@findex get0/1 +@syindex get0/1 +@cyindex get0/1 +The next character from the current input stream is consumed, and then +unified with @var{C}. There are no restrictions on the possible +values of the ASCII code for the character, but the character will be +internally converted by YAP. + +@item get_byte(-@var{C}) [ISO] +@findex get_byte/1 +@snindex get_byte/1 +@cnindex get_byte/1 +If @var{C} is unbound, or is a character code, and the current stream is a +binary stream, read the next byte from the current stream and unify its +code with @var{C}. + +@item get_char(-@var{C}) [ISO] +@findex get_char/1 +@snindex get_char/1 +@cnindex get_char/1 +If @var{C} is unbound, or is an atom representation of a character, and +the current stream is a text stream, read the next character from the +current stream and unify its atom representation with @var{C}. + +@item get_code(-@var{C}) [ISO] +@findex get_code/1 +@snindex get_code/1 +@cnindex get_code/1 +If @var{C} is unbound, or is the code for a character, and +the current stream is a text stream, read the next character from the +current stream and unify its code with @var{C}. + +@item peek_byte(-@var{C}) [ISO] +@findex peek_byte/1 +@snindex peek_byte/1 +@cnindex peek_byte/1 +If @var{C} is unbound, or is a character code, and the current stream is a +binary stream, read the next byte from the current stream and unify its +code with @var{C}, while leaving the current stream position unaltered. + +@item peek_char(-@var{C}) [ISO] +@findex peek_char/1 +@syindex peek_char/1 +@cnindex peek_char/1 +If @var{C} is unbound, or is an atom representation of a character, and +the current stream is a text stream, read the next character from the +current stream and unify its atom representation with @var{C}, while +leaving the current stream position unaltered. + +@item peek_code(-@var{C}) [ISO] +@findex peek_code/1 +@snindex peek_code/1 +@cnindex peek_code/1 +If @var{C} is unbound, or is the code for a character, and +the current stream is a text stream, read the next character from the +current stream and unify its code with @var{C}, while +leaving the current stream position unaltered. + +@item skip(+@var{N}) +@findex skip/1 +@syindex skip/1 +@cyindex skip/1 +Skips input characters until the next occurrence of the character with +ASCII code @var{N}. The argument to this predicate can take the same forms +as those for @code{put} (see 6.11). + +@item tab(+@var{N}) +@findex tab/1 +@syindex tab/1 +@cyindex tab/1 +Outputs @var{N} spaces to the current output stream. + +@item nl [ISO] +@findex nl/0 +@syindex nl/0 +@cyindex nl/0 +Outputs a new line to the current output stream. + +@end table + +@node I/O for Streams, C-Prolog to Terminal, I/O of Characters, I/O +@subsection Input/Output Predicates applied to Streams + +@table @code + +@item read(+@var{S},-@var{T}) [ISO] +@findex read/2 +@syindex read/2 +@cnindex read/2 +Reads term @var{T} from the stream @var{S} instead of from the current input +stream. + +@item read_term(+@var{S},-@var{T},+@var{Options}) [ISO] +@findex read_term/3 +@saindex read_term/3 +@cnindex read_term/3 +Reads term @var{T} from stream @var{S} with execution controlled by the +same options as @code{read_term/2}. + +@item write(+@var{S},@var{T}) [ISO] +@findex write/2 +@syindex write/2 +@cnindex write/2 +Writes term @var{T} to stream @var{S} instead of to the current output +stream. + +@item write_canonical(+@var{S},+@var{T}) [ISO] +@findex write_canonical/2 +@syindex write_canonical/2 +@cnindex write_canonical/2 +Displays term @var{T} on the stream @var{S}. Atoms are quoted when +necessary, and operators are ignored. + +@item write_canonical(+@var{T}) [ISO] +@findex write_canonical/1 +@syindex write_canonical/1 +@cnindex write_canonical/1 +Displays term @var{T}. Atoms are quoted when necessary, and operators +are ignored. + +@item write_term(+@var{S}, +@var{T}, +@var{Opts}) [ISO] +@findex write_term/3 +@syindex write_term/3 +@cnindex write_term/3 +Displays term @var{T} on the current output stream, according to the same +options used by @code{write_term/3}. + +@item writeq(+@var{S},@var{T}) [ISO] +@findex writeq/2 +@syindex writeq/2 +@cnindex writeq/2 +As @code{writeq/1}, but the output is sent to the stream @var{S}. + +@item display(+@var{S},@var{T}) +@findex display/2 +@syindex display/2 +@cnindex display/2 +Like @code{display/1}, but using stream @var{S} to display the term. + +@item print(+@var{S},@var{T}) +@findex print/2 +@syindex print/2 +@cnindex print/2 +Prints term @var{T} to the stream @var{S} instead of to the current output +stream. + +@item put(+@var{S},+@var{N}) +@findex put/2 +@syindex put/2 +@cnindex put/2 +As @code{put(N)}, but to stream @var{S}. + +@item put_byte(+@var{S},+@var{N}) [ISO] +@findex put_byte/2 +@snindex put_byte/2 +@cnindex put_byte/2 +As @code{put_byte(N)}, but to binary stream @var{S}. + +@item put_char(+@var{S},+@var{A}) [ISO] +@findex put_char/2 +@snindex put_char/2 +@cnindex put_char/2 +As @code{put_char(A)}, but to text stream @var{S}. + +@item put_code(+@var{S},+@var{N}) [ISO] +@findex put_code/2 +@snindex put_code/2 +@cnindex put_code/2 +As @code{put_code(N)}, but to text stream @var{S}. + +@item get(+@var{S},-@var{C}) +@findex get/2 +@syindex get/2 +@cnindex get/2 +The same as @code{get(C)}, but from stream @var{S}. + +@item get0(+@var{S},-@var{C}) +@findex get0/2 +@syindex get0/2 +@cnindex get0/2 +The same as @code{get0(C)}, but from stream @var{S}. + +@item get_byte(+@var{S},-@var{C}) [ISO] +@findex get_byte/2 +@snindex get_byte/2 +@cnindex get_byte/2 +If @var{C} is unbound, or is a character code, and the stream @var{S} is a +binary stream, read the next byte from that stream and unify its +code with @var{C}. + +@item get_char(+@var{S},-@var{C}) [ISO] +@findex get_char/2 +@snindex get_char/2 +@cnindex get_char/2 +If @var{C} is unbound, or is an atom representation of a character, and +the stream @var{S} is a text stream, read the next character from that +stream and unify its representation as an atom with @var{C}. + +@item get_code(+@var{S},-@var{C}) [ISO] +@findex get_code/2 +@snindex get_code/2 +@cnindex get_code/2 +If @var{C} is unbound, or is a character code, and the stream @var{S} is a +text stream, read the next character from that stream and unify its +code with @var{C}. + +@item peek_byte(+@var{S},-@var{C}) [ISO] +@findex peek_byte/2 +@snindex peek_byte/2 +@cnindex peek_byte/2 +If @var{C} is unbound, or is a character code, and @var{S} is a binary +stream, read the next byte from the current stream and unify its code +with @var{C}, while leaving the current stream position unaltered. + +@item peek_char(+@var{S},-@var{C}) [ISO] +@findex peek_char/2 +@snindex peek_char/2 +@cnindex peek_char/2 +If @var{C} is unbound, or is an atom representation of a character, and +the stream @var{S} is a text stream, read the next character from that +stream and unify its representation as an atom with @var{C}, while leaving +the current stream position unaltered. + +@item peek_code(+@var{S},-@var{C}) [ISO] +@findex peek_code/2 +@snindex peek_code/2 +@cnindex peek_code/2 +If @var{C} is unbound, or is an atom representation of a character, and +the stream @var{S} is a text stream, read the next character from that +stream and unify its representation as an atom with @var{C}, while leaving +the current stream position unaltered. + +@item skip(+@var{S},-@var{C}) +@findex skip/2 +@syindex skip/2 +@cnindex skip/2 +Like @code{skip/1}, but using stream @var{S} instead of the current +input stream. + +@item tab(+@var{S},+@var{N}) +@findex tab/2 +@syindex tab/2 +@cnindex tab/2 +The same as @code{tab/1}, but using stream @var{S}. + +@item nl(+@var{S}) [ISO] +@findex nl/1 +@syindex nl/1 +@cnindex nl/1 +Outputs a new line to stream @var{S}. + +@end table + +@node C-Prolog to Terminal, I/O Control, I/O for Streams, I/O +@subsection Compatible C-Prolog predicates for Terminal I/O + +@table @code + +@item ttyput(+@var{N}) +@findex ttyput/1 +@syindex ttyput/1 +@cnindex ttyput/1 +As @code{put(N)} but always to @code{user_output}. + +@item ttyget(-@var{C}) +@findex ttyget/1 +@syindex ttyget/1 +@cnindex ttyget/1 +The same as @code{get(C)}, but from stream @code{user_input}. + +@item ttyget0(-@var{C}) +@findex ttyget0/1 +@syindex ttyget0/1 +@cnindex ttyget0/1 +The same as @code{get0(C)}, but from stream @code{user_input}. + +@item ttyskip(-@var{C}) +@findex ttyskip/1 +@syindex ttyskip/1 +@cnindex ttyskip/1 +Like @code{skip/1}, but always using stream @code{user_input}. +stream. + +@item ttytab(+@var{N}) +@findex ttytab/1 +@syindex ttytab/1 +@cnindex ttytab/1 +The same as @code{tab/1}, but using stream @code{user_output}. + +@item ttynl +@findex ttynl/0 +@syindex ttynl/0 +@cnindex ttynl/0 +Outputs a new line to stream @code{user_output}. + +@end table + +@node I/O Control, Sockets, C-Prolog to Terminal, I/O +@subsection Controlling Input/Output + +@table @code + +@item exists(+@var{F}) +@findex exists/1 +@snindex exists/1 +@cyindex exists/1 +Checks if file @var{F} exists in the current directory. + +@item nofileerrors +@findex nofileerrors/0 +@syindex nofileerrors/0 +@cyindex nofileerrors/0 +Switches off the file_errors flag, so that the predicates @code{see/1}, +@code{tell/1}, @code{open/3} and @code{close/1} just fail, instead of producing +an error message and aborting whenever the specified file cannot be +opened or closed. + +@item fileerrors +@findex fileerrors/0 +@syindex fileerrors/0 +@cyindex fileerrors/0 +Switches on the file_errors flag so that in certain error conditions +I/O predicates will produce an appropriated message and abort. + +@item always_prompt_user +@findex always_prompt_user/0 +@snindex always_prompt_user/0 +@cnindex always_prompt_user/0 +Force the system to prompt the user even if the @code{user_input} stream +is not a terminal. This command is useful if you want to obtain +interactive control from a pipe or a socket. + +@end table + +@node Sockets, , I/O Control, I/O +@subsection Using Sockets From YAP + +YAP includes a SICStus Prolog compatible socket interface. In YAP-6.3 +this uses the @c{clib} package to emulate the old low level interface that +provides direct access to the major socket system calls. These calls +can be used both to open a new connection in the network or connect to +a networked server. Socket connections are described as read/write +streams, and standard I/O built-ins can be used to write on or read +from sockets. The following calls are available: + +@table @code + +@item socket(+@var{DOMAIN},+@var{TYPE},+@var{PROTOCOL},-@var{SOCKET}) +@findex socket/4 +@syindex socket/4 +@cnindex socket/4 +Corresponds to the BSD system call @code{socket}. Create a socket for +domain @var{DOMAIN} of type @var{TYPE} and protocol +@var{PROTOCOL}. Both @var{DOMAIN} and @var{TYPE} should be atoms, +whereas @var{PROTOCOL} must be an integer. +The new socket object is +accessible through a descriptor bound to the variable @var{SOCKET}. + +The current implementation of YAP only accepts one socket +domain: @code{'AF_INET'}. @c and @code{'AF_UNIX'}. +Socket types depend on the +underlying operating system, but at least the following types are +supported: @code{'SOCK_STREAM'} and @code{'SOCK_DGRAM'} (untested in 6.3). + +@item socket(+@var{DOMAIN},-@var{SOCKET}) +@findex socket/2 +@syindex socket/2 +@cnindex socket/2 + +Call @code{socket/4} with @var{TYPE} bound to @code{'SOCK_STREAM'} and +@var{PROTOCOL} bound to @code{0}. + +@item socket_close(+@var{SOCKET}) +@findex socket_close/1 +@syindex socket_close/1 +@cnindex socket_close/1 + +Close socket @var{SOCKET}. Note that sockets used in +@code{socket_connect} (that is, client sockets) should not be closed with +@code{socket_close}, as they will be automatically closed when the +corresponding stream is closed with @code{close/1} or @code{close/2}. + +@item socket_bind(+@var{SOCKET}, ?@var{PORT}) +@findex socket_bind/2 +@syindex socket_bind/2 +@cnindex socket_bind/2 + +Interface to system call @code{bind}, as used for servers: bind socket +to a port. Port information depends on the domain: +@table @code +@item 'AF_UNIX'(+@var{FILENAME}) (unsupported) +@item 'AF_FILE'(+@var{FILENAME}) +use file name @var{FILENAME} for UNIX or local sockets. + +@item 'AF_INET'(?@var{HOST},?PORT) +If @var{HOST} is bound to an atom, bind to host @var{HOST}, otherwise +if unbound bind to local host (@var{HOST} remains unbound). If port +@var{PORT} is bound to an integer, try to bind to the corresponding +port. If variable @var{PORT} is unbound allow operating systems to +choose a port number, which is unified with @var{PORT}. + +@end table + +@item socket_connect(+@var{SOCKET}, +@var{PORT}, -@var{STREAM}) +@findex socket_connect/3 +@syindex socket_connect/3 +@cnindex socket_connect/3 + +Interface to system call @code{connect}, used for clients: connect +socket @var{SOCKET} to @var{PORT}. The connection results in the +read/write stream @var{STREAM}. + +Port information depends on the domain: +@table @code +@item 'AF_UNIX'(+@var{FILENAME}) +@item 'AF_FILE'(+@var{FILENAME}) +connect to socket at file @var{FILENAME}. + +@item 'AF_INET'(+@var{HOST},+@var{PORT}) +Connect to socket at host @var{HOST} and port @var{PORT}. +@end table + +@item socket_listen(+@var{SOCKET}, +@var{LENGTH}) +@findex socket_listen/2 +@syindex socket_listen/2 +@cnindex socket_listen/2 +Interface to system call @code{listen}, used for servers to indicate +willingness to wait for connections at socket @var{SOCKET}. The +integer @var{LENGTH} gives the queue limit for incoming connections, +and should be limited to @code{5} for portable applications. The socket +must be of type @code{SOCK_STREAM} or @code{SOCK_SEQPACKET}. + +@item socket_accept(+@var{SOCKET}, -@var{STREAM}) +@findex socket_accept/2 +@syindex socket_accept/2 +@cnindex socket_accept/2 + +@item socket_accept(+@var{SOCKET}, -@var{CLIENT}, -@var{STREAM}) +@findex socket_accept/3 +@syindex socket_accept/3 +@cnindex socket_accept/3 +Interface to system call @code{accept}, used for servers to wait for +connections at socket @var{SOCKET}. The stream descriptor @var{STREAM} +represents the resulting connection. If the socket belongs to the +domain @code{'AF_INET'}, @var{CLIENT} unifies with an atom containing +the IP address for the client in numbers and dots notation. + +@item socket_accept(+@var{SOCKET}, -@var{STREAM}) +@findex socket_accept/2 +@syindex socket_accept/2 +@cnindex socket_accept/2 +Accept a connection but do not return client information. + +@item socket_buffering(+@var{SOCKET}, -@var{MODE}, -@var{OLD}, +@var{NEW}) +@findex socket_buffering/4 +@syindex socket_buffering/4 +@cnindex socket_buffering/4 +Set buffering for @var{SOCKET} in @code{read} or @code{write} +@var{MODE}. @var{OLD} is unified with the previous status, and @var{NEW} +receives the new status which may be one of @code{unbuf} or +@code{fullbuf}. + +@item socket_select(+@var{SOCKETS}, -@var{NEWSTREAMS}, +@var{TIMEOUT}, ++@var{STREAMS}, -@var{READSTREAMS}) [unsupported in YAP-6.3] +@findex socket_select/5 +@syindex socket_select/5 +@cnindex socket_select/5 +Interface to system call @code{select}, used for servers to wait for +connection requests or for data at sockets. The variable +@var{SOCKETS} is a list of form @var{KEY-SOCKET}, where @var{KEY} is +an user-defined identifier and @var{SOCKET} is a socket descriptor. The +variable @var{TIMEOUT} is either @code{off}, indicating execution will +wait until something is available, or of the form @var{SEC-USEC}, where +@var{SEC} and @var{USEC} give the seconds and microseconds before +@code{socket_select/5} returns. The variable @var{SOCKETS} is a list of +form @var{KEY-STREAM}, where @var{KEY} is an user-defined identifier +and @var{STREAM} is a stream descriptor + +Execution of @code{socket_select/5} unifies @var{READSTREAMS} from +@var{STREAMS} with readable data, and @var{NEWSTREAMS} with a list of +the form @var{KEY-STREAM}, where @var{KEY} was the key for a socket +with pending data, and @var{STREAM} the stream descriptor resulting +from accepting the connection. + +@item current_host(?@var{HOSTNAME}) +@findex current_host/1 + Unify @var{HOSTNAME} with an atom representing the fully qualified +hostname for the current host. Also succeeds if @var{HOSTNAME} is bound +to the unqualified hostname. + +@item hostname_address(?@var{HOSTNAME},?@var{IP_ADDRESS}) +@findex hostname_address/2 +@var{HOSTNAME} is an host name and @var{IP_ADDRESS} its IP +address in number and dots notation. + + +@end table + +@node Database, Sets, I/O, Top +@section Using the Clausal Data Base + +Predicates in YAP may be dynamic or static. By default, when +consulting or reconsulting, predicates are assumed to be static: +execution is faster and the code will probably use less space. +Static predicates impose some restrictions: in general there can be no +addition or removal of clauses for a procedure if it is being used in the +current execution. + +Dynamic predicates allow programmers to change the Clausal Data Base with +the same flexibility as in C-Prolog. With dynamic predicates it is +always possible to add or remove clauses during execution and the +semantics will be the same as for C-Prolog. But the programmer should be +aware of the fact that asserting or retracting are still expensive operations, +and therefore he should try to avoid them whenever possible. + +@table @code + +@item dynamic +@var{P} +@findex dynamic/1 +@saindex dynamic/1 +@cnindex dynamic/1 +Declares predicate @var{P} or list of predicates [@var{P1},...,@var{Pn}] +as a dynamic predicate. @var{P} must be written in form: +@var{name/arity}. + +@example +:- dynamic god/1. +@end example + +@noindent +a more convenient form can be used: + +@example +:- dynamic son/3, father/2, mother/2. +@end example + +or, equivalently, + +@example +:- dynamic [son/3, father/2, mother/2]. +@end example + +@noindent +Note: + +a predicate is assumed to be dynamic when +asserted before being defined. + +@item dynamic_predicate(+@var{P},+@var{Semantics}) +@findex dynamic_predicate/2 +@snindex dynamic_predicate/2 +@cnindex dynamic_predicate/2 +Declares predicate @var{P} or list of predicates [@var{P1},...,@var{Pn}] +as a dynamic predicate following either @code{logical} or +@code{immediate} semantics. + +@item compile_predicates(:@var{ListOfNameArity}) +@findex compile_predicates/1 +@snindex compile_predicates/1 +@cnindex compile_predicates/1 + +Compile a list of specified dynamic predicates (see @code{dynamic/1} and +@code{assert/1} into normal static predicates. This call tells the +Prolog environment the definition will not change anymore and further +calls to @code{assert/1} or @code{retract/1} on the named predicates +raise a permission error. This predicate is designed to deal with parts +of the program that is generated at runtime but does not change during +the remainder of the program execution. + +@menu + +Subnodes of Database +* Modifying the Database:: Asserting and Retracting +* Looking at the Database:: Finding out what is in the Data Base +* Database References:: Using Data Base References +* Internal Database:: YAP's Internal Database +* BlackBoard:: Storing and Fetching Terms in the BlackBoard + +@end menu + +@end table + +@node Modifying the Database, Looking at the Database, , Database +@subsection Modification of the Data Base + +These predicates can be used either for static or for dynamic +predicates: + +@table @code + +@item assert(+@var{C}) +@findex assert/1 +@saindex assert/1 +@caindex assert/1 + Same as @code{assertz/1}. Adds clause @var{C} to the program. If the predicate is undefined, +declare it as dynamic. New code should use @code{assertz/1} for better portability. + + Most Prolog systems only allow asserting clauses for dynamic +predicates. This is also as specified in the ISO standard. YAP allows +asserting clauses for static predicates, as long as the predicate is not +in use and the language flag is @t{cprolog}. Note that this feature is +deprecated, if you want to assert clauses for static procedures you +should use @code{assert_static/1}. + +@item asserta(+@var{C}) [ISO] +@findex asserta/1 +@saindex asserta/1 +@caindex asserta/1 + Adds clause @var{C} to the beginning of the program. If the predicate is +undefined, declare it as dynamic. + +@item assertz(+@var{C}) [ISO] +@findex assertz/1 +@saindex assertz/1 +@caindex assertz/1 + Adds clause @var{C} to the end of the program. If the predicate is +undefined, declare it as dynamic. + + Most Prolog systems only allow asserting clauses for dynamic +predicates. This is also as specified in the ISO standard. YAP allows +asserting clauses for static predicates. The current version of YAP +supports this feature, but this feature is deprecated and support may go +away in future versions. + +@item abolish(+@var{PredSpec}) [ISO] +@findex abolish/1 +@saindex abolish/1 +@caindex abolish/1 + Deletes the predicate given by @var{PredSpec} from the database. If +@var{PredSpec} is an unbound variable, delete all predicates for the +current module. The +specification must include the name and arity, and it may include module +information. Under @t{iso} language mode this built-in will only abolish +dynamic procedures. Under other modes it will abolish any procedures. + +@item abolish(+@var{P},+@var{N}) +@findex abolish/2 +@saindex abolish/2 +@caindex abolish/2 + Deletes the predicate with name @var{P} and arity @var{N}. It will remove +both static and dynamic predicates. + +@item assert_static(:@var{C}) +@findex assert_static/1 +@snindex assert_static/1 +@cnindex assert_static/1 +Adds clause @var{C} to a static procedure. Asserting a static clause +for a predicate while choice-points for the predicate are available has +undefined results. + +@item asserta_static(:@var{C}) +@findex asserta_static/1 +@snindex asserta_static/1 +@cnindex asserta_static/1 + Adds clause @var{C} to the beginning of a static procedure. + +@item assertz_static(:@var{C}) +@findex assertz_static/1 +@snindex assertz_static/1 +@cnindex assertz_static/1 + Adds clause @var{C} to the end of a static procedure. Asserting a +static clause for a predicate while choice-points for the predicate are +available has undefined results. + +@end table + +The following predicates can be used for dynamic predicates and for +static predicates, if source mode was on when they were compiled: + +@table @code + +@item clause(+@var{H},@var{B}) [ISO] +@findex clause/2 +@saindex clause/2 +@caindex clause/2 + A clause whose head matches @var{H} is searched for in the +program. Its head and body are respectively unified with @var{H} and +@var{B}. If the clause is a unit clause, @var{B} is unified with +@var{true}. + +This predicate is applicable to static procedures compiled with +@code{source} active, and to all dynamic procedures. + +@item clause(+@var{H},@var{B},-@var{R}) +@findex clause/3 +@saindex clause/3 +@caindex clause/3 +The same as @code{clause/2}, plus @var{R} is unified with the +reference to the clause in the database. You can use @code{instance/2} +to access the reference's value. Note that you may not use +@code{erase/1} on the reference on static procedures. + +@item nth_clause(+@var{H},@var{I},-@var{R}) +@findex nth_clause/3 +@saindex nth_clause/3 +@caindex nth_clause/3 +Find the @var{I}th clause in the predicate defining @var{H}, and give +a reference to the clause. Alternatively, if the reference @var{R} is +given the head @var{H} is unified with a description of the predicate +and @var{I} is bound to its position. + +@end table + +The following predicates can only be used for dynamic predicates: + +@table @code + +@item retract(+@var{C}) [ISO] +@findex retract/1 +@saindex retract/1 +@cnindex retract/1 +Erases the first clause in the program that matches @var{C}. This +predicate may also be used for the static predicates that have been +compiled when the source mode was @code{on}. For more information on +@code{source/0} (@pxref{Setting the Compiler}). + +@item retractall(+@var{G}) [ISO] +@findex retractall/1 +@saindex retractall/1 +@cnindex retractall/1 +Retract all the clauses whose head matches the goal @var{G}. Goal +@var{G} must be a call to a dynamic predicate. + +@end table + +@node Looking at the Database, Database References, Modifying the Database, Database +@subsection Looking at the Data Base + +@table @code + +@item listing +@findex listing/0 +@saindex listing/0 +@caindex listing/0 +Lists in the current output stream all the clauses for which source code +is available (these include all clauses for dynamic predicates and +clauses for static predicates compiled when source mode was @code{on}). + +@item listing(+@var{P}) +@findex listing/1 +@syindex listing/1 +@caindex listing/1 +Lists predicate @var{P} if its source code is available. + +@item portray_clause(+@var{C}) +@findex portray_clause/1 +@syindex portray_clause/1 +@cnindex portray_clause/1 +Write clause @var{C} as if written by @code{listing/0}. + +@item portray_clause(+@var{S},+@var{C}) +@findex portray_clause/2 +@syindex portray_clause/2 +@cnindex portray_clause/2 +Write clause @var{C} on stream @var{S} as if written by @code{listing/0}. + +@item current_atom(@var{A}) +@findex current_atom/1 +@syindex current_atom/1 +@cyindex current_atom/1 +Checks whether @var{A} is a currently defined atom. It is used to find all +currently defined atoms by backtracking. + +@item current_predicate(@var{F}) [ISO] +@findex current_predicate/1 +@syindex current_predicate/1 +@cyindex current_predicate/1 +@var{F} is the predicate indicator for a currently defined user or +library predicate. @var{F} is of the form @var{Na/Ar}, where the atom +@var{Na} is the name of the predicate, and @var{Ar} its arity. + +@item current_predicate(@var{A},@var{P}) +@findex current_predicate/2 +@syindex current_predicate/2 +@cnindex current_predicate/2 +Defines the relation: @var{P} is a currently defined predicate whose +name is the atom @var{A}. + +@item system_predicate(@var{A},@var{P}) +@findex system_predicate/2 +@syindex system_predicate/2 +@cnindex system_predicate/2 +Defines the relation: @var{P} is a built-in predicate whose name +is the atom @var{A}. + +@item predicate_property(@var{P},@var{Prop}) [ISO] +@findex predicate_property/2 +@saindex predicate_property/2 +@cnindex predicate_property/2 +For the predicates obeying the specification @var{P} unify @var{Prop} +with a property of @var{P}. These properties may be: +@table @code +@item built_in +@findex built_in/0 (predicate_property flag) +true for built-in predicates, +@item dynamic +@findex dynamic/0 (predicate_property flag) +true if the predicate is dynamic +@item static +@findex static/0 (predicate_property flag) +true if the predicate is static +@item meta_predicate(@var{M}) +@findex meta_predicate/1 (predicate_property flag) +true if the predicate has a meta_predicate declaration @var{M}. +@item multifile +@findex multifile/1 (predicate_property flag) +true if the predicate was declared to be multifile +@item imported_from(@var{Mod}) +@findex imported_from/1 (predicate_property flag) +true if the predicate was imported from module @var{Mod}. +@item exported +@findex exported/0 (predicate_property flag) +true if the predicate is exported in the current module. +@item public +@findex public/0 (predicate_property flag) +true if the predicate is public; note that all dynamic predicates are +public. +@item tabled +@findex tabled/0 (predicate_property flag) +true if the predicate is tabled; note that only static predicates can +be tabled in YAP. +@item source +@findex source/0 (predicate_property flag) +true if source for the predicate is available. +@item number_of_clauses(@var{ClauseCount}) +@findex number_of_clauses/1 (predicate_property flag) +Number of clauses in the predicate definition. Always one if external +or built-in. +@end table + +@item predicate_statistics(@var{P},@var{NCls},@var{Sz},@var{IndexSz}) +@findex predicate_statistics/4 + +Given predicate @var{P}, @var{NCls} is the number of clauses for +@var{P}, @var{Sz} is the amount of space taken to store those clauses +(in bytes), and @var{IndexSz} is the amount of space required to store +indices to those clauses (in bytes). + +@item predicate_erased_statistics(@var{P},@var{NCls},@var{Sz},@var{IndexSz}) +@findex predicate_statistics/4 + +Given predicate @var{P}, @var{NCls} is the number of erased clauses for +@var{P} that could not be discarded yet, @var{Sz} is the amount of space +taken to store those clauses (in bytes), and @var{IndexSz} is the amount +of space required to store indices to those clauses (in bytes). + +@end table + +@node Database References, Internal Database, Looking at the Database, Database +@subsection Using Data Base References + +Data Base references are a fast way of accessing terms. The predicates +@code{erase/1} and @code{instance/1} also apply to these references and may +sometimes be used instead of @code{retract/1} and @code{clause/2}. + +@table @code + +@item assert(+@var{C},-@var{R}) +@findex assert/2 +@saindex assert/2 +@caindex assert/2 + The same as @code{assert(C)} (@pxref{Modifying the Database}) but +unifies @var{R} with the database reference that identifies the new +clause, in a one-to-one way. Note that @code{asserta/2} only works for dynamic +predicates. If the predicate is undefined, it will automatically be +declared dynamic. + +@item asserta(+@var{C},-@var{R}) +@findex asserta/2 +@saindex asserta/2 +@caindex asserta/2 + The same as @code{asserta(C)} but unifying @var{R} with +the database reference that identifies the new clause, in a +one-to-one way. Note that @code{asserta/2} only works for dynamic +predicates. If the predicate is undefined, it will automatically be +declared dynamic. + +@item assertz(+@var{C},-@var{R}) +@findex assertz/2 +@saindex assertz/2 +@caindex assertz/2 + The same as @code{assertz(C)} but unifying @var{R} with +the database reference that identifies the new clause, in a +one-to-one way. Note that @code{asserta/2} only works for dynamic +predicates. If the predicate is undefined, it will automatically be +declared dynamic. + +@item retract(+@var{C},-@var{R}) +@findex retract/2 +@saindex retract/2 +@caindex retract/2 + Erases from the program the clause @var{C} whose +database reference is @var{R}. The predicate must be dynamic. + + +@end table + +@node Internal Database, BlackBoard, Database References, Database +@section Internal Data Base +Some programs need global information for, e.g. counting or collecting +data obtained by backtracking. As a rule, to keep this information, the +internal data base should be used instead of asserting and retracting +clauses (as most novice programmers do), . +In YAP (as in some other Prolog systems) the internal data base (i.d.b. +for short) is faster, needs less space and provides a better insulation of +program and data than using asserted/retracted clauses. +The i.d.b. is implemented as a set of terms, accessed by keys that +unlikely what happens in (non-Prolog) data bases are not part of the +term. Under each key a list of terms is kept. References are provided so that +terms can be identified: each term in the i.d.b. has a unique reference +(references are also available for clauses of dynamic predicates). + +@table @code + +@item recorda(+@var{K},@var{T},-@var{R}) +@findex recorda/3 +@saindex recorda/3 +@cyindex recorda/3 +Makes term @var{T} the first record under key @var{K} and unifies @var{R} +with its reference. + +@item recordz(+@var{K},@var{T},-@var{R}) +@findex recordz/3 +@saindex recordz/3 +@cyindex recordz/3 +Makes term @var{T} the last record under key @var{K} and unifies @var{R} +with its reference. + +@item recorda_at(+@var{R0},@var{T},-@var{R}) +@findex recorda_at/3 +@snindex recorda_at/3 +@cnindex recorda_at/3 +Makes term @var{T} the record preceding record with reference +@var{R0}, and unifies @var{R} with its reference. + +@item recordz_at(+@var{R0},@var{T},-@var{R}) +@findex recordz_at/3 +@snindex recordz_at/3 +@cnindex recordz_at/3 +Makes term @var{T} the record following record with reference +@var{R0}, and unifies @var{R} with its reference. + +@item recordaifnot(+@var{K},@var{T},-@var{R}) +@findex recordaifnot/3 +@saindex recordaifnot/3 +@cnindex recordaifnot/3 +If a term equal to @var{T} up to variable renaming is stored under key +@var{K} fail. Otherwise, make term @var{T} the first record under key +@var{K} and unify @var{R} with its reference. + +@item recordzifnot(+@var{K},@var{T},-@var{R}) +@findex recorda/3 +@snindex recorda/3 +@cnindex recorda/3 +If a term equal to @var{T} up to variable renaming is stored under key +@var{K} fail. Otherwise, make term @var{T} the first record under key +@var{K} and unify @var{R} with its reference. + +@item recorded(+@var{K},@var{T},@var{R}) +@findex recorded/3 +@saindex recorded/3 +@cyindex recorded/3 +Searches in the internal database under the key @var{K}, a term that +unifies with @var{T} and whose reference matches @var{R}. This +built-in may be used in one of two ways: +@itemize @bullet +@item @var{K} may be given, in this case the built-in will return all +elements of the internal data-base that match the key. +@item @var{R} may be given, if so returning the key and element that +match the reference. +@end itemize + +@item erase(+@var{R}) +@findex erase/1 +@saindex erase/1 +@cyindex erase/1 +The term referred to by @var{R} is erased from the internal database. If +reference @var{R} does not exist in the database, @code{erase} just fails. + +@item erased(+@var{R}) +@findex erased/1 +@saindex erased/1 +@cyindex erased/1 +Succeeds if the object whose database reference is @var{R} has been +erased. + +@item instance(+@var{R},-@var{T}) +@findex instance/2 +@saindex instance/2 +@cyindex instance/2 +If @var{R} refers to a clause or a recorded term, @var{T} is unified +with its most general instance. If @var{R} refers to an unit clause +@var{C}, then @var{T} is unified with @code{@var{C} :- true}. When +@var{R} is not a reference to an existing clause or to a recorded term, +this goal fails. + +@item eraseall(+@var{K}) +@findex eraseall/1 +@snindex eraseall/1 +@cnindex eraseall/1 +All terms belonging to the key @code{K} are erased from the internal +database. The predicate always succeeds. + +@item current_key(?@var{A},?@var{K}) +@findex current_key/2 +@syindex current_key/2 +@cnindex current_key/2 +Defines the relation: @var{K} is a currently defined database key whose +name is the atom @var{A}. It can be used to generate all the keys for +the internal data-base. + +@item nth_instance(?@var{Key},?@var{Index},?@var{R}) +@findex nth_instance/3 +@saindex nth_instance/3 +@cnindex nth_instance/3 +Fetches the @var{Index}nth entry in the internal database under the key +@var{Key}. Entries are numbered from one. If the key @var{Key} or the +@var{Index} are bound, a reference is unified with @var{R}. Otherwise, +the reference @var{R} must be given, and YAP will find +the matching key and index. + + +@item nth_instance(?@var{Key},?@var{Index},@var{T},?@var{R}) +@findex nth_instance/4 +@saindex nth_instance/4 +@cnindex nth_instance/4 +Fetches the @var{Index}nth entry in the internal database under the key +@var{Key}. Entries are numbered from one. If the key @var{Key} or the +@var{Index} are bound, a reference is unified with @var{R}. Otherwise, +the reference @var{R} must be given, and YAP will find +the matching key and index. + +@item key_statistics(+@var{K},-@var{Entries},-@var{Size},-@var{IndexSize}) +@findex key_statistics/4 +@snindex key_statistics/4 +@cnindex key_statistics/4 +Returns several statistics for a key @var{K}. Currently, it says how +many entries we have for that key, @var{Entries}, what is the +total size spent on entries, @var{Size}, and what is the amount of +space spent in indices. + +@item key_statistics(+@var{K},-@var{Entries},-@var{TotalSize}) +@findex key_statistics/3 +@snindex key_statistics/3 +@cnindex key_statistics/3 +Returns several statistics for a key @var{K}. Currently, it says how +many entries we have for that key, @var{Entries}, what is the +total size spent on this key. + +@item get_value(+@var{A},-@var{V}) +@findex get_value/2 +@snindex get_value/2 +@cnindex get_value/2 +In YAP, atoms can be associated with constants. If one such +association exists for atom @var{A}, unify the second argument with the +constant. Otherwise, unify @var{V} with @code{[]}. + +This predicate is YAP specific. + +@item set_value(+@var{A},+@var{C}) +@findex set_value/2 +@snindex set_value/2 +@cnindex set_value/2 +Associate atom @var{A} with constant @var{C}. + +The @code{set_value} and @code{get_value} built-ins give a fast alternative to +the internal data-base. This is a simple form of implementing a global +counter. +@example + read_and_increment_counter(Value) :- + get_value(counter, Value), + Value1 is Value+1, + set_value(counter, Value1). +@end example +@noindent +This predicate is YAP specific. + +@item recordzifnot(+@var{K},@var{T},-@var{R}) +@findex recordzifnot/3 +@snindex recordzifnot/3 +@cnindex recordzifnot/3 +If a variant of @var{T} is stored under key @var{K} fail. Otherwise, make +term @var{T} the last record under key @var{K} and unify @var{R} with its +reference. + +This predicate is YAP specific. + +@item recordaifnot(+@var{K},@var{T},-@var{R}) +@findex recordaifnot/3 +@snindex recordaifnot/3 +@cnindex recordaifnot/3 +If a variant of @var{T} is stored under key @var{K} fail. Otherwise, make +term @var{T} the first record under key @var{K} and unify @var{R} with its +reference. + +This predicate is YAP specific. + +@end table + +There is a strong analogy between the i.d.b. and the way dynamic +predicates are stored. In fact, the main i.d.b. predicates might be +implemented using dynamic predicates: + +@example +recorda(X,T,R) :- asserta(idb(X,T),R). +recordz(X,T,R) :- assertz(idb(X,T),R). +recorded(X,T,R) :- clause(idb(X,T),R). +@end example +@noindent + We can take advantage of this, the other way around, as it is quite +easy to write a simple Prolog interpreter, using the i.d.b.: + +@example +asserta(G) :- recorda(interpreter,G,_). +assertz(G) :- recordz(interpreter,G,_). +retract(G) :- recorded(interpreter,G,R), !, erase(R). +call(V) :- var(V), !, fail. +call((H :- B)) :- !, recorded(interpreter,(H :- B),_), call(B). +call(G) :- recorded(interpreter,G,_). +@end example +@noindent +In YAP, much attention has been given to the implementation of the +i.d.b., especially to the problem of accelerating the access to terms kept in +a large list under the same key. Besides using the key, YAP uses an internal +lookup function, transparent to the user, to find only the terms that might +unify. For instance, in a data base containing the terms + +@example +b +b(a) +c(d) +e(g) +b(X) +e(h) +@end example + +@noindent +stored under the key k/1, when executing the query + +@example +:- recorded(k(_),c(_),R). +@end example + +@noindent +@code{recorded} would proceed directly to the third term, spending almost the +time as if @code{a(X)} or @code{b(X)} was being searched. + The lookup function uses the functor of the term, and its first three +arguments (when they exist). So, @code{recorded(k(_),e(h),_)} would go +directly to the last term, while @code{recorded(k(_),e(_),_)} would find +first the fourth term, and then, after backtracking, the last one. + + This mechanism may be useful to implement a sort of hierarchy, where +the functors of the terms (and eventually the first arguments) work as +secondary keys. + + In the YAP's i.d.b. an optimized representation is used for +terms without free variables. This results in a faster retrieval of terms +and better space usage. Whenever possible, avoid variables in terms in terms stored in the i.d.b. + + +@node BlackBoard, , Internal Database, Database +@section The Blackboard + +YAP implements a blackboard in the style of the SICStus Prolog +blackboard. The blackboard uses the same underlying mechanism as the +internal data-base but has several important differences: +@itemize @bullet +@item It is module aware, in contrast to the internal data-base. +@item Keys can only be atoms or integers, and not compound terms. +@item A single term can be stored per key. +@item An atomic update operation is provided; this is useful for +parallelism. +@end itemize + + +@table @code +@item bb_put(+@var{Key},?@var{Term}) +@findex bb_put/2 +@syindex bb_put/2 +@cnindex bb_put/2 +Store term table @var{Term} in the blackboard under key @var{Key}. If a +previous term was stored under key @var{Key} it is simply forgotten. + +@item bb_get(+@var{Key},?@var{Term}) +@findex bb_get/2 +@syindex bb_get/2 +@cnindex bb_get/2 +Unify @var{Term} with a term stored in the blackboard under key +@var{Key}, or fail silently if no such term exists. + +@item bb_delete(+@var{Key},?@var{Term}) +@findex bb_delete/2 +@syindex bb_delete/2 +@cnindex bb_delete/2 +Delete any term stored in the blackboard under key @var{Key} and unify +it with @var{Term}. Fail silently if no such term exists. + +@item bb_update(+@var{Key},?@var{Term},?@var{New}) +@findex bb_update/3 +@syindex bb_update/3 +@cnindex bb_update/3 +Atomically unify a term stored in the blackboard under key @var{Key} +with @var{Term}, and if the unification succeeds replace it by +@var{New}. Fail silently if no such term exists or if unification fails. + +@end table + +@node Sets, Grammars, Database, Top +@section Collecting Solutions to a Goal + +When there are several solutions to a goal, if the user wants to collect all +the solutions he may be led to use the data base, because backtracking will +forget previous solutions. + +YAP allows the programmer to choose from several system +predicates instead of writing his own routines. @code{findall/3} gives you +the fastest, but crudest solution. The other built-in predicates +post-process the result of the query in several different ways: + +@table @code + +@item findall(@var{T},+@var{G},-@var{L}) [ISO] +@findex findall/3 +@syindex findall/3 +@cyindex findall/3 +Unifies @var{L} with a list that contains all the instantiations of the +term @var{T} satisfying the goal @var{G}. + +With the following program: +@example +a(2,1). +a(1,1). +a(2,2). +@end example +@noindent +the answer to the query +@example +findall(X,a(X,Y),L). +@end example +@noindent +would be: +@example +X = _32 +Y = _33 +L = [2,1,2]; +no +@end example + +@item findall(@var{T},+@var{G},+@var{L},-@var{L0}) +@findex findall/4 +@syindex findall/4 +@cnindex findall/4 +Similar to @code{findall/3}, but appends all answers to list @var{L0}. + +@item all(@var{T},+@var{G},-@var{L}) +@findex all/3 +@snindex all/3 +@cnindex all/3 +Similar to @code{findall(@var{T},@var{G},@var{L})} but eliminate +repeated elements. Thus, assuming the same clauses as in the above +example, the reply to the query + +@example +all(X,a(X,Y),L). +@end example +@noindent +would be: + +@example +X = _32 +Y = _33 +L = [2,1]; +no +@end example + +Note that @code{all/3} will fail if no answers are found. + +@item bagof(@var{T},+@var{G},-@var{L}) [ISO] +@findex bagof/3 +@saindex bagof/3 +@cyindex bagof/3 +For each set of possible instances of the free variables occurring in +@var{G} but not in @var{T}, generates the list @var{L} of the instances of +@var{T} satisfying @var{G}. Again, assuming the same clauses as in the +examples above, the reply to the query + +@example +bagof(X,a(X,Y),L). + +would be: +X = _32 +Y = 1 +L = [2,1]; +X = _32 +Y = 2 +L = [2]; +no +@end example + +@item setof(@var{X},+@var{P},-@var{B}) [ISO] +@findex setof/3 +@saindex setof/3 +@cyindex setof/3 +Similar to @code{bagof(@var{T},@var{G},@var{L})} but sorts list +@var{L} and keeping only one copy of each element. Again, assuming the +same clauses as in the examples above, the reply to the query +@example +setof(X,a(X,Y),L). +@end example +@noindent +would be: +@example +X = _32 +Y = 1 +L = [1,2]; +X = _32 +Y = 2 +L = [2]; +no +@end example + +@end table + +@node Grammars, OS, Sets, Top +@section Grammar Rules + +Grammar rules in Prolog are both a convenient way to express definite +clause grammars and an extension of the well known context-free grammars. + +A grammar rule is of the form: + +@example +@i{ head --> body } +@end example +@noindent +where both @i{head} and @i{body} are sequences of one or more items +linked by the standard conjunction operator ','. + +@emph{Items can be:} + +@itemize @bullet +@item +a @emph{non-terminal} symbol may be either a complex term or an atom. +@item +a @emph{terminal} symbol may be any Prolog symbol. Terminals are +written as Prolog lists. +@item +an @emph{empty body} is written as the empty list '[ ]'. +@item +@emph{extra conditions} may be inserted as Prolog procedure calls, by being +written inside curly brackets '@{' and '@}'. +@item +the left side of a rule consists of a nonterminal and an optional list +of terminals. +@item +alternatives may be stated in the right-hand side of the rule by using +the disjunction operator ';'. +@item +the @emph{cut} and @emph{conditional} symbol ('->') may be inserted in the +right hand side of a grammar rule +@end itemize + +Grammar related built-in predicates: + +@table @code + +@item expand_term(@var{T},-@var{X}) +@findex expand_term/2 +@syindex expand_term/2 +@cyindex expand_term/2 + +This predicate is used by YAP for preprocessing each top level +term read when consulting a file and before asserting or executing it. +It rewrites a term @var{T} to a term @var{X} according to the following +rules: first try @code{term_expansion/2} in the current module, and then try to use the user defined predicate +@code{user:term_expansion/2}. If this call fails then the translating process +for DCG rules is applied, together with the arithmetic optimizer +whenever the compilation of arithmetic expressions is in progress. + +@item @var{CurrentModule}:term_expansion(@var{T},-@var{X}), user:term_expansion(@var{T},-@var{X}) +@findex term_expansion/2 +@syindex term_expansion/2 +@cyindex term_expansion/2 +This user-defined predicate is called by @code{expand_term/3} to +preprocess all terms read when consulting a file. If it succeeds: + +@itemize +@item +If @var{X} is of the form @code{:- G} or @code{?- G}, it is processed as +a directive. +@item +If @var{X} is of the form @code{'$source_location'(, +):} it is processed as if from @code{File} and line @code{Line}. + +@item +If @var{X} is a list, all terms of the list are asserted or processed +as directives. +@item The term @var{X} is asserted instead of @var{T}. +@end itemize + +@item @var{CurrentModule}:goal_expansion(+@var{G},+@var{M},-@var{NG}), user:goal_expansion(+@var{G},+@var{M},-@var{NG}) +@findex goal_expansion/3 +@snindex goal_expansion/3 +@cnindex goal_expansion/3 +YAP now supports @code{goal_expansion/3}. This is an user-defined +procedure that is called after term expansion when compiling or +asserting goals for each sub-goal in a clause. The first argument is +bound to the goal and the second to the module under which the goal +@var{G} will execute. If @code{goal_expansion/3} succeeds the new +sub-goal @var{NG} will replace @var{G} and will be processed in the same +way. If @code{goal_expansion/3} fails the system will use the default +rules. + +@item phrase(+@var{P},@var{L},@var{R}) +@findex phrase/3 +@syindex phrase/3 +@cnindex phrase/3 +This predicate succeeds when the difference list @code{@var{L}-@var{R}} +is a phrase of type @var{P}. + +@item phrase(+@var{P},@var{L}) +@findex phrase/2 +@syindex phrase/2 +@cnindex phrase/2 +This predicate succeeds when @var{L} is a phrase of type @var{P}. The +same as @code{phrase(P,L,[])}. + +Both this predicate and the previous are used as a convenient way to +start execution of grammar rules. + +@item 'C'(@var{S1},@var{T},@var{S2}) +@findex C/3 +@syindex C/3 +@cnindex C/3 +This predicate is used by the grammar rules compiler and is defined as +@code{'C'([H|T],H,T)}. + +@end table + +@node OS, Term Modification, Grammars, Top +@section Access to Operating System Functionality + +The following built-in predicates allow access to underlying +Operating System functionality: + +@table @code + +@item cd(+@var{D}) +@findex cd/1 +@snindex cd/1 +@cnindex cd/1 +Changes the current directory (on UNIX environments). + +@item cd +@findex cd/0 +@snindex cd/0 +@cnindex cd/0 +Changes the current directory (on UNIX environments) to the user's home directory. + +@item environ(+@var{E},-@var{S}) +@findex environ/2 +@syindex environ/2 +@cnindex environ/2 +@comment This backtrackable predicate unifies the first argument with an +@comment environment variable @var{E}, and the second with its value @var{S}. It +@comment can used to detect all environment variables. + Given an environment variable @var{E} this predicate unifies the second argument @var{S} with its value. + +@item getcwd(-@var{D}) +@findex getcwd/1 +@snindex getcwd/1 +@cnindex getcwd/1 +Unify the current directory, represented as an atom, with the argument +@var{D}. + +@item pwd +@findex pwd/0 +@snindex pwd/0 +@cnindex pwd/0 +Prints the current directory. + +@item ls +@findex ls/0 +@snindex ls/0 +@cnindex ls/0 +Prints a list of all files in the current directory. + +@item putenv(+@var{E},+@var{S}) +@findex putenv/2 +@snindex putenv/2 +@cnindex putenv/2 +Set environment variable @var{E} to the value @var{S}. If the +environment variable @var{E} does not exist, create a new one. Both the +environment variable and the value must be atoms. + +@item rename(+@var{F},+@var{G}) +@findex rename/2 +@snindex rename/2 +@cyindex rename/2 +Renames file @var{F} to @var{G}. + +@item sh +@findex sh/0 +@snindex sh/0 +@cyindex sh/0 +Creates a new shell interaction. + +@item system(+@var{S}) +@findex system/1 +@snindex system/1 +@cyindex system/1 +Passes command @var{S} to the Bourne shell (on UNIX environments) or the +current command interpreter in WIN32 environments. + +@item unix(+@var{S}) +@findex unix/1 +@snindex unix/1 +@cnindex unix/1 +Access to Unix-like functionality: +@table @code +@item argv/1 +Return a list of arguments to the program. These are the arguments that +follow a @code{--}, as in the usual Unix convention. +@item cd/0 +Change to home directory. +@item cd/1 +Change to given directory. Acceptable directory names are strings or +atoms. +@item environ/2 +If the first argument is an atom, unify the second argument with the +value of the corresponding environment variable. +@item getcwd/1 +Unify the first argument with an atom representing the current directory. +@item putenv/2 +Set environment variable @var{E} to the value @var{S}. If the +environment variable @var{E} does not exist, create a new one. Both the +environment variable and the value must be atoms. +@item shell/1 +Execute command under current shell. Acceptable commands are strings or +atoms. +@item system/1 +Execute command with @code{/bin/sh}. Acceptable commands are strings or +atoms. +@item shell/0 +Execute a new shell. +@end table + +@item working_directory(-@var{CurDir},?@var{NextDir}) +@findex working_directory/2 +@syindex working_directory/2 +@cnindex working_directory/2 @c +Fetch the current directory at @var{CurDir}. If @var{NextDir} is bound +to an atom, make its value the current working directory. + +@item alarm(+@var{Seconds},+@var{Callable},+@var{OldAlarm}) +@findex alarm/3 +@snindex alarm/3 +@cnindex alarm/3 +Arranges for YAP to be interrupted in @var{Seconds} seconds, or in +[@var{Seconds}|@var{MicroSeconds}]. When interrupted, YAP will execute +@var{Callable} and then return to the previous execution. If +@var{Seconds} is @code{0}, no new alarm is scheduled. In any event, +any previously set alarm is canceled. + +The variable @var{OldAlarm} unifies with the number of seconds remaining +until any previously scheduled alarm was due to be delivered, or with +@code{0} if there was no previously scheduled alarm. + +Note that execution of @var{Callable} will wait if YAP is +executing built-in predicates, such as Input/Output operations. + +The next example shows how @var{alarm/3} can be used to implement a +simple clock: + +@example +loop :- loop. + +ticker :- write('.'), flush_output, + get_value(tick, yes), + alarm(1,ticker,_). + +:- set_value(tick, yes), alarm(1,ticker,_), loop. +@end example + +The clock, @code{ticker}, writes a dot and then checks the flag +@code{tick} to see whether it can continue ticking. If so, it calls +itself again. Note that there is no guarantee that the each dot +corresponds a second: for instance, if the YAP is waiting for +user input, @code{ticker} will wait until the user types the entry in. + +The next example shows how @code{alarm/3} can be used to guarantee that +a certain procedure does not take longer than a certain amount of time: + +@example +loop :- loop. + +:- catch((alarm(10, throw(ball), _),loop), + ball, + format('Quota exhausted.~n',[])). +@end example +In this case after @code{10} seconds our @code{loop} is interrupted, +@code{ball} is thrown, and the handler writes @code{Quota exhausted}. +Execution then continues from the handler. + +Note that in this case @code{loop/0} always executes until the alarm is +sent. Often, the code you are executing succeeds or fails before the +alarm is actually delivered. In this case, you probably want to disable +the alarm when you leave the procedure. The next procedure does exactly so: +@example +once_with_alarm(Time,Goal,DoOnAlarm) :- + catch(execute_once_with_alarm(Time, Goal), alarm, DoOnAlarm). + +execute_once_with_alarm(Time, Goal) :- + alarm(Time, alarm, _), + ( call(Goal) -> alarm(0, alarm, _) ; alarm(0, alarm, _), fail). +@end example + +The procedure @code{once_with_alarm/3} has three arguments: +the @var{Time} to wait before the alarm is +sent; the @var{Goal} to execute; and the goal @var{DoOnAlarm} to execute +if the alarm is sent. It uses @code{catch/3} to handle the case the +@code{alarm} is sent. Then it starts the alarm, calls the goal +@var{Goal}, and disables the alarm on success or failure. + +@item on_signal(+@var{Signal},?@var{OldAction},+@var{Callable}) +@findex on_signal/3 +@snindex on_signal/3 +@cnindex on_signal/3 +Set the interrupt handler for soft interrupt @var{Signal} to be +@var{Callable}. @var{OldAction} is unified with the previous handler. + +Only a subset of the software interrupts (signals) can have their +handlers manipulated through @code{on_signal/3}. +Their POSIX names, YAP names and default behavior is given below. +The "YAP name" of the signal is the atom that is associated with +each signal, and should be used as the first argument to +@code{on_signal/3}. It is chosen so that it matches the signal's POSIX +name. + +@code{on_signal/3} succeeds, unless when called with an invalid +signal name or one that is not supported on this platform. No checks +are made on the handler provided by the user. + +@table @code +@item sig_up (Hangup) + SIGHUP in Unix/Linux; Reconsult the initialization files + ~/.yaprc, ~/.prologrc and ~/prolog.ini. +@item sig_usr1 and sig_usr2 (User signals) + SIGUSR1 and SIGUSR2 in Unix/Linux; Print a message and halt. +@end table + +A special case is made, where if @var{Callable} is bound to +@code{default}, then the default handler is restored for that signal. + +A call in the form @code{on_signal(@var{S},@var{H},@var{H})} can be used +to retrieve a signal's current handler without changing it. + +It must be noted that although a signal can be received at all times, +the handler is not executed while YAP is waiting for a query at the +prompt. The signal will be, however, registered and dealt with as soon +as the user makes a query. + +Please also note, that neither POSIX Operating Systems nor YAP guarantee +that the order of delivery and handling is going to correspond with the +order of dispatch. + +@end table + +@node Term Modification, Global Variables, OS, Top +@section Term Modification + +@cindex updating terms +It is sometimes useful to change the value of instantiated +variables. Although, this is against the spirit of logic programming, it +is sometimes useful. As in other Prolog systems, YAP has +several primitives that allow updating Prolog terms. Note that these +primitives are also backtrackable. + +The @code{setarg/3} primitive allows updating any argument of a Prolog +compound terms. The @code{mutable} family of predicates provides +@emph{mutable variables}. They should be used instead of @code{setarg/3}, +as they allow the encapsulation of accesses to updatable +variables. Their implementation can also be more efficient for long +deterministic computations. + +@table @code +@item setarg(+@var{I},+@var{S},?@var{T}) +@findex setarg/3n +@snindex setarg/3n +@cnindex setarg/3n +Set the value of the @var{I}th argument of term @var{S} to term @var{T}. + +@cindex mutable variables +@item create_mutable(+@var{D},-@var{M}) +@findex create_mutable/2 +@syindex create_mutable/2 +@cnindex create_mutable/2 +Create new mutable variable @var{M} with initial value @var{D}. + +@item get_mutable(?@var{D},+@var{M}) +@findex get_mutable/2 +@syindex get_mutable/2 +@cnindex get_mutable/2 +Unify the current value of mutable term @var{M} with term @var{D}. + +@item is_mutable(?@var{D}) +@findex is_mutable/1 +@syindex is_mutable/1 +@cnindex is_mutable/1 +Holds if @var{D} is a mutable term. + +@item get_mutable(?@var{D},+@var{M}) +@findex get_mutable/2 +@syindex get_mutable/2 +@cnindex get_mutable/2 +Unify the current value of mutable term @var{M} with term @var{D}. + +@item update_mutable(+@var{D},+@var{M}) +@findex update_mutable/2 +@syindex update_mutable/2 +@cnindex update_mutable/2 +Set the current value of mutable term @var{M} to term @var{D}. +@end table + +@node Global Variables, Profiling, Term Modification, Top +@section Global Variables + +@cindex global variables + +Global variables are associations between names (atoms) and +terms. They differ in various ways from storing information using +@code{assert/1} or @code{recorda/3}. + +@itemize @bullet +@item The value lives on the Prolog (global) stack. This implies that +lookup time is independent from the size of the term. This is +particularly interesting for large data structures such as parsed XML +documents or the CHR global constraint store. + +@item They support both global assignment using @code{nb_setval/2} and +backtrackable assignment using @code{b_setval/2}. + +@item Only one value (which can be an arbitrary complex Prolog term) +can be associated to a variable at a time. + +@item Their value cannot be shared among threads. Each thread has its own +namespace and values for global variables. +@end itemize + +Currently global variables are scoped globally. We may consider module +scoping in future versions. Both @code{b_setval/2} and +@code{nb_setval/2} implicitly create a variable if the referenced name +does not already refer to a variable. + +Global variables may be initialised from directives to make them +available during the program lifetime, but some considerations are +necessary for saved-states and threads. Saved-states to not store +global variables, which implies they have to be declared with +@code{initialization/1} to recreate them after loading the saved +state. Each thread has its own set of global variables, starting with +an empty set. Using @code{thread_initialization/1} to define a global +variable it will be defined, restored after reloading a saved state +and created in all threads that are created after the +registration. Finally, global variables can be initialised using the +exception hook called @code{exception/3}. The latter technique is used +by CHR. + +@table @code +@item b_setval(+@var{Name}, +@var{Value}) +@findex b_setval/2 +@snindex b_setval/2 +@cnindex b_setval/2 +Associate the term @var{Value} with the atom @var{Name} or replaces +the currently associated value with @var{Value}. If @var{Name} does +not refer to an existing global variable a variable with initial value +[] is created (the empty list). On backtracking the assignment is +reversed. + +@item b_getval(+@var{Name}, -@var{Value}) +@findex b_getval/2 +@snindex b_getval/2 +@cnindex b_getval/2 +Get the value associated with the global variable @var{Name} and unify +it with @var{Value}. Note that this unification may further +instantiate the value of the global variable. If this is undesirable +the normal precautions (double negation or @code{copy_term/2}) must be +taken. The @code{b_getval/2} predicate generates errors if @var{Name} is not +an atom or the requested variable does not exist. + +Notice that for compatibility with other systems @var{Name} @emph{must} be already associated with a term: otherwise the system will generate an error. + +@item nb_setval(+@var{Name}, +@var{Value}) +@findex nb_setval/2 +@snindex nb_setval/2 +@cnindex nb_setval/2 +Associates a copy of @var{Value} created with @code{duplicate_term/2} with +the atom @var{Name}. Note that this can be used to set an initial +value other than @code{[]} prior to backtrackable assignment. + +@item nb_getval(+@var{Name}, -@var{Value}) +@findex nb_getval/2 +@snindex nb_getval/2 +@cnindex nb_getval/2 +The @code{nb_getval/2} predicate is a synonym for @code{b_getval/2}, +introduced for compatibility and symmetry. As most scenarios will use +a particular global variable either using non-backtrackable or +backtrackable assignment, using @code{nb_getval/2} can be used to +document that the variable is used non-backtrackable. + +@item nb_linkval(+@var{Name}, +@var{Value}) +@findex nb_linkval/2 +@snindex nb_linkval/2 +@cnindex nb_linkval/2 +Associates the term @var{Value} with the atom @var{Name} without +copying it. This is a fast special-purpose variation of @code{nb_setval/2} +intended for expert users only because the semantics on backtracking +to a point before creating the link are poorly defined for compound +terms. The principal term is always left untouched, but backtracking +behaviour on arguments is undone if the original assignment was +trailed and left alone otherwise, which implies that the history that +created the term affects the behaviour on backtracking. Please +consider the following example: + +@example +demo_nb_linkval :- + T = nice(N), + ( N = world, + nb_linkval(myvar, T), + fail + ; nb_getval(myvar, V), + writeln(V) + ). +@end example + +@item nb_set_shared_val(+@var{Name}, +@var{Value}) +@findex nb_set_shared_val/2 +@snindex nb_set_shared_val/2 +@cnindex nb_set_shared_val/2 +Associates the term @var{Value} with the atom @var{Name}, but sharing +non-backtrackable terms. This may be useful if you want to rewrite a +global variable so that the new copy will survive backtracking, but +you want to share structure with the previous term. + +The next example shows the differences between the three built-ins: +@example +?- nb_setval(a,a(_)),nb_getval(a,A),nb_setval(b,t(C,A)),nb_getval(b,B). +A = a(_A), +B = t(_B,a(_C)) ? + +?- nb_setval(a,a(_)),nb_getval(a,A),nb_set_shared_val(b,t(C,A)),nb_getval(b,B). + +?- nb_setval(a,a(_)),nb_getval(a,A),nb_linkval(b,t(C,A)),nb_getval(b,B). +A = a(_A), +B = t(C,a(_A)) ? +@end example + +@item nb_setarg(+@{Arg], +@var{Term}, +@var{Value}) +@findex nb_setarg/3 +@snindex nb_setarg/3 +@cnindex nb_setarg/3 + +Assigns the @var{Arg}-th argument of the compound term @var{Term} with +the given @var{Value} as setarg/3, but on backtracking the assignment +is not reversed. If @var{Term} is not atomic, it is duplicated using +duplicate_term/2. This predicate uses the same technique as +@code{nb_setval/2}. We therefore refer to the description of +@code{nb_setval/2} for details on non-backtrackable assignment of +terms. This predicate is compatible to GNU-Prolog +@code{setarg(A,T,V,false)}, removing the type-restriction on +@var{Value}. See also @code{nb_linkarg/3}. Below is an example for +counting the number of solutions of a goal. Note that this +implementation is thread-safe, reentrant and capable of handling +exceptions. Realising these features with a traditional implementation +based on assert/retract or flag/3 is much more complicated. + +@example + succeeds_n_times(Goal, Times) :- + Counter = counter(0), + ( Goal, + arg(1, Counter, N0), + N is N0 + 1, + nb_setarg(1, Counter, N), + fail + ; arg(1, Counter, Times) + ). +@end example + +@item nb_set_shared_arg(+@var{Arg}, +@var{Term}, +@var{Value}) +@findex nb_set_shared_arg/3 +@snindex nb_set_shared_arg/3 +@cnindex nb_set_shared_arg/3 + +As @code{nb_setarg/3}, but like @code{nb_linkval/2} it does not +duplicate the global sub-terms in @var{Value}. Use with extreme care +and consult the documentation of @code{nb_linkval/2} before use. + +@item nb_linkarg(+@var{Arg}, +@var{Term}, +@var{Value}) +@findex nb_linkarg/3 +@snindex nb_lnkarg/3 +@cnindex nb_linkarg/3 + +As @code{nb_setarg/3}, but like @code{nb_linkval/2} it does not +duplicate @var{Value}. Use with extreme care and consult the +documentation of @code{nb_linkval/2} before use. + + +@item nb_current(?@var{Name}, ?@var{Value}) +@findex nb_current/2 +@snindex nb_current/2 +@cnindex nb_current/2 +Enumerate all defined variables with their value. The order of +enumeration is undefined. + +@item nb_delete(+@var{Name}) +@findex nb_delete/2 +@snindex nb_delete/2 +@cnindex nb_delete/2 +Delete the named global variable. +@end table + +Global variables have been introduced by various Prolog +implementations recently. We follow the implementation of them in +SWI-Prolog, itself based on hProlog by Bart Demoen. + +GNU-Prolog provides a rich set of global variables, including +arrays. Arrays can be implemented easily in YAP and SWI-Prolog using +@code{functor/3} and @code{setarg/3} due to the unrestricted arity of +compound terms. + + +@node Profiling, Call Counting, Global Variables, Top +@section Profiling Prolog Programs + +@cindex profiling + +YAP includes two profilers. The count profiler keeps information on the +number of times a predicate was called. This information can be used to +detect what are the most commonly called predicates in the program. The +count profiler can be compiled by setting YAP's flag @code{profiling} +to @code{on}. The time-profiler is a @code{gprof} profiler, and counts +how many ticks are being spent on specific predicates, or on other +system functions such as internal data-base accesses or garbage collects. + +The YAP profiling sub-system is currently under +development. Functionality for this sub-system will increase with newer +implementation. + +@subsection The Count Profiler + +@strong{Notes:} + +The count profiler works by incrementing counters at procedure entry or +backtracking. It provides exact information: + +@itemize @bullet +@item Profiling works for both static and dynamic predicates. +@item Currently only information on entries and retries to a predicate +are maintained. This may change in the future. +@item As an example, the following user-level program gives a list of +the most often called procedures in a program. The procedure +@code{list_profile} shows all procedures, irrespective of module, and +the procedure @code{list_profile/1} shows the procedures being used in +a specific module. +@example +list_profile :- + % get number of calls for each profiled procedure + setof(D-[M:P|D1],(current_module(M),profile_data(M:P,calls,D),profile_data(M:P,retries,D1)),LP), + % output so that the most often called + % predicates will come last: + write_profile_data(LP). + +list_profile(Module) :- + % get number of calls for each profiled procedure + setof(D-[Module:P|D1],(profile_data(Module:P,calls,D),profile_data(Module:P,retries,D1)),LP), + % output so that the most often called + % predicates will come last: + write_profile_data(LP). + +write_profile_data([]). +write_profile_data([D-[M:P|R]|SLP]) :- + % swap the two calls if you want the most often + % called predicates first. + format('~a:~w: ~32+~t~d~12+~t~d~12+~n', [M,P,D,R]), + write_profile_data(SLP). +@end example +@end itemize + +These are the current predicates to access and clear profiling data: + +@table @code +@item profile_data(?@var{Na/Ar}, ?@var{Parameter}, -@var{Data}) +@findex profile_data/3 +@snindex profile_data/3 +@cnindex profile_data/3 +Give current profile data on @var{Parameter} for a predicate described +by the predicate indicator @var{Na/Ar}. If any of @var{Na/Ar} or +@var{Parameter} are unbound, backtrack through all profiled predicates +or stored parameters. Current parameters are: + +@table @code +@item calls +Number of times a procedure was called. + +@item retries + Number of times a call to the procedure was backtracked to and retried. +@end table + +@item profile_reset +@findex profiled_reset/0 +@snindex profiled_reset/0 +@cnindex profiled_reset/0 +Reset all profiling information. + +@end table + +@subsection Tick Profiler +The tick profiler works by interrupting the Prolog code every so often +and checking at each point the code was. The profiler must be able to +retrace the state of the abstract machine at every moment. The major +advantage of this approach is that it gives the actual amount of time +being spent per procedure, or whether garbage collection dominates +execution time. The major drawback is that tracking down the state of +the abstract machine may take significant time, and in the worst case +may slow down the whole execution. + +The following procedures are available: + +@table @code +@item profinit +@findex profinit/0 +@snindex profinit/0 +@cnindex profinit/0 +Initialise the data-structures for the profiler. Unnecessary for +dynamic profiler. + +@item profon +@findex profon/0 +@snindex profon/0 +@cnindex profon/0 +Start profiling. + +@item profoff +@findex profoff/0 +@snindex profoff/0 +@cnindex profoff/0 +Stop profiling. + +@item showprofres +@findex showprofres/0 +@snindex showprofres/0 +@cnindex showprofres/0 +Show profiling info. + +@item showprofres(@var{N}) +@findex showprofres/1 +@snindex showprofres/1 +@cnindex showprofres/1 +Show profiling info for the top-most @var{N} predicates. + +@end table + +The @code{showprofres/0} and @code{showprofres/1} predicates call a user-defined multifile hook predicate, @code{user:prolog_predicate_name/2}, that can be used for converting a possibly explicitly-qualified callable term into an atom that will used when printing the profiling information. + +@node Call Counting, Arrays, Profiling, Top +@section Counting Calls + +@cindex Counting Calls +Predicates compiled with YAP's flag @code{call_counting} set to +@code{on} update counters on the numbers of calls and of +retries. Counters are actually decreasing counters, so that they can be +used as timers. Three counters are available: +@itemize @bullet +@item @code{calls}: number of predicate calls since execution started or since +system was reset; +@item @code{retries}: number of retries for predicates called since +execution started or since counters were reset; +@item @code{calls_and_retries}: count both on predicate calls and +retries. +@end itemize +These counters can be used to find out how many calls a certain +goal takes to execute. They can also be used as timers. + +The code for the call counters piggybacks on the profiling +code. Therefore, activating the call counters also activates the profiling +counters. + +These are the predicates that access and manipulate the call counters: + +@table @code +@item call_count_data(-@var{Calls}, -@var{Retries}, -@var{CallsAndRetries}) +@findex call_count_data/3 +@snindex call_count_data/3 +@cnindex call_count_data/3 +Give current call count data. The first argument gives the current value +for the @var{Calls} counter, next the @var{Retries} counter, and last +the @var{CallsAndRetries} counter. + +@item call_count_reset +@findex call_count_data/0 +@snindex call_count_data/0 +@cnindex call_count_data/0 +Reset call count counters. All timers are also reset. + +@item call_count(?@var{CallsMax}, ?@var{RetriesMax}, ?@var{CallsAndRetriesMax}) +@findex call_count_data/3 +@snindex call_count_data/3 +@cnindex call_count_data/3 +Set call count counter as timers. YAP will generate an exception +if one of the instantiated call counters decreases to 0. YAP will ignore +unbound arguments: +@itemize @bullet +@item @var{CallsMax}: throw the exception @code{call_counter} when the +counter @code{calls} reaches 0; +@item @var{RetriesMax}: throw the exception @code{retry_counter} when the +counter @code{retries} reaches 0; +@item @var{CallsAndRetriesMax}: throw the exception +@code{call_and_retry_counter} when the counter @code{calls_and_retries} +reaches 0. +@end itemize +@end table + +Next, we show a simple example of how to use call counters: +@example + ?- yap_flag(call_counting,on), [-user]. l :- l. end_of_file. yap_flag(call_counting,off). + +yes + +yes + ?- catch((call_count(10000,_,_),l),call_counter,format("limit_exceeded.~n",[])). + +limit_exceeded. + +yes +@end example +Notice that we first compile the looping predicate @code{l/0} with +@code{call_counting} @code{on}. Next, we @code{catch/3} to handle an +exception when @code{l/0} performs more than 10000 reductions. + + +@node Arrays, Preds, Call Counting , Top +@section Arrays + +The YAP system includes experimental support for arrays. The +support is enabled with the option @code{YAP_ARRAYS}. + +There are two very distinct forms of arrays in YAP. The +@emph{dynamic arrays} are a different way to access compound terms +created during the execution. Like any other terms, any bindings to +these terms and eventually the terms themselves will be destroyed during +backtracking. Our goal in supporting dynamic arrays is twofold. First, +they provide an alternative to the standard @code{arg/3} +built-in. Second, because dynamic arrays may have name that are globally +visible, a dynamic array can be visible from any point in the +program. In more detail, the clause +@example +g(X) :- array_element(a,2,X). +@end example +will succeed as long as the programmer has used the built-in @t{array/2} +to create an array term with at least 3 elements in the current +environment, and the array was associated with the name @code{a}. The +element @code{X} is a Prolog term, so one can bind it and any such +bindings will be undone when backtracking. Note that dynamic arrays do +not have a type: each element may be any Prolog term. + +The @emph{static arrays} are an extension of the database. They provide +a compact way for manipulating data-structures formed by characters, +integers, or floats imperatively. They can also be used to provide +two-way communication between YAP and external programs through +shared memory. + +In order to efficiently manage space elements in a static array must +have a type. Currently, elements of static arrays in YAP should +have one of the following predefined types: + +@itemize @bullet +@item @code{byte}: an 8-bit signed character. +@item @code{unsigned_byte}: an 8-bit unsigned character. +@item @code{int}: Prolog integers. Size would be the natural size for +the machine's architecture. +@item @code{float}: Prolog floating point number. Size would be equivalent +to a double in @code{C}. +@item @code{atom}: a Prolog atom. +@item @code{dbref}: an internal database reference. +@item @code{term}: a generic Prolog term. Note that this will term will +not be stored in the array itself, but instead will be stored in the +Prolog internal database. +@end itemize + +Arrays may be @emph{named} or @emph{anonymous}. Most arrays will be +@emph{named}, that is associated with an atom that will be used to find +the array. Anonymous arrays do not have a name, and they are only of +interest if the @code{TERM_EXTENSIONS} compilation flag is enabled. In +this case, the unification and parser are extended to replace +occurrences of Prolog terms of the form @code{X[I]} by run-time calls to +@code{array_element/3}, so that one can use array references instead of +extra calls to @code{arg/3}. As an example: +@example +g(X,Y,Z,I,J) :- X[I] is Y[J]+Z[I]. +@end example +should give the same results as: +@example +G(X,Y,Z,I,J) :- + array_element(X,I,E1), + array_element(Y,J,E2), + array_element(Z,I,E3), + E1 is E2+E3. +@end example + +Note that the only limitation on array size are the stack size for +dynamic arrays; and, the heap size for static (not memory mapped) +arrays. Memory mapped arrays are limited by available space in the file +system and in the virtual memory space. + +The following predicates manipulate arrays: + +@table @code + +@item array(+@var{Name}, +@var{Size}) +@findex array/2 +@snindex array/2 +@cnindex array/2 +Creates a new dynamic array. The @var{Size} must evaluate to an +integer. The @var{Name} may be either an atom (named array) or an +unbound variable (anonymous array). + +Dynamic arrays work as standard compound terms, hence space for the +array is recovered automatically on backtracking. + +@item static_array(+@var{Name}, +@var{Size}, +@var{Type}) +@findex static_array/3 +@snindex static_array/3 +@cnindex static_array/3 +Create a new static array with name @var{Name}. Note that the @var{Name} +must be an atom (named array). The @var{Size} must evaluate to an +integer. The @var{Type} must be bound to one of types mentioned +previously. + +@item reset_static_array(+@var{Name}) +@findex reset_static_array/1 +@snindex reset_static_array/1 +@cnindex reset_static_array/1 +Reset static array with name @var{Name} to its initial value. + +@item static_array_location(+@var{Name}, -@var{Ptr}) +@findex static_array_location/4 +@snindex static_array_location/4 +@cnindex static_array_location/4 +Give the location for a static array with name +@var{Name}. + +@item static_array_properties(?@var{Name}, ?@var{Size}, ?@var{Type}) +@findex static_array_properties/3 +@snindex static_array_properties/3 +@cnindex static_array_properties/3 +Show the properties size and type of a static array with name +@var{Name}. Can also be used to enumerate all current +static arrays. + +This built-in will silently fail if the there is no static array with +that name. + +@item static_array_to_term(?@var{Name}, ?@var{Term}) +@findex static_array_to_term/3 +@snindex static_array_to_term/3 +@cnindex static_array_to_term/3 +Convert a static array with name +@var{Name} to a compound term of name @var{Name}. + +This built-in will silently fail if the there is no static array with +that name. + +@item mmapped_array(+@var{Name}, +@var{Size}, +@var{Type}, +@var{File}) +@findex static_array/3 +@snindex static_array/3 +@cnindex static_array/3 +Similar to @code{static_array/3}, but the array is memory mapped to file +@var{File}. This means that the array is initialized from the file, and +that any changes to the array will also be stored in the file. + +This built-in is only available in operating systems that support the +system call @code{mmap}. Moreover, mmapped arrays do not store generic +terms (type @code{term}). + +@item close_static_array(+@var{Name}) +@findex close_static_array/1 +@snindex close_static_array/1 +@cnindex close_static_array/1 +Close an existing static array of name @var{Name}. The @var{Name} must +be an atom (named array). Space for the array will be recovered and +further accesses to the array will return an error. + +@item resize_static_array(+@var{Name}, -@var{OldSize}, +@var{NewSize}) +@findex resize_static_array/3 +@snindex resize_static_array/3 +@cnindex resize_static_array/3 +Expand or reduce a static array, The @var{Size} must evaluate to an +integer. The @var{Name} must be an atom (named array). The @var{Type} +must be bound to one of @code{int}, @code{dbref}, @code{float} or +@code{atom}. + +Note that if the array is a mmapped array the size of the mmapped file +will be actually adjusted to correspond to the size of the array. + +@item array_element(+@var{Name}, +@var{Index}, ?@var{Element}) +@findex array_element/3 +@snindex array_element/3 +@cnindex array_element/3 +Unify @var{Element} with @var{Name}[@var{Index}]. It works for both +static and dynamic arrays, but it is read-only for static arrays, while +it can be used to unify with an element of a dynamic array. + +@item update_array(+@var{Name}, +@var{Index}, ?@var{Value}) +@findex update_array/3 +@snindex update_array/3 +@cnindex update_array/3 +Attribute value @var{Value} to @var{Name}[@var{Index}]. Type +restrictions must be respected for static arrays. This operation is +available for dynamic arrays if @code{MULTI_ASSIGNMENT_VARIABLES} is +enabled (true by default). Backtracking undoes @var{update_array/3} for +dynamic arrays, but not for static arrays. + +Note that @code{update_array/3} actually uses @code{setarg/3} to update +elements of dynamic arrays, and @code{setarg/3} spends an extra cell for +every update. For intensive operations we suggest it may be less +expensive to unify each element of the array with a mutable terms and +to use the operations on mutable terms. + +@item add_to_array_element(+@var{Name}, +@var{Index}, , +@var{Number}, ?@var{NewValue}) +@findex add_to_array_element/4 +@snindex add_to_array_element/4 +@cnindex add_to_array_element/4 +Add @var{Number} @var{Name}[@var{Index}] and unify @var{NewValue} with +the incremented value. Observe that @var{Name}[@var{Index}] must be an +number. If @var{Name} is a static array the type of the array must be +@code{int} or @code{float}. If the type of the array is @code{int} you +only may add integers, if it is @code{float} you may add integers or +floats. If @var{Name} corresponds to a dynamic array the array element +must have been previously bound to a number and @code{Number} can be +any kind of number. + +The @code{add_to_array_element/3} built-in actually uses +@code{setarg/3} to update elements of dynamic arrays. For intensive +operations we suggest it may be less expensive to unify each element +of the array with a mutable terms and to use the operations on mutable +terms. + +@end table + +@node Preds, Misc, Arrays, Top +@section Predicate Information + +Built-ins that return information on the current predicates and modules: + +@table @code +@c ......... begin of 'module' documentation ......... +@item current_module(@var{M}) +@findex current_module/1 +@syindex current_module/1 +@cnindex current_module/1 +Succeeds if @var{M} are defined modules. A module is defined as soon as some +predicate defined in the module is loaded, as soon as a goal in the +module is called, or as soon as it becomes the current type-in module. + +@item current_module(@var{M},@var{F}) +@findex current_module/2 +@syindex current_module/2 +@cnindex current_module/2 +Succeeds if @var{M} are current modules associated to the file @var{F}. + +@c .......... end of 'module' documentation .......... +@end table + +@node Misc, , Preds, Top +@section Miscellaneous + +@table @code + +@item statistics/0 +@findex statistics/0 +@saindex statistics/0 +@cyindex statistics/0 +Send to the current user error stream general information on space used and time +spent by the system. +@example +?- statistics. +memory (total) 4784124 bytes + program space 3055616 bytes: 1392224 in use, 1663392 free + 2228132 max + stack space 1531904 bytes: 464 in use, 1531440 free + global stack: 96 in use, 616684 max + local stack: 368 in use, 546208 max + trail stack 196604 bytes: 8 in use, 196596 free + + 0.010 sec. for 5 code, 2 stack, and 1 trail space overflows + 0.130 sec. for 3 garbage collections which collected 421000 bytes + 0.000 sec. for 0 atom garbage collections which collected 0 bytes + 0.880 sec. runtime + 1.020 sec. cputime + 25.055 sec. elapsed time + +@end example +The example shows how much memory the system spends. Memory is divided +into Program Space, Stack Space and Trail. In the example we have 3MB +allocated for program spaces, with less than half being actually +used. YAP also shows the maximum amount of heap space having been used +which was over 2MB. + +The stack space is divided into two stacks which grow against each +other. We are in the top level so very little stack is being used. On +the other hand, the system did use a lot of global and local stack +during the previous execution (we refer the reader to a WAM tutorial in +order to understand what are the global and local stacks). + +YAP also shows information on how many memory overflows and garbage +collections the system executed, and statistics on total execution +time. Cputime includes all running time, runtime excludes garbage +collection and stack overflow time. + +@item statistics(?@var{Param},-@var{Info}) +@findex statistics/2 +@saindex statistics/2 +@cnindex statistics/2 +Gives statistical information on the system parameter given by first +argument: + +@table @code + +@item atoms +@findex atoms (statistics/2 option) +@code{[@var{NumberOfAtoms},@var{SpaceUsedBy Atoms}]} +@* +This gives the total number of atoms @code{NumberOfAtoms} and how much +space they require in bytes, @var{SpaceUsedBy Atoms}. + +@item cputime +@findex cputime (statistics/2 option) +@code{[@var{Time since Boot},@var{Time From Last Call to Cputime}]} +@* +This gives the total cputime in milliseconds spent executing Prolog code, +garbage collection and stack shifts time included. + +@item dynamic_code +@findex dynamic_code (statistics/2 option) +@code{[@var{Clause Size},@var{Index Size},@var{Tree Index +Size},@var{Choice Point Instructions +Size},@var{Expansion Nodes Size},@var{Index Switch Size}]} +@* +Size of static code in YAP in bytes: @var{Clause Size}, the number of +bytes allocated for clauses, plus +@var{Index Size}, the number of bytes spent in the indexing code. The +indexing code is divided into main tree, @var{Tree Index +Size}, tables that implement choice-point manipulation, @var{Choice Point Instructions +Size}, tables that cache clauses for future expansion of the index +tree, @var{Expansion Nodes Size}, and +tables such as hash tables that select according to value, @var{Index Switch Size}. + +@item garbage_collection +@findex garbage_collection (statistics/2 option) +@code{[@var{Number of GCs},@var{Total Global Recovered},@var{Total Time +Spent}]} +@* +Number of garbage collections, amount of space recovered in kbytes, and +total time spent doing garbage collection in milliseconds. More detailed +information is available using @code{yap_flag(gc_trace,verbose)}. + +@item global_stack +@findex global_stack (statistics/2 option) +@code{[@var{Global Stack Used},@var{Execution Stack Free}]} +@* +Space in kbytes currently used in the global stack, and space available for +expansion by the local and global stacks. + +@item local_stack +@findex local_stack (statistics/2 option) +@code{[@var{Local Stack Used},@var{Execution Stack Free}]} +@* +Space in kbytes currently used in the local stack, and space available for +expansion by the local and global stacks. + +@item heap +@findex heap (statistics/2 option) +@code{[@var{Heap Used},@var{Heap Free}]} +@* +Total space in kbytes not recoverable +in backtracking. It includes the program code, internal data base, and, +atom symbol table. + +@item program +@findex program (statistics/2 option) +@code{[@var{Program Space Used},@var{Program Space Free}]} +@* +Equivalent to @code{heap}. + +@item runtime +@findex runtime (statistics/2 option) +@code{[@var{Time since Boot},@var{Time From Last Call to Runtime}]} +@* +This gives the total cputime in milliseconds spent executing Prolog +code, not including garbage collections and stack shifts. Note that +until YAP4.1.2 the @code{runtime} statistics would return time spent on +garbage collection and stack shifting. + +@item stack_shifts +@findex stack_shifts (statistics/2 option) +@code{[@var{Number of Heap Shifts},@var{Number of Stack +Shifts},@var{Number of Trail Shifts}]} +@* +Number of times YAP had to +expand the heap, the stacks, or the trail. More detailed information is +available using @code{yap_flag(gc_trace,verbose)}. + +@item static_code +@findex static_code (statistics/2 option) +@code{[@var{Clause Size},@var{Index Size},@var{Tree Index +Size},@var{Expansion Nodes Size},@var{Index Switch Size}]} +@* +Size of static code in YAP in bytes: @var{Clause Size}, the number of +bytes allocated for clauses, plus +@var{Index Size}, the number of bytes spent in the indexing code. The +indexing code is divided into a main tree, @var{Tree Index +Size}, table that cache clauses for future expansion of the index +tree, @var{Expansion Nodes Size}, and and +tables such as hash tables that select according to value, @var{Index Switch Size}. + +@item trail +@findex trail (statistics/2 option) +@code{[@var{Trail Used},@var{Trail Free}]} +@* +Space in kbytes currently being used and still available for the trail. + +@item walltime +@findex walltime (statistics/2 option) +@code{[@var{Time since Boot},@var{Time From Last Call to Walltime}]} +@* +This gives the clock time in milliseconds since starting Prolog. + +@end table + +@item time(:@var{Goal}) +@findex time/1 +@snindex time/1 +@cnindex time/1 +Prints the CPU time and the wall time for the execution of @var{Goal}. +Possible choice-points of @var{Goal} are removed. Based on the SWI-Prolog +definition (minus reporting the number of inferences, which YAP currently +does not support). + +@item yap_flag(?@var{Param},?@var{Value}) +@findex yap_flag/2 +@snindex yap_flag/2 +@cnindex yap_flag/2 +Set or read system properties for @var{Param}: + +@table @code + +@item argv +@findex argv (yap_flag/2 option) +@* Read-only flag. It unifies with a list of atoms that gives the +arguments to YAP after @code{--}. + +@item agc_margin +@findex agc_margin (yap_flag/2 option) +An integer: if this amount of atoms has been created since the last +atom-garbage collection, perform atom garbage collection at the first +opportunity. Initial value is 10,000. May be changed. A value of 0 +(zero) disables atom garbage collection. + +@item associate +@findex associate (yap_flag/2 option) +@* +Read-write flag telling a suffix for files associated to Prolog +sources. It is @code{yap} by default. + +@item bounded [ISO] +@findex bounded (yap_flag/2 option) +@* +Read-only flag telling whether integers are bounded. The value depends +on whether YAP uses the GMP library or not. + +@item profiling +@findex call_counting (yap_flag/2 option) +@* +If @code{off} (default) do not compile call counting information for +procedures. If @code{on} compile predicates so that they calls and +retries to the predicate may be counted. Profiling data can be read through the +@code{call_count_data/3} built-in. + +@item char_conversion [ISO] +@findex char_conversion (yap_flag/2 option) +@* +Writable flag telling whether a character conversion table is used when +reading terms. The default value for this flag is @code{off} except in +@code{sicstus} and @code{iso} language modes, where it is @code{on}. + +@item character_escapes [ISO] +@findex character_escapes (yap_flag/2 option) +@* Writable flag telling whether a character escapes are enables, +@code{true}, or disabled, @code{false}. The default value for this flag is +@code{on}. + +@c You can also use @code{cprolog} mode, which corresponds to @code{off}, +@c @code{iso} mode, which corresponds to @code{on}, and @code{sicstus} +@c mode, which corresponds to the mode traditionally used in SICStus +@c Prolog. In this mode back-quoted escape sequences should not close with +@c a backquote and unrecognized escape codes do not result in error. + +@item debug [ISO] +@findex debug (yap_flag/2 option) +@* +If @var{Value} is unbound, tell whether debugging is @code{true} or +@code{false}. If @var{Value} is bound to @code{true} enable debugging, and if +it is bound to @code{false} disable debugging. + +@item debugger_print_options +@findex debugger_print_options (yap_flag/2 option) +@* +If bound, set the argument to the @code{write_term/3} options the +debugger uses to write terms. If unbound, show the current options. + +@item dialect +@findex dialect (yap_flag/2 option) +@* +Read-only flag that always returns @code{yap}. + +@item discontiguous_warnings +@findex discontiguous_warnings (yap_flag/2 option) +@* +If @var{Value} is unbound, tell whether warnings for discontiguous +predicates are @code{on} or +@code{off}. If @var{Value} is bound to @code{on} enable these warnings, +and if it is bound to @code{off} disable them. The default for YAP is +@code{off}, unless we are in @code{sicstus} or @code{iso} mode. + +@item dollar_as_lower_case +@findex dollar_as_lower_case (yap_flag/2 option) +@* +If @code{off} (default) consider the character '$' a control character, if +@code{on} consider '$' a lower case character. + +@item double_quotes [ISO] +@findex double_quotes (yap_flag/2 option) +@* +If @var{Value} is unbound, tell whether a double quoted list of characters +token is converted to a list of atoms, @code{chars}, to a list of integers, +@code{codes}, or to a single atom, @code{atom}. If @var{Value} is bound, set to +the corresponding behavior. The default value is @code{codes}. + +@item executable +@findex executable (yap_flag/2 option) +@* Read-only flag. It unifies with an atom that gives the +original program path. + +@item fast +@findex fast (yap_flag/2 option) +@* +If @code{on} allow fast machine code, if @code{off} (default) disable it. Only +available in experimental implementations. + +@item fileerrors +@findex fileerrors (yap_flag/2 option) +@* +If @code{on} @code{fileerrors} is @code{on}, if @code{off} (default) +@code{fileerrors} is disabled. + +@item float_format +@findex float_format (yap_flag/2 option) +@* C-library @code{printf()} format specification used by @code{write/1} and +friends to determine how floating point numbers are printed. The +default is @code{%.15g}. The specified value is passed to @code{printf()} +without further checking. For example, if you want less digits +printed, @code{%g} will print all floats using 6 digits instead of the +default 15. + +@item gc +@findex gc (yap_flag/2 option) +@* +If @code{on} allow garbage collection (default), if @code{off} disable it. + +@item gc_margin +@findex gc_margin (yap_flag/2 option) +@* +Set or show the minimum free stack before starting garbage +collection. The default depends on total stack size. + +@item gc_trace +@findex gc_trace (yap_flag/2 option) +@* If @code{off} (default) do not show information on garbage collection +and stack shifts, if @code{on} inform when a garbage collection or stack +shift happened, if @code{verbose} give detailed information on garbage +collection and stack shifts. Last, if @code{very_verbose} give detailed +information on data-structures found during the garbage collection +process, namely, on choice-points. + +@item generate_debugging_info +@findex generate_debugging_info (yap_flag/2 option) +@* If @code{true} (default) generate debugging information for +procedures, including source mode. If @code{false} predicates no +information is generated, although debugging is still possible, and +source mode is disabled. + +@item host_type +@findex host_type (yap_flag/2 option) +@* Return @code{configure} system information, including the machine-id +for which YAP was compiled and Operating System information. + +@item index +@findex index (yap_flag/2 option) +@* If @code{on} allow indexing (default), if @code{off} disable it, if +@code{single} allow on first argument only. + +@item index_sub_term_search_depth +@findex index (yap_flag/2 option) +@* +Maximum bound on searching sub-terms for indexing, if @code{0} (default) no bound. + +@item informational_messages +@findex informational_messages (yap_flag/2 option) +@* +If @code{on} allow printing of informational messages, such as the ones +that are printed when consulting. If @code{off} disable printing +these messages. It is @code{on} by default except if YAP is booted with +the @code{-L} flag. + +@item integer_rounding_function [ISO] +@findex integer_rounding_function (yap_flag/2 option) +@* +Read-only flag telling the rounding function used for integers. Takes the value +@code{toward_zero} for the current version of YAP. + +@item language +@findex language (yap_flag/2 option) +@* +Choose whether YAP is closer to C-Prolog, @code{cprolog}, iso-prolog, +@code{iso} or SICStus Prolog, @code{sicstus}. The current default is +@code{cprolog}. This flag affects update semantics, leashing mode, +style checking, handling calls to undefined procedures, how directives +are interpreted, when to use dynamic, character escapes, and how files +are consulted. + +@item max_arity [ISO] +@findex max_arity (yap_flag/2 option) +@* +Read-only flag telling the maximum arity of a functor. Takes the value +@code{unbounded} for the current version of YAP. + +@item max_integer [ISO] +@findex max_integer (yap_flag/2 option) +@* +Read-only flag telling the maximum integer in the +implementation. Depends on machine and Operating System +architecture, and on whether YAP uses the @code{GMP} multi-precision +library. If @code{bounded} is false, requests for @code{max_integer} +will fail. + +@item max_tagged_integer +@findex max_tagged_integer (yap_flag/2 option) +@* +Read-only flag telling the maximum integer we can store as a single +word. Depends on machine and Operating System +architecture. It can be used to find the word size of the current machine. + +@item min_integer [ISO] +@findex min_integer (yap_flag/2 option) +@* Read-only flag telling the minimum integer in the +implementation. Depends on machine and Operating System architecture, +and on whether YAP uses the @code{GMP} multi-precision library. If +@code{bounded} is false, requests for @code{min_integer} will fail. + +@item min_tagged_integer +@findex max_tagged_integer (yap_flag/2 option) +@* +Read-only flag telling the minimum integer we can store as a single +word. Depends on machine and Operating System +architecture. + +@item n_of_integer_keys_in_bb +@findex n_of_integer_keys_in_bb (yap_flag/2 option) +@* +Read or set the size of the hash table that is used for looking up the +blackboard when the key is an integer. + +@item occurs_check +@findex occurs_check (yap_flag/2 option) +@* +Current read-only and set to @code{false}. + +@item n_of_integer_keys_in_db +@findex n_of_integer_keys_in_db (yap_flag/2 option) +@* +Read or set the size of the hash table that is used for looking up the +internal data-base when the key is an integer. + +@item open_expands_filename +@findex open_expands_filename (yap_flag/2 option) +@* +If @code{true} the @code{open/3} builtin performs filename-expansion +before opening a file (SICStus Prolog like). If @code{false} it does not +(SWI-Prolog like). + +@item open_shared_object +@findex open_shared_object (yap_flag/2 option) +@* +If true, @code{open_shared_object/2} and friends are implemented, +providing access to shared libraries (@code{.so} files) or to dynamic link +libraries (@code{.DLL} files). + +@item profiling +@findex profiling (yap_flag/2 option) +@* +If @code{off} (default) do not compile profiling information for +procedures. If @code{on} compile predicates so that they will output +profiling information. Profiling data can be read through the +@code{profile_data/3} built-in. + +@item prompt_alternatives_on(atom, changeable) +@findex prompt_alternatives_on (yap_flag/2 option) +SWI-Compatible option, determines prompting for alternatives in the Prolog toplevel. Default is @t{groundness}, YAP prompts for alternatives if and only if the query contains variables. The alternative, default in SWI-Prolog is @t{determinism} which implies the system prompts for alternatives if the goal succeeded while leaving choicepoints. + + +@item redefine_warnings +@findex discontiguous_warnings (yap_flag/2 option) +@* +If @var{Value} is unbound, tell whether warnings for procedures defined +in several different files are @code{on} or +@code{off}. If @var{Value} is bound to @code{on} enable these warnings, +and if it is bound to @code{off} disable them. The default for YAP is +@code{off}, unless we are in @code{sicstus} or @code{iso} mode. + +@item shared_object_search_path +@findex shared_object_search_path (yap_flag/2 option) +Name of the environment variable used by the system to search for shared +objects. + +@item shared_object_extension +@findex shared_object_extension (yap_flag/2 option) +Suffix associated with loadable code. + +@item single_var_warnings +@findex single_var_warnings (yap_flag/2 option) +@* +If @var{Value} is unbound, tell whether warnings for singleton variables +are @code{on} or @code{off}. If @var{Value} is bound to @code{on} enable +these warnings, and if it is bound to @code{off} disable them. The +default for YAP is @code{off}, unless we are in @code{sicstus} or +@code{iso} mode. + +@item strict_iso +@findex strict_iso (yap_flag/2 option) +@* + If @var{Value} is unbound, tell whether strict ISO compatibility mode +is @code{on} or @code{off}. If @var{Value} is bound to @code{on} set +language mode to @code{iso} and enable strict mode. If @var{Value} is +bound to @code{off} disable strict mode, and keep the current language +mode. The default for YAP is @code{off}. + +Under strict ISO Prolog mode all calls to non-ISO built-ins generate an +error. Compilation of clauses that would call non-ISO built-ins will +also generate errors. Pre-processing for grammar rules is also +disabled. Module expansion is still performed. + +Arguably, ISO Prolog does not provide all the functionality required +from a modern Prolog system. Moreover, because most Prolog +implementations do not fully implement the standard and because the +standard itself gives the implementor latitude in a few important +questions, such as the unification algorithm and maximum size for +numbers there is no guarantee that programs compliant with this mode +will work the same way in every Prolog and in every platform. We thus +believe this mode is mostly useful when investigating how a program +depends on a Prolog's platform specific features. + +@item stack_dump_on_error +@findex stack_dump_on_error (yap_flag/2 option) +@* +If @code{on} show a stack dump when YAP finds an error. The default is +@code{off}. + +@item syntax_errors +@findex syntax_errors (yap_flag/2 option) +@* +Control action to be taken after syntax errors while executing @code{read/1}, +@code{read/2}, or @code{read_term/3}: +@table @code + +@item dec10 +@* +Report the syntax error and retry reading the term. + +@item fail +@* +Report the syntax error and fail (default). + +@item error +@* +Report the syntax error and generate an error. + +@item quiet +@* +Just fail +@end table + +@item system_options +@findex system_options (yap_flag/2 option) +@* This read only flag tells which options were used to compile +YAP. Currently it informs whether the system supports @code{big_numbers}, +@code{coroutining}, @code{depth_limit}, @code{low_level_tracer}, +@code{or-parallelism}, @code{rational_trees}, @code{readline}, @code{tabling}, +@code{threads}, or the @code{wam_profiler}. + +@item tabling_mode +@* Sets or reads the tabling mode for all tabled predicates. Please +@pxref{Tabling} for the list of options. + +@item to_chars_mode +@findex to_chars_modes (yap_flag/2 option) +@* Define whether YAP should follow @code{quintus}-like +semantics for the @code{atom_chars/1} or @code{number_chars/1} built-in, +or whether it should follow the ISO standard (@code{iso} option). + +@item toplevel_hook +@findex toplevel_hook (yap_flag/2 option) +@* ++If bound, set the argument to a goal to be executed before entering the +top-level. If unbound show the current goal or @code{true} if none is +presented. Only the first solution is considered and the goal is not +backtracked into. + +@item toplevel_print_options +@findex toplevel_print_options (yap_flag/2 option) +@* ++If bound, set the argument to the @code{write_term/3} options used to write +terms from the top-level. If unbound, show the current options. + +@item typein_module +@findex typein_module (yap_flag/2 option) +@* +If bound, set the current working or type-in module to the argument, +which must be an atom. If unbound, unify the argument with the current +working module. + +@item unix +@findex unix (yap_flag/2 option) +@* Read-only Boolean flag that unifies with @code{true} if YAP is +running on an Unix system. Defined if the C-compiler used to compile +this version of YAP either defines @code{__unix__} or @code{unix}. + +@item unknown [ISO] +@findex unknown (yap_flag/2 option) +@* +Corresponds to calling the @code{unknown/2} built-in. Possible values +are @code{error}, @code{fail}, and @code{warning}. + +@item update_semantics +@findex update_semantics (yap_flag/2 option) +@* +Define whether YAP should follow @code{immediate} update +semantics, as in C-Prolog (default), @code{logical} update semantics, +as in Quintus Prolog, SICStus Prolog, or in the ISO standard. There is +also an intermediate mode, @code{logical_assert}, where dynamic +procedures follow logical semantics but the internal data base still +follows immediate semantics. + +@item user_error +@findex user_error (yap_flag/2 option) +@* +If the second argument is bound to a stream, set @code{user_error} to +this stream. If the second argument is unbound, unify the argument with +the current @code{user_error} stream. + +By default, the @code{user_error} stream is set to a stream +corresponding to the Unix @code{stderr} stream. + +The next example shows how to use this flag: +@example + ?- open( '/dev/null', append, Error, + [alias(mauri_tripa)] ). + +Error = '$stream'(3) ? ; + +no + ?- set_prolog_flag(user_error, mauri_tripa). + +close(mauri_tripa). + +yes + ?- +@end example +We execute three commands. First, we open a stream in write mode and +give it an alias, in this case @code{mauri_tripa}. Next, we set +@code{user_error} to the stream via the alias. Note that after we did so +prompts from the system were redirected to the stream +@code{mauri_tripa}. Last, we close the stream. At this point, YAP +automatically redirects the @code{user_error} alias to the original +@code{stderr}. + +@item user_flags +@findex user_flags (yap_flag/2 option) +@* +Define the behaviour of @code{set_prolog_flag/2} if the flag is not known. Values are @code{silent}, @code{warning} and @code{error}. The first two create the flag on-the-fly, with @code{warning} printing a message. The value @code{error} is consistent with ISO: it raises an existence error and does not create the flag. See also @code{create_prolog_flag/3}. The default is@code{error}, and developers are encouraged to use @code{create_prolog_flag/3} to create flags for their library. + +@item user_input +@findex user_input (yap_flag/2 option) +@* +If the second argument is bound to a stream, set @code{user_input} to +this stream. If the second argument is unbound, unify the argument with +the current @code{user_input} stream. + +By default, the @code{user_input} stream is set to a stream +corresponding to the Unix @code{stdin} stream. + +@item user_output +@findex user_output (yap_flag/2 option) +@* +If the second argument is bound to a stream, set @code{user_output} to +this stream. If the second argument is unbound, unify the argument with +the current @code{user_output} stream. + +By default, the @code{user_output} stream is set to a stream +corresponding to the Unix @code{stdout} stream. + +@item verbose +@findex verbose (yap_flag/2 option) +@* +If @code{normal} allow printing of informational and banner messages, +such as the ones that are printed when consulting. If @code{silent} +disable printing these messages. It is @code{normal} by default except if +YAP is booted with the @code{-q} or @code{-L} flag. + +@item verbose_load +@findex verbose_load (yap_flag/2 option) +@* If @code{true} allow printing of informational messages when +consulting files. If @code{false} disable printing these messages. It +is @code{normal} by default except if YAP is booted with the @code{-L} +flag. + +@item verbose_load +@findex verbose_load (yap_flag/2 option) +@* If @code{true} allow printing of informational messages when +consulting files. If @code{false} disable printing these messages. It +is @code{normal} by default except if YAP is booted with the @code{-L} +flag. + +@item version +@findex version (yap_flag/2 option) +@* Read-only flag that returns an atom with the current version of +YAP. + +@item version_data +@findex version_data (yap_flag/2 option) +@* Read-only flag that reads a term of the form +@code{yap}(@var{Major},@var{Minor},@var{Patch},@var{Undefined}), where +@var{Major} is the major version, @var{Minor} is the minor version, +and @var{Patch} is the patch number. + +@item windows +@findex windoes (yap_flag/2 option) +@* +Read-only boolean flag that unifies with tr @code{true} if YAP is +running on an Windows machine. + +@item write_strings +@findex write_strings (yap_flag/2 option) +@* Writable flag telling whether the system should write lists of +integers that are writable character codes using the list notation. It +is @code{on} if enables or @code{off} if disabled. The default value for +this flag is @code{off}. + +@item max_workers +@findex max_workers (yap_flag/2 option) +@* Read-only flag telling the maximum number of parallel processes. + +@item max_threads +@findex max_threads (yap_flag/2 option) +@* Read-only flag telling the maximum number of Prolog threads that can +be created. + +@end table + +@item current_prolog_flag(?@var{Flag},-@var{Value}) [ISO] +@findex current_prolog_flag/2 +@snindex current_prolog_flag/2 +@cnindex current_prolog_flag/2 + +Obtain the value for a YAP Prolog flag. Equivalent to calling +@code{yap_flag/2} with the second argument unbound, and unifying the +returned second argument with @var{Value}. + +@item prolog_flag(?@var{Flag},-@var{OldValue},+@var{NewValue}) +@findex prolog_flag/3 +@syindex prolog_flag/3 +@cnindex prolog_flag/3 + +Obtain the value for a YAP Prolog flag and then set it to a new +value. Equivalent to first calling @code{current_prolog_flag/2} with the +second argument @var{OldValue} unbound and then calling +@code{set_prolog_flag/2} with the third argument @var{NewValue}. + +@item set_prolog_flag(+@var{Flag},+@var{Value}) [ISO] +@findex set_prolog_flag/2 +@snindex set_prolog_flag/2 +@cnindex set_prolog_flag/2 + +Set the value for YAP Prolog flag @code{Flag}. Equivalent to +calling @code{yap_flag/2} with both arguments bound. + + +@item create_prolog_flag(+@var{Flag},+@var{Value},+@var{Options}) +@findex create_prolog_flag/2 +@snindex create_prolog_flag/2 +@cnindex create_prolog_flag/2 + +Create a new YAP Prolog flag. @var{Options} include @code{type(+Type)} and @code{access(+Access)} with @var{Access} +one of @code{read_only} or @code{read_write} and @var{Type} one of @code{boolean}, @code{integer}, @code{float}, @code{atom} +and @code{term} (that is, no type). + +@item op(+@var{P},+@var{T},+@var{A}) [ISO] +@findex op/3 +@syindex op/3 +@cyindex op/3 +Defines the operator @var{A} or the list of operators @var{A} with type +@var{T} (which must be one of @code{xfx}, @code{xfy},@code{yfx}, +@code{xf}, @code{yf}, @code{fx} or @code{fy}) and precedence @var{P} +(see appendix iv for a list of predefined operators). + +Note that if there is a preexisting operator with the same name and +type, this operator will be discarded. Also, @code{','} may not be defined +as an operator, and it is not allowed to have the same for an infix and +a postfix operator. + +@item current_op(@var{P},@var{T},@var{F}) [ISO] +@findex current_op/3 +@syindex current_op/3 +@cnindex current_op/3 +Defines the relation: @var{P} is a currently defined operator of type +@var{T} and precedence @var{P}. + +@item prompt(-@var{A},+@var{B}) +@findex prompt/2 +@syindex prompt/2 +@cyindex prompt/2 +Changes YAP input prompt from @var{A} to @var{B}. + +@item initialization +@findex initialization/0 +@syindex initialization/0 +@cnindex initialization/0 +Execute the goals defined by initialization/1. Only the first answer is +considered. + +@item prolog_initialization(@var{G}) +@findex prolog_initialization/1 +@saindex prolog_initialization/1 +@cnindex prolog_initialization/1 +Add a goal to be executed on system initialization. This is compatible +with SICStus Prolog's @code{initialization/1}. + +@item version +@findex version/0 +@saindex version/0 +@cnindex version/0 +Write YAP's boot message. + +@item version(-@var{Message}) +@findex version/1 +@syindex version/1 +@cnindex version/1 +Add a message to be written when yap boots or after aborting. It is not +possible to remove messages. + +@item prolog_load_context(?@var{Key}, ?@var{Value}) +@findex prolog_load_context/2 +@syindex prolog_load_context/2 +@cnindex prolog_load_context/2 +Obtain information on what is going on in the compilation process. The +following keys are available: + +@table @code + +@item directory +@findex directory (prolog_load_context/2 option) +@* +Full name for the directory where YAP is currently consulting the +file. + +@item file +@findex file (prolog_load_context/2 option) +@* +Full name for the file currently being consulted. Notice that included +filed are ignored. + +@item module +@findex module (prolog_load_context/2 option) +@* +Current source module. + +@item source +@findex file (prolog_load_context/2 option) +@* +Full name for the file currently being read in, which may be consulted, +reconsulted, or included. + +@item stream +@findex file (prolog_load_context/2 option) +@* +Stream currently being read in. + +@item term_position +@findex file (prolog_load_context/2 option) +@* +Stream position at the stream currently being read in. For SWI +compatibility, it is a term of the form +@code{'$stream_position'(0,Line,0,0,0)}. +@end table + +@item source_location(?@var{FileName}, ?@var{Line}) +@findex source_location/2 +@syindex source_location/2 +@cnindex source_location/2 +SWI-compatible predicate. If the last term has been read from a physical file (i.e., not from the file user or a string), unify File with an absolute path to the file and Line with the line-number in the file. Please use @code{prolog_load_context/2}. + +@item source_file(?@var{File}) +@findex source_file/1 +@syindex source_file/1 +@cnindex source_file/1 +SWI-compatible predicate. True if @var{File} is a loaded Prolog source file. + +@item source_file(?@var{ModuleAndPred},?@var{File}) +@findex source_file/2 +@syindex source_file/2 +@cnindex source_file/2 +SWI-compatible predicate. True if the predicate specified by @var{ModuleAndPred} was loaded from file @var{File}, where @var{File} is an absolute path name (see @code{absolute_file_name/2}). + + + +@end table + diff --git a/docs/install.tex b/docs/install.tex new file mode 100644 index 000000000..593a9e55d --- /dev/null +++ b/docs/install.tex @@ -0,0 +1,389 @@ +@c -*- mode: texinfo; coding: utf-8; -*- + +@node Install, Run, Intro, Top +@chapter Installing YAP +@cindex installation + + +@menu +* Configuration Options:: Tuning the Functionality of YAP Machine +* Machine Options:: Tuning YAP for a Particular Machine and Compiler +@end menu + +To compile YAP it should be sufficient to: + +@enumerate +@item @command{autoconf}. Recent versions of YAP try to follow GNU +conventions on where to place software. + +@itemize @bullet +@item The main executable is placed at @var{$BINDIR}. This executable is +actually a script that calls the Prolog engine, stored at @var{$LIBDIR}. + +@item @var{$LIBDIR} is the directory where libraries are stored. YAPLIBDIR is a +subdirectory that contains the Prolog engine and a Prolog library. + +@item @var{$INCLUDEDIR} is used if you want to use YAP as a library. + +@item @var{$INFODIR} is where to store @code{info} files. Usually +@file{/usr/local/info}, @file{/usr/info}, or @file{/usr/share/info}. +@end itemize + +@item @command{make}. + +@item If the compilation succeeds, try @command{./yap}. + +@item If you feel satisfied with the result, do @command{make install}. + +@item @command{make install-info} will create the info files in the +standard info directory. + +@item @command{make html} will create documentation in html format in the +predefined directory. + +@end enumerate +In most systems you will need to be superuser in order to do @command{make +install} and @command{make info} on the standard directories. + +@node Configuration Options, Machine Options, ,Install +@section Tuning the Functionality of YAP +@cindex syntax + +Compiling YAP with the standard options give you a plain vanilla +Prolog. You can tune YAP to include extra functionality by calling +@command{configure} with the appropriate options: + +@itemize @bullet + @item @command{--enable-rational-trees=yes} gives you support for infinite +rational trees. + + @item @command{--enable-coroutining=yes} gives you support for coroutining, +including freezing of goals, attributed variables, and +constraints. This will also enable support for infinite rational +trees. + + @item @command{--enable-depth-limit=yes} allows depth limited evaluation, say for +implementing iterative deepening. + + @item @command{--enable-low-level-tracer=yes} allows support for tracing all calls, +retries, and backtracks in the system. This can help in debugging your +application, but results in performance loss. + + @item @command{--enable-wam-profile=yes} allows profiling of abstract machine +instructions. This is useful when developing YAP, should not be so +useful for normal users. + + @item @command{--enable-condor=yes} allows using the Condor system that +support High Throughput Computing (HTC) on large collections of +distributively owned computing resources. + + @item @command{--enable-tabling=yes} allows tabling support. This option +is still experimental. + + @item @command{--enable-parallelism=@{env-copy,sba,a-cow@}} allows +or-parallelism supported by one of these three forms. This option is +still highly experimental. + + @item @command{--with-max-workers} allows definition of the maximum +number of parallel processes (its value can be consulted at runtime +using the flag @command{max_workers}). + + @item @command{--with-gmp[=DIR]} give a path to where one can find the +@code{GMP} library if not installed in the default path. + + @item @command{--enable-threads} allows using of the multi-threading +predicates provided by YAP. Depending on the operating system, the +option @command{--enable-pthread-locking} may also need to be used. + + @item @command{--with-max-threads} allows definition of the maximum +number of threads (the default value is 1024; its value can be consulted +at runtime using the flag @code{max_threads}). + +@end itemize + +Next section discusses machine dependent details. + +@node Machine Options, , Configuration Options,Install +@section Tuning YAP for a Particular Machine and Compiler +@cindex machine optimizations + +The default options should give you best performance under +@command{GCC}. Although the system is tuned for this compiler +we have been able to compile versions of YAP under lcc in Linux, +Sun's cc compiler, IBM's xlc, SGI's cc, and Microsoft's Visual C++ +6.0. + +@menu +* Tuning for GCC:: Using the GNUCC compiler +* Compiling Under Visual C++:: Using Microsoft's Visual C++ environment +* Tuning for SGI cc:: Compiling Under SGI's @command{cc} +@end menu + + +@node Tuning for GCC, Compiling Under Visual C++, , Machine Options +@section Tuning YAP for @command{GCC}. + +YAP has been developed to take advantage of @command{GCC} (but not to +depend on it). The major advantage of @command{GCC} is threaded code and +explicit register reservation. + +YAP is set by default to compile with the best compilation flags we +know. Even so, a few specific options reduce portability. The option +@itemize @bullet + @item @command{--enable-max-performance=yes} will try to support the best +available flags for a specific architectural model. Currently, the option +assumes a recent version of @command{GCC}. + @item @command{--enable-debug-yap} compiles YAP so that it can be debugged +by tools such as @command{dbx} or @command{gdb}. +@end itemize + +Here follow a few hints: + +On x86 machines the flags: + +@example +YAP_EXTRAS= ... -DBP_FREE=1 +@end example + +tells us to use the @code{%bp} register (frame-pointer) as the emulator's +program counter. This seems to be stable and is now default. + +On Sparc/Solaris2 use: + +@example +YAP_EXTRAS= ... -mno-app-regs -DOPTIMISE_ALL_REGS_FOR_SPARC=1 +@end example + +and YAP will get two extra registers! This trick does not work on +SunOS 4 machines. + +Note that versions of GCC can be tweaked to recognize different +processors within the same instruction set, e.g. 486, Pentium, and +PentiumPro for the x86; or Ultrasparc, and Supersparc for +Sparc. Unfortunately, some of these tweaks do may make YAP run slower or +not at all in other machines with the same instruction set, so they +cannot be made default. + +Last, the best options also depends on the version of GCC you are using, and +it is a good idea to consult the GCC manual under the menus "Invoking +GCC"/"Submodel Options". Specifically, you should check +@command{-march=XXX} for recent versions of GCC/EGCS. In the case of +@command{GCC2.7} and other recent versions of @command{GCC} you can check: + +@itemize @bullet + +@item 486: +In order to take advantage of 486 specific optimizations in GCC 2.7.*: + +@example +YAP_EXTRAS= ... -m486 -DBP_FREE=1 +@end example + +@item Pentium: +@example +YAP_EXTRAS= ... -m486 -malign-loops=2 -malign-jumps=2 \ + -malign-functions=2 +@end example + +@item PentiumPro and other recent Intel and AMD machines: +PentiumPros are known not to require alignment. Check your version of +@command{GCC} for the best @command{-march} option. + +@item Super and UltraSparcs: +@example +YAP_EXTRAS= ... -msupersparc +@end example + +@item MIPS: if have a recent machine and you need a 64 bit wide address +space you can use the abi 64 bits or eabi option, as in: +@example +CC="gcc -mabi=64" ./configure --... +@end example +Be careful. At least for some versions of @command{GCC}, compiling with +@command{-g} seems to result in broken code. + +@item WIN32: GCC is distributed in the MINGW32 and CYGWIN packages. + +The Mingw32 environment is available from the URL: + +@url{http://www.mingw.org} + +You will need to install the @command{msys} and @command{mingw} +packages. You should be able to do configure, make and make install. + +If you use mingw32 you may want to search the contributed packages for +the @command{gmp} multi-precision arithmetic library. If you do setup YAP +with @code{gmp} note that @file{libgmp.dll} must be in the path, +otherwise YAP will not be able to execute. + +CygWin environment is available from the URL: + +@url{http://www.cygwin.com} + +@noindent +and mirrors. We suggest using recent versions of the cygwin shell. The +compilation steps under the cygwin shell are as follows: + +@example +mkdir cyg +$YAPSRC/configure --enable-coroutining \\ + --enable-depth-limit \\ + --enable-max-performance +make +make install +@end example + +By default, YAP will use the @command{-mno-cygwin} option to +disable the use of the cygwin dll and to enable the mingw32 subsystem +instead. YAP thus will not need the cygwin dll. It instead accesses +the system's @file{CRTDLL.DLL} @code{C} run time library supplied with +Win32 platforms through the mingw32 interface. Note that some older +WIN95 systems may not have @file{CRTDLL.DLL}, in this case it should +be sufficient to import the file from a newer WIN95 or WIN98 machine. + +You should check the default installation path which is set to +@file{/YAP} in the standard Makefile. This string will usually +be expanded into @file{c:\YAP} by Windows. + +The cygwin environment does not provide @t{gmp} on the MINGW +subsystem. You can fetch a dll for the @t{gmp} library from +@url{http://www.sf.net/projects/mingwrep}. + +It is also possible to configure YAP to be a part of the cygwin +environment. In this case you should use: +@example +mkdir cyg +$YAPSRC/configure --enable-max-performance \\ + --enable-cygwin=yes +make +make install +@end example +YAP will then compile using the cygwin library and will be installed +in cygwin's @file{/usr/local}. You can use YAP from a cygwin console, +or as a standalone application as long as it can find +@file{cygwin1.dll} in its path. Note that you may use to use +@command{--enable-depth-limit} for Aleph compatibility, and that you may +want to be sure that GMP is installed. + +@end itemize + +@node Compiling Under Visual C++, Tuning for SGI cc, Tuning for GCC, Machine Options +@subsection Compiling Under Visual C++ + +YAP compiles cleanly under Microsoft's Visual C++ release 6.0. We next +give a step-by-step tutorial on how to compile YAP manually using this +environment. + +First, it is a good idea to build YAP as a DLL: + +@enumerate + +@item create a project named yapdll using File.New. The project will be a +DLL project, initially empty. + +Notice that either the project is named yapdll or you must replace the +preprocessors variable @var{$YAPDLL_EXPORTS} to match your project names +in the files @file{YAPInterface.h} and @code{c_interface.c}. + +@item add all .c files in the @file{$YAPSRC/C} directory and in the +@file{$YAPSRC\OPTYAP} directory to the Project's @code{Source Files} (use +FileView). + +@item add all .h files in the @var{$YAPSRC/H} directory, +@var{$YAPSRC\include} directory and in the @var{$YAPSRC\OPTYAP} +subdirectory to the Project's @code{Header Files}. + +@item Ideally, you should now use @code{m4} to generate extra .h from .m4 files and use +@code{configure} to create a @code{config.h}. Or, you can be lazy, and +fetch these files from @var{$YAPSRC\VC\include}. + +@item You may want to go to @code{Build.Set Active Configuration} and +set @code{Project Type} to @code{Release} + +@item To use YAP's own include directories you have to set the Project +option @code{Project.Project Settings.C/C++.Preprocessor.Additional +Include Directories} to include the directories @var{$YAPSRC\H}, +@var{$YAPSRC\VC\include}, @var{$YAPSRC\OPTYAP} and +@var{$YAPSRC\include}. The syntax is: + +@example +$YAPSRC\H, $YAPSRC\VC\include, $YAPSRC\OPTYAP, $YAPSRC\include +@end example + +@item Build: the system should generate an @file{yapdll.dll} and an @file{yapdll.lib}. + +@item Copy the file @file{yapdll.dll} to your path. The file +@file{yapdll.lib} should also be copied to a location where the linker can find it. +@end enumerate + +Now you are ready to create a console interface for YAP: +@enumerate +@item create a second project say @code{wyap} with @code{File.New}. The project will be a +WIN32 console project, initially empty. + +@item add @var{$YAPSRC\console\yap.c} to the @code{Source Files}. + +@item add @var{$YAPSRC\VC\include\config.h} and the files in @var{$YAPSRC\include} to +the @code{Header Files}. + +@item You may want to go to @code{Build.Set Active Configuration} and set +@code{Project Type} to @code{Release}. + +@item you will eventually need to bootstrap the system by booting from +@code{boot.yap}, so write: + +@example + -b $YAPSRC\pl\boot.yap +@end example + + in @code{Project.Project Settings.Debug.Program Arguments}. + +@item You need the sockets and yap libraries. Add + +@example +ws2_32.lib yapdll.lib +@end example + +to @code{Project.Project Settings.Link.Object/Library Modules} + +You may also need to set the @code{Link Path} so that VC++ will find @code{yapdll.lib}. + +@item set @code{Project.Project Settings.C/C++.Preprocessor.Additional Include Directories} to include the +@var{$YAPSRC/VC/include} and +@var{$YAPSRC/include}. + +The syntax is: + +@example +$YAPSRC\VC\include, $YAPSRC\include +@end example + +@item Build the system. + +@item Use @code{Build.Start Debug} to boot the system, and then create the saved state with + +@example +['$YAPSRC\\pl\\init']. +qsave_program('startup.yss'). +^Z +@end example + +That's it, you've got YAP and the saved state! +@end enumerate + +The $YAPSRC\VC directory has the make files to build YAP4.3.17 under VC++ 6.0. + +@node Tuning for SGI cc, , Compiling Under Visual C++ ,Machine Options +@subsection Compiling Under SGI's cc + +YAP should compile under the Silicon Graphic's @code{cc} compiler, +although we advise using the GNUCC compiler, if available. + +@table @code +@item 64 bit +Support for 64 bits should work by using (under Bourne shell syntax): +@example +CC="cc -64" $YAP_SRC_PATH/configure --... +@end example +@end table + diff --git a/docs/load.tex b/docs/load.tex new file mode 100644 index 000000000..c2b0ed77d --- /dev/null +++ b/docs/load.tex @@ -0,0 +1,1021 @@ +@c -*- mode: texinfo; coding: utf-8; -*- + + +@node Loading Programs, Modules, Syntax, Top +@chapter Loading and Manipulating Programs + +@menu + +Loading Programs +* Compiling:: Program Loading and Updating +* Setting the Compiler:: Changing the compiler's parameters +* Conditional Compilation:: Compiling program fragments +* Saving:: Saving and Restoring Programs + +@end menu + + +@node Compiling, Setting the Compiler, , Loading Programs +@section Program loading and updating + +@table @code + +@item consult(@var{+F}) +@findex consult/1 +@snindex consult/1 +@cyindex consult/1 +Adds the clauses written in file @var{F} or in the list of files @var{F} +to the program. + +In YAP @code{consult/1} does not remove previous clauses for +the procedures defined in @var{F}. Moreover, note that all code in YAP +is compiled. + +@item reconsult(@var{+F}) +@findex reconsult/1 +@snindex reconsult/1 +@cyindex reconsult/1 +Updates the program replacing the +previous definitions for the predicates defined in @var{F}. + + +@item [@var{+F}] +@findex nil/1 +@saindex []/1 +@cyindex []/1 +The same as @code{consult(F)}. + +@item [-@var{+F}] +@findex dash_nil/1 +@saindex [-]/1 +@cyindex [-]/1 +The same as @code{reconsult(F)} + +Example: + +@example +?- [file1, -file2, -file3, file4]. +@end example +@noindent +will consult @code{file1} @code{file4} and reconsult @code{file2} and +@code{file3}. + +@item compile(@var{+F}) +@findex compile/1 +@syindex compile/1 +@cnindex compile/1 +@noindent +In YAP, the same as @code{reconsult/1}. + +@item load_files(@var{+Files}, @var{+Options}) +@findex load_files/2 +@syindex load_files/2 +@cnindex load_files/2 +@noindent +General implementation of @code{consult}. Execution is controlled by the +following flags: + +@table @code +@item autoload(+@var{Autoload}) +SWI-compatible option where if @var{Autoload} is @code{true} predicates +are loaded on first call. Currently +not supported. +@item derived_from(+@var{File}) + SWI-compatible option to control make. Currently + not supported. +@item encoding(+@var{Encoding}) +Character encoding used in consulting files. Please @pxref{Encoding} for +supported encodings. + +@item expand(+@var{Bool}) + Not yet implemented. In SWI-Prolog, if @code{true}, run the + filenames through @code{expand_file_name/2} and load the returned + files. Default is false, except for @code{consult/1} which is + intended for interactive use. + +@item if(+@var{Condition}) + Load the file only if the specified @var{Condition} is + satisfied. The value @code{true} the file unconditionally, + @code{changed} loads the file if it was not loaded before, or has + been modified since it was loaded the last time, @code{not_loaded} + loads the file if it was not loaded before. + +@item imports(+@var{ListOrAll}) + If @code{all} and the file is a module file, import all public + predicates. Otherwise import only the named predicates. Each + predicate is referred to as @code{/}. This option has + no effect if the file is not a module file. + +@item must_be_module(+@var{Bool}) + If true, raise an error if the file is not a module file. Used by + @code{use_module/[1,2]}. + +@c qcompile(Bool) +@c If this call appears in a directive of a file that is compiled into Quick Load Format using qcompile/1 and this flag is true, the contents of the argument files are included in the .qlf file instead of the loading directive. + +@item silent(+@var{Bool}) + If true, load the file without printing a message. The specified value is the default for all files loaded as a result of loading the specified files. + +@item stream(+@var{Input}) + This SWI-Prolog extension compiles the data from the stream + @var{Input}. If this option is used, @var{Files} must be a single + atom which is used to identify the source-location of the loaded + clauses as well as remove all clauses if the data is re-consulted. + + This option is added to allow compiling from non-file locations such as databases, the web, the user (see consult/1) or other servers. + +@item compilation_mode(+@var{Mode}) + This extension controls how procedures are compiled. If @var{Mode} + is @code{compact} clauses are compiled and no source code is stored; + if it is @code{source} clauses are compiled and source code is stored; + if it is @code{assert_all} clauses are asserted into the data-base. + +@item comnsult(+@var{Mode}) + This extension controls the type of file to load. If @var{Mode} + is @code{consult}, clauses are added to the data-base, + is @code{reconsult}, clauses are recompiled, + is @code{db}, these are facts that need to be added to the data-base, + is @code{exo}, these are facts with atoms and integers that need a very compact representation. +@end table + +@item ensure_loaded(@var{+F}) [ISO] +@findex ensure_loaded/1 +@syindex compile/1 +@cnindex compile/1 +When the files specified by @var{F} are module files, +@code{ensure_loaded/1} loads them if they have note been previously +loaded, otherwise advertises the user about the existing name clashes +and prompts about importing or not those predicates. Predicates which +are not public remain invisible. + +When the files are not module files, @code{ensure_loaded/1} loads them +if they have not been loaded before, does nothing otherwise. + +@var{F} must be a list containing the names of the files to load. + +@item load_db(@var{+Files}) +@findex load_db/1 +@syindex load_db/1 +@cnindex load_db/1 +@noindent +Load a database of facts with equal structure. + +@item exo_files(@var{+Files}) +@findex exo_files/1 +@syindex exo_files/1 +@cnindex exo_files/1 +@noindent +Load compactly a database of facts with equal structure. Useful when wanting to +read in a very compact way database tables. + +@item make +@findex make/0 +@snindex make/0 +@cnindex make/0 + SWI-Prolog built-in to consult all source files that have been + changed since they were consulted. It checks all loaded source + files. make/0 can be combined with the compiler to speed up the + development of large packages. In this case compile the package + using + +@example + sun% pl -g make -o my_program -c file ... +@end example + + If `my_program' is started it will first reconsult all source files + that have changed since the compilation. + +@item include(@var{+F}) [ISO] +@findex include/1 (directive) +@snindex compile/1 (directive) +@cnindex compile/1 (directive) +The @code{include} directive includes the text files or sequence of text +files specified by @var{F} into the file being currently consulted. + +@end table + +@node Setting the Compiler, Conditional Compilation, Compiling, Loading Programs +@section Changing the Compiler's Behavior + +This section presents a set of built-ins predicates designed to set the +environment for the compiler. + +@table @code + +@item source_mode(-@var{O},+@var{N}) +@findex source_mode/2 +@snindex source_mode/2 +@cnindex source_mode/2 +The state of source mode can either be on or off. When the source mode +is on, all clauses are kept both as compiled code and in a "hidden" +database. @var{O} is unified with the previous state and the mode is set +according to @var{N}. + +@item source +@findex source/0 +@snindex source/0 +@cnindex source/0 +After executing this goal, YAP keeps information on the source +of the predicates that will be consulted. This enables the use of +@code{listing/0}, @code{listing/1} and @code{clause/2} for those +clauses. + +The same as @code{source_mode(_,on)} or as declaring all newly defined +static procedures as @code{public}. + +@item no_source +@findex no_source/0 +@snindex no_source/0 +@cnindex no_source/0 +The opposite to @code{source}. + +The same as @code{source_mode(_,off)}. + +@item compile_expressions +@findex compile_expressions/0 +@snindex compile_expressions/0 +@cnindex compile_expressions/0 +After a call to this predicate, arithmetical expressions will be compiled. +(see example below). This is the default behavior. + +@item do_not_compile_expressions +@findex do_not_compile_expressions/0 +@snindex do_not_compile_expressions/0 +@cnindex do_not_compile_expressions/0 +After a call to this predicate, arithmetical expressions will not be compiled. +@example +?- source, do_not_compile_expressions. +yes +?- [user]. +| p(X) :- X is 2 * (3 + 8). +| :- end_of_file. +?- compile_expressions. +yes +?- [user]. +| q(X) :- X is 2 * (3 + 8). +| :- end_of_file. +:- listing. + +p(A):- + A is 2 * (3 + 8). + +q(A):- + A is 22. +@end example + +@item hide(+@var{Atom}) +@findex hide/1 +@snindex hide/1 +@cnindex hide/1 +Make atom @var{Atom} invisible. + +@item unhide(+@var{Atom}) +@findex unhide/1 +@snindex unhide/1 +@cnindex unhide/1 +Make hidden atom @var{Atom} visible. + + +@item hide_predicate(+@var{Pred}) +@findex hide_predicate/1 +@snindex hide_predicate/1 +@cnindex hide_predicate/1 +Make predicate @var{Pred} invisible to @code{current_predicate/2}, +@code{listing}, and friends. + +@item stash_predicate(+@var{Pred}) +@findex stash_predicate/1 +@snindex stash_predicate/1 +@cnindex stash_predicate/1 +Make predicate @var{Pred} invisible to new code, and to @code{current_predicate/2}, +@code{listing}, and friends. New predicates with the same name and +functor can be declared. + +@item expand_exprs(-@var{O},+@var{N}) +@findex expand_exprs/2 +@snindex expand_exprs/2 +@cyindex expand_exprs/2 +Puts YAP in state @var{N} (@code{on} or @code{off}) and unify +@var{O} with the previous state, where @var{On} is equivalent to +@code{compile_expressions} and @code{off} is equivalent to +@code{do_not_compile_expressions}. This predicate was kept to maintain +compatibility with C-Prolog. + +@item path(-@var{D}) +@findex path/1 +@snindex path/1 +@cnindex path/1 +Unifies @var{D} with the current directory search-path of YAP. +Note that this search-path is only used by YAP to find the +files for @code{consult/1}, @code{reconsult/1} and @code{restore/1} and +should not be taken for the system search path. + +@item add_to_path(+@var{D}) +@findex add_to_path/1 +@snindex path/1 +@cnindex path/1 +Adds @var{D} to the end of YAP's directory search path. + +@item add_to_path(+@var{D},+@var{N}) +@findex add_to_path/2 +@snindex path/1 +@cnindex path/1 +Inserts @var{D} in the position, of the directory search path of +YAP, specified by @var{N}. @var{N} must be either of +@code{first} or @code{last}. + +@item remove_from_path(+@var{D}) +@findex remove_from_path/1 +@snindex remove_from_path/1 +@cnindex remove_from_path/1 +Remove @var{D} from YAP's directory search path. + +@item style_check(+@var{X}) +@findex style_check/1 +@snindex style_check/1 +@cnindex style_check/1 +Turns on style checking according to the attribute specified by @var{X}, +which must be one of the following: +@table @code +@item single_var +Checks single occurrences of named variables in a clause. +@item discontiguous +Checks non-contiguous clauses for the same predicate in a file. +@item multiple +Checks the presence of clauses for the same predicate in more than one +file when the predicate has not been declared as @code{multifile} +@item all +Performs style checking for all the cases mentioned above. +@end table +By default, style checking is disabled in YAP unless we are in +@code{sicstus} or @code{iso} language mode. + +The @code{style_check/1} built-in is now deprecated. Please use the +@code{set_prolog_flag/1} instead. + +@item no_style_check(+@var{X}) +@findex no_style_check/1 +@snindex style_check/1 +@cnindex style_check/1 +Turns off style checking according to the attribute specified by +@var{X}, which has the same meaning as in @code{style_check/1}. + +The @code{no_style_check/1} built-in is now deprecated. Please use the +@code{set_prolog_flag/1} instead. + +@item multifile @var{P} [ISO] +@findex multifile/1 (directive) +@syindex multifile/1 (directive) +@cnindex multifile/1 (directive) +Instructs the compiler about the declaration of a predicate @var{P} in +more than one file. It must appear in the first of the loaded files +where the predicate is declared, and before declaration of any of its +clauses. + +Multifile declarations affect @code{reconsult/1} and @code{compile/1}: +when a multifile predicate is reconsulted, only the clauses from the +same file are removed. + +Since YAP4.3.0 multifile procedures can be static or dynamic. + +@item discontiguous(+@var{G}) [ISO] +@findex discontiguous/1 (directive) +@syindex discontiguous/1 (directive) +@cnindex discontiguous/1 (directive) + +Declare that the arguments are discontiguous procedures, that is, +clauses for discontigous procedures may be separated by clauses from +other procedures. + +@item initialization(+@var{G}) [ISO] +@findex initialization/1 (directive) +@snindex initialization/1 (directive) +@cnindex initialization/1 (directive) +The compiler will execute goals @var{G} after consulting the current +file. + +@item initialization(+@var{Goal},+@var{When}) +@findex initialization/2 (directive) +@snindex initialization/2 (directive) +@cnindex initialization/2 (directive) +Similar to @code{initialization/1}, but allows for specifying when +@var{Goal} is executed while loading the program-text: + +@table @code +@item now + Execute @var{Goal} immediately. +@item after_load + Execute @var{Goal} after loading program-text. This is the same as initialization/1. +@item restore + Do not execute @var{Goal} while loading the program, but only when + restoring a state (not implemented yet). +@end table + +@item library_directory(+@var{D}) +@findex library_directory/1 +@snindex library_directory/1 +@cnindex library_directory/1 +Succeeds when @var{D} is a current library directory name. Library +directories are the places where files specified in the form +@code{library(@var{File})} are searched by the predicates +@code{consult/1}, @code{reconsult/1}, @code{use_module/1} or +@code{ensure_loaded/1}. + +@item file_search_path(+@var{NAME},-@var{DIRECTORY}) +@findex file_search_path/2 +@syindex file_search_path/2 +@cnindex file_search_path/2 +Allows writing file names as compound terms. The @var{NAME} and + @var{DIRECTORY} must be atoms. The predicate may generate multiple +solutions. The predicate is originally defined as follows: + +@example +file_search_path(library,A) :- + library_directory(A). +file_search_path(system,A) :- + prolog_flag(host_type,A). +@end example + +Thus, @code{[library(A)]} will search for a file using +@code{library_directory/1} to obtain the prefix. + +@item library_directory(+@var{D}) +@findex library_directory/1 +@snindex library_directory/1 +@cnindex library_directory/1 +Succeeds when @var{D} is a current library directory name. Library +directories are the places where files specified in the form +@code{library(@var{File})} are searched by the predicates +@code{consult/1}, @code{reconsult/1}, @code{use_module/1} or +@code{ensure_loaded/1}. + +@item prolog_file_name(+@var{Name},-@var{FullPath}) +@findex prolog_file_name/2 +@syindex prolog_file_name/1 +@cnindex prolog_file_name/2 +Unify @var{FullPath} with the absolute path YAP would use to consult +file @var{Name}. + +@item prolog_to_os_filename(+@var{PrologPath},-@var{OsPath}) +@findex prolog_to_os_filename/2 +@snindex prolog_to_os_filename/2 +@cnindex prolog_to_os_filename/2 + +This is an SWI-Prolog built-in. Converts between the internal Prolog +pathname conventions and the operating-system pathname conventions. The +internal conventions are Unix and this predicates is equivalent to =/2 +(unify) on Unix systems. On DOS systems it will change the +directory-separator, limit the filename length map dots, except for the +last one, onto underscores. + +@item expand_file_name(+@var{WildCard},-@var{List}) +@findex expand_file_name/2 +@snindex expand_file_name/2 +@cnindex expand_file_name/2 + +This is an SWI-Prolog built-in. Unify @var{List} with a sorted list of +files or directories matching @var{WildCard}. The normal Unix wildcard +constructs @t{?}, @t{*}, @t{[ ... ]} and @t{@{...@}} are recognised. The +interpretation of @t{@{...@}} is interpreted slightly different from the +C shell (csh(1)). The comma separated argument can be arbitrary +patterns, including @t{@{...@}} patterns. The empty pattern is legal as +well: @t{@{.pl,@}} matches either @t{.pl} or the empty string. + +If the pattern contains wildcard characters, only existing files and +directories are returned. Expanding a @emph{pattern'} without wildcard +characters returns the argument, regardless on whether or not it exists. + +Before expanding wildcards, the construct $var is expanded to the value +of the environment variable var and a possible leading ~ character is +expanded to the user's home directory. In Windows, the home directory is +determined as follows: if the environment variable @code{HOME} exists, +this is used. If the variables @code{HOMEDRIVE} and @code{HOMEPATH} +exist (Windows-NT), these are used. At initialisation, the system will +set the environment variable @code{HOME} to point to the YAP home +directory if neither @code{HOME} nor @code{HOMEPATH} and +@code{HOMEDRIVE} are defined. + + +@item public @var{P} [ISO extension] +@findex public/1 (directive) +@snindex public/1 (directive) +@cnindex public/1 (directive) +Instructs the compiler that the source of a predicate of a list of +predicates @var{P} must be kept. This source is then accessible through +the @code{clause/2} procedure and through the @code{listing} family of +built-ins. + +Note that all dynamic procedures are public. The @code{source} directive +defines all new or redefined predicates to be public. + +Since YAP4.3.0 multifile procedures can be static or dynamic. + +@end table + +@node Conditional Compilation, Saving, Setting the Compiler, Loading Programs + +@section Conditional Compilation + +@c \index{if, directive}% +Conditional compilation builds on the same principle as +@code{term_expansion/2}, @code{goal_expansion/2} and the expansion of +grammar rules to compile sections of the source-code +conditionally. One of the reasons for introducing conditional +compilation is to simplify writing portable code. +@c See \secref{dialect} +@c for more information. Here is a simple example: + +@c @table code +@c :- if(\+source_exports(library(lists), suffix/2)). + +@c suffix(Suffix, List) :- +@c append(_, Suffix, List). + +@c :- endif. +@c \end{code} + +Note that these directives can only be appear as separate terms in the +input. Typical usage scenarios include: + +@itemize @bullet + @item Load different libraries on different dialects + @item Define a predicate if it is missing as a system predicate + @item Realise totally different implementations for a particular + part of the code due to different capabilities. + @item Realise different configuration options for your software. +@end itemize + + +@table @code +@item if(+@var{Goal}) +@findex if/1 directive +@snindex if/1 +@cnindex if/1 +Compile subsequent code only if @var{Goal} succeeds. For enhanced +portability, @var{Goal} is processed by @code{expand_goal/2} before execution. +If an error occurs, the error is printed and processing proceeds as if +@var{Goal} has failed. + +@item else +@findex else/0 directive +@snindex else/0 +@cnindex else/0 +Start `else' branch. + +@item endif +@findex endif/0 directive +@snindex endif/0 +@cnindex endif/0 +End of conditional compilation. + +@item elif(+@var{Goal}) +@findex elif/1 directive +@snindex elif/1 +@cnindex elif/1 +Equivalent to @code{:- else. :-if(Goal) ... :- endif.} In a sequence +as below, the section below the first matching elif is processed, If +no test succeeds the else branch is processed. + +@example +:- if(test1). +section_1. +:- elif(test2). +section_2. +:- elif(test3). +section_3. +:- else. +section_else. +:- endif. +@end example + +@end table + +@node Saving, , Conditional Compilation, Loading Programs +@section Saving and Loading Prolog States + +@table @code +@item save(+@var{F}) +@findex save/1 +@snindex save/1 +@cyindex save/1 +Saves an image of the current state of YAP in file @var{F}. From +@strong{YAP4.1.3} onwards, YAP saved states are executable +files in the Unix ports. + +@item save(+@var{F},-@var{OUT}) +@findex save/2 +@snindex save/2 +@cnindex save/2 +Saves an image of the current state of YAP in file @var{F}. From +@strong{YAP4.1.3} onwards, YAP saved states are executable +files in the Unix ports. + +Unify @var{OUT} with 1 when saving the file and @var{OUT} with 0 when +restoring the saved state. + +@item save_program(+@var{F}) +@findex save_program/1 +@syindex save_program/1 +@cnindex save_program/1 +Saves an image of the current state of the YAP database in file +@var{F}. + +@item save_program(+@var{F}, :@var{G}) +@findex save_program/2 +@syindex save_program/2 +@cnindex save_program/2 +Saves an image of the current state of the YAP database in file +@var{F}, and guarantee that execution of the restored code will start by +trying goal @var{G}. + +@item qsave_program(+@var{F}, +@var{ListOfOpts}) +@findex qsave_program/2 +@syindex qsave_program/2 +@cnindex qsave_program/2 + +Saves the current state of the program to the file @var{File}. The +result is a resource archive containing a saved state that expresses +all Prolog data from the running program and all user-defined +resources. Depending on the stand_alone option, the resource is headed +by the emulator, a Unix shell script or nothing. Options is a list of +additional options: + +@table @code +@item stack(+@var{KBytes}) +Limit for the local and global stack. +@item trail(+@var{KBytes}) +Limit for the trail stack. +@item goal(:@var{Callable}) +Initialization goal for the new executable (see -g). +@c @item toplevel(:@var{Callable}) +@c Top-level goal for the new executable (see -t). +@item init_file(+@var{Atom}) +Default initialization file for the new executable. See -f. +@c class(+Class) +@c If runtime, only read resources from the state (default). If kernel, lock all predicates as system predicates. If development, save the predicates in their current state and keep reading resources from their source (if present). See also resource/3. +@c autoload(+Boolean) +@c If true (default), run autoload/0 first. +@c map(+File) +@c Dump a human-readable trace of what has been saved in File. +@c op(+Action) +@c One of save (default) to save the current operator table or standard to use the initial table of the emulator. +@c stand_alone(+Boolean) +@c If true, the emulator is the first part of the state. If the emulator is started it will test whether a boot-file (state) is attached to the emulator itself and load this state. Provided the application has all libraries loaded, the resulting executable is completely independent of the runtime environment or location where it was built. See also section 2.10.2.4. +@c emulator(+File) +@c File to use for the emulator. Default is the running Prolog image. +@c foreign(+Action) +@c If save, include shared objects (DLLs) into the saved state. See current_foreign_library/2. If the program strip is available, this is first used to reduce the size of the shared object. If a state is started, use_foreign_library/1 first tries to locate the foreign resource in the executable. When found it copies the content of the resource to a temporary file and loads it. If possible (Unix), the temporary object is deleted immediately after opening.106 +@end table + +@item restore(+@var{F}) +@findex restore/1 +@syindex restore/1 +@cnindex restore/1 +Restores a previously saved state of YAP from file @var{F}. + +YAP always tries to find saved states from the current directory +first. If it cannot it will use the environment variable YAPLIBDIR, if +defined, or search the default library directory. +@end table + + +@node Modules, Built-ins, Loading Programs, Top +@section The Module System + +Module systems are quite important for the development of large +applications. YAP implements a module system compatible with the Quintus +Prolog module system. + +The YAP module system is predicate-based. This means a module consists +of a set of predicates (or procedures), such that some predicates are +public and the others are local to a module. Atoms and terms in general +are global to the system. Moreover, the module system is flat, meaning +that we do not support a hierarchy of modules. Modules can +automatically import other modules, though. For compatibility with other +module systems the YAP module system is non-strict, meaning both that +there is a way to access predicates private to a module and that it +is possible to declare predicates for a module from some other module. + +YAP allows one to ignore the module system if one does not want to use +it. Last note that using the module system does not introduce any +significant overheads. + +@menu + +* Module Concepts:: The Key Ideas in Modules +* Defining Modules:: How To Define a New Module +* Using Modules:: How to Use a Module +* Meta-Predicates in Modules:: How to Handle New Meta-Predicates +* Re-Exporting Modules:: How to Re-export Predicates From Other Modules + +@end menu + +@node Module Concepts, Defining Modules, , Modules +@subsection Module Concepts + +The YAP module system applies to predicates. All predicates belong to a +module. System predicates belong to the module @code{primitives}, and by +default new predicates belong to the module @code{user}. Predicates from +the module @code{primitives} are automatically visible to every module. + +Every predicate must belong to a module. This module is called its +@emph{source module}. + +By default, the source module for a clause occurring in a source file +with a module declaration is the declared module. For goals typed in +a source file without module declarations, their module is the module +the file is being loaded into. If no module declarations exist, this is +the current @emph{type-in module}. The default type-in module is +@code{user}, but one can set the current module by using the built-in +@code{module/1}. + +Note that in this module system one can explicitly specify the source +mode for a clause by prefixing a clause with its module, say: +@example +user:(a :- b). +@end example +@noindent +In fact, to specify the source module for a clause it is sufficient to +specify the source mode for the clause's head: +@example +user:a :- b. +@end example +@noindent + +The rules for goals are similar. If a goal appears in a text file with a +module declaration, the goal's source module is the declared +module. Otherwise, it is the module the file is being loaded into or the +type-in module. + +One can override this rule by prefixing a goal with the module it is +supposed to be executed in, say: +@example +nasa:launch(apollo,13). +@end example +will execute the goal @code{launch(apollo,13)} as if the current source +module was @code{nasa}. + +Note that this rule breaks encapsulation and should be used with care. + +@node Defining Modules, Using Modules, Module Concepts, Modules +@subsection Defining a New Module + +A new module is defined by a @code{module} declaration: + +@table @code + +@item module(+@var{M},+@var{L}) +@findex module/2 (directive) +@syindex module/2 (directive) +@cnindex module/2 (directive) +This directive defines the file where it appears as a module file; it +must be the first declaration in the file. +@var{M} must be an atom specifying the module name; @var{L} must be a list +containing the module's public predicates specification, in the form +@code{[predicate_name/arity,...]}. + +The public predicates of a module file can be made accessible by other +files through the directives @code{use_module/1}, @code{use_module/2}, +@code{ensure_loaded/1} and the predicates @code{consult/1} or +@code{reconsult/1}. The non-public predicates +of a module file are not visible by other files; they can, however, be +accessed by prefixing the module name with the +@code{:/2} operator. + +@end table + +The built-in @code{module/1} sets the current source module: +@table @code + +@item module(+@var{M},+@var{L}, +@var{Options}) +@findex module/3 (directive) +@syindex module/3 (directive) +@cnindex module/3 (directive) +Similar to @code{module/2}, this directive defines the file where it +appears in as a module file; it must be the first declaration in the file. +@var{M} must be an atom specifying the module name; @var{L} must be a +list containing the module's public predicates specification, in the +form @code{[predicate_name/arity,...]}. + +The last argument @var{Options} must be a list of options, which can be: + +@table @code +@item filename + the filename for a module to import into the current module. + +@item library(file) + a library file to import into the current module. + +@item hide(@var{Opt}) + if @var{Opt} is @code{false}, keep source code for current module, if +@code{true}, disable. +@end table + +@item module(+@var{M}) +@findex module/1 +@syindex module/1 +@cnindex module/1 +Defines @var{M} to be the current working or type-in module. All files +which are not bound to a module are assumed to belong to the working +module (also referred to as type-in module). To compile a non-module +file into a module which is not the working one, prefix the file name +with the module name, in the form @code{@var{Module}:@var{File}}, when +loading the file. + +@item export(+@var{PredicateIndicator}) +@findex export/1 +@snindex export/1 +@cnindex export/1 + +Add predicates to the public list of the context module. This implies +the predicate will be imported into another module if this module is +imported with @code{use_module/[1,2]}. Note that predicates are normally +exported using the directive @code{module/2}. @code{export/1} is meant +to handle export from dynamically created modules. The directive argument +may also be a list of predicates. + +@item export_list(?@var{Mod},?@var{ListOfPredicateIndicator}) +@findex export_list/2 +@snindex export_list/2 +@cnindex export_list/2 + +The list @var{ListOfPredicateIndicator} contains all predicates exported +by module @var{Mod}. + +@end table + +@node Using Modules, Meta-Predicates in Modules, Defining Modules, Modules +@subsection Using Modules + +By default, all procedures to consult a file will load the modules +defined therein. The two following declarations allow one to import a +module explicitly. They differ on whether one imports all predicate +declared in the module or not. + +@table @code + +@item use_module(+@var{F}) +@findex use_module/1 +@syindex use_module/1 +@cnindex use_module/1 +Loads the files specified by @var{F}, importing all their public +predicates. Predicate name clashes are resolved by asking the user about +importing or not the predicate. A warning is displayed when @var{F} is +not a module file. + +@item use_module(+@var{F},+@var{L}) +@findex use_module/2 +@syindex use_module/2 +@cnindex use_module/2 +Loads the files specified by @var{F}, importing the predicates specified +in the list @var{L}. Predicate name clashes are resolved by asking the +user about importing or not the predicate. A warning is displayed when +@var{F} is not a module file. + +@item use_module(?@var{M},?@var{F},+@var{L}) +@findex use_module/3 +@syindex use_module/3 +@cnindex use_module/3 +If module @var{M} has been defined, import the procedures in @var{L} to +the current module. Otherwise, load the files specified by @var{F}, +importing the predicates specified in the list @var{L}. +@end table + + +@node Meta-Predicates in Modules, Re-Exporting Modules, Using Modules, Modules +@subsection Meta-Predicates and Modules + +The module system must know whether predicates operate on goals or +clauses. Otherwise, such predicates would call a goal in the module they +were defined, instead of calling it in the module they are currently +executing. So, for instance, consider a file example.pl: +@example +:- module(example,[a/1]). + +a(G) :- call(G) +@end example + +We import this module with @code{use_module(example)} into module +@code{user}. The expected behavior for a goal @code{a(p)} is to +execute goal @code{p} within the module @code{user}. However, +@code{a/1} will call @code{p} within module @code{example}. + +The @code{meta_predicate/1} declaration informs the system that some +arguments of a predicate are goals, clauses, clauses heads or other +terms related to a module, and that these arguments must be prefixed +with the current source module: + +@table @code + +@item meta_predicate @var{G1},....,@var{Gn} +@findex meta_predicate/1 (directive) +@syindex meta_predicate/1 (directive) +@cnindex meta_predicate/1 (directive) +Each @var{Gi} is a mode specification. + +If the argument is @code{:}, it does not refer directly to a predicate +but must be module expanded. If the argument is an integer, the argument +is a goal or a closure and must be expanded. Otherwise, the argument is +not expanded. Note that the system already includes declarations for all +built-ins. + +For example, the declaration for @code{call/1} and @code{setof/3} are: + +@example +:- meta_predicate call(0), setof(?,0,?). +@end example + +@end table + +The previous example is expanded to the following code which explains, +why the goal @code{a(p)} calls @code{p} in @code{example} and not in +@code{user}. The goal @code{call(G)} is expanded because of the +meta-predicate declaration for @code{call/1}. + +@example +:- module(example,[a/1]). + +a(G) :- call(example:G) +@end example + +By adding a meta-predicate declaration for @code{a/1}, the goal +@code{a(p)} in module user will be expanded to @code{a(user:p)} +thereby preserving the module information. + +@example +:- module(example,[a/1]). + +:- meta_predicate a(:). +a(G) :- call(G) +@end example + +An alternate mechanism is the directive @code{module_transparent/1} +offered for compatibility with SWI-Prolog. + +@table @code + +@item module_transparent +@var{Preds} +@findex module_transparent/1 (directive) +@syindex module_transparent/1 (directive) +@cnindex module_transparent/1 (directive) + @var{Preds} is a comma separated sequence of name/arity predicate + indicators (like + @code{dynamic/1}). Each goal associated with a transparent declared + predicate will inherit the context module from its parent goal. +@end table + + +@node Re-Exporting Modules, , Meta-Predicates in Modules, Modules +@subsection Re-Exporting Predicates From Other Modules + +It is sometimes convenient to re-export predicates originally defined in +a different module. This is often useful if you are adding to the +functionality of a module, or if you are composing a large module with +several small modules. The following declarations can be used for that purpose: + +@table @code + +@item reexport(+@var{F}) +@findex reexport/1 +@snindex reexport/1 +@cnindex reexport/1 +Export all predicates defined in file @var{F} as if they were defined in +the current module. + +@item reexport(+@var{F},+@var{Decls}) +@findex reexport/2 +@snindex reexport/2 +@cnindex reexport/2 +Export predicates defined in file @var{F} according to @var{Decls}. The +declarations may be of the form: +@itemize @bullet +@item A list of predicate declarations to be exported. Each declaration +may be a predicate indicator or of the form ``@var{PI} @code{as} +@var{NewName}'', meaning that the predicate with indicator @var{PI} is +to be exported under name @var{NewName}. +@item @code{except}(@var{List}) +In this case, all predicates not in @var{List} are exported. Moreover, +if ``@var{PI} @code{as} @var{NewName}'' is found, the predicate with +indicator @var{PI} is to be exported under name @var{NewName}@ as +before. +@end itemize +@end table + +Re-exporting predicates must be used with some care. Please, take into +account the following observations: + +@itemize @bullet +@item +The @code{reexport} declarations must be the first declarations to +follow the @code{module} declaration. +@item +It is possible to use both @code{reexport} and @code{use_module}, but +all predicates reexported are automatically available for use in the +current module. +@item +In order to obtain efficient execution, YAP compiles dependencies +between re-exported predicates. In practice, this means that changing a +@code{reexport} declaration and then @strong{just} recompiling the file +may result in incorrect execution. +@end itemize + diff --git a/docs/run.tex b/docs/run.tex new file mode 100644 index 000000000..82c937efa --- /dev/null +++ b/docs/run.tex @@ -0,0 +1,214 @@ +@c -*- mode: texinfo; coding: utf-8; -*- + +@node Run, Syntax, Install, Top +@chapter Running YAP + +@menu +* Running YAP Interactively:: Interacting with YAP +* Running Prolog Files:: Running Prolog files as scripts +@end menu + +@cindex booting +We next describe how to invoke YAP in Unix systems. + +@node Running YAP Interactively, ,Running Prolog Files,Run +@section Running YAP Interactively + +Most often you will want to use YAP in interactive mode. Assuming that +YAP is in the user's search path, the top-level can be invoked under +Unix with the following command: + +@example +yap [-s n] [-h n] [-a n] [-c IP_HOST port ] [filename] +@end example + +@noindent +All the arguments and flags are optional and have the following meaning: +@table @code +@item -? +print a short error message. +@item -s@var{Size} +allocate @var{Size} KBytes for local and global stacks. The user may + specify @t{M} bytes. +@item -h@var{Size} +allocate @var{Size} KBytes for heap and auxiliary stacks +@item -t@var{Size} +allocate @var{Size} KBytes for the trail stack +@item -L@var{Size} +SWI-compatible option to allocate @var{Size} K bytes for local and global stacks, the local stack + cannot be expanded. To avoid confusion with the load option, @var{Size} + must immediately follow the letter @code{L}. +@item -G@var{Size} +SWI-compatible option to allocate @var{Size} K bytes for local and global stacks; the global +stack cannot be expanded +@item -T@var{Size} +SWI-compatible option to allocate @var{Size} K bytes for the trail stack; the trail cannot be expanded. +@item -l @var{YAP_FILE} +compile the Prolog file @var{YAP_FILE} before entering the top-level. +@item -L @var{YAP_FILE} +compile the Prolog file @var{YAP_FILE} and then halt. This option is +useful for implementing scripts. +@item -g @var{Goal} +run the goal @var{Goal} before top-level. The goal is converted from +an atom to a Prolog term. +@item -z @var{Goal} +run the goal @var{Goal} as top-level. The goal is converted from +an atom to a Prolog term. +@item -b @var{BOOT_FILE} +boot code is in Prolog file @var{BOOT_FILE}. The filename must define +the predicate @code{'$live'/0}. +@item -c @t{IP_HOST} @t{port} +connect standard streams to host @t{IP_HOST} at port @t{port} +@item filename +restore state saved in the given file +@item -f +do not consult initial files +@item -q +do not print informational messages +@item -- +separator for arguments to Prolog code. These arguments are visible +through the @code{unix/1} built-in predicate. +@end table + +Note that YAP will output an error message on the following conditions: + +@itemize @bullet +@item +a file name was given but the file does not exist or is not a saved +YAP state; +@item +the necessary amount of memory could not be allocated; +@item +the allocated memory is not enough to restore the state. +@end itemize + +When restoring a saved state, YAP will allocate the +same amount of memory as that in use when the state was saved, unless a +different amount is specified by flags in the command line. By default, +YAP restores the file @file{startup.yss} from the current directory or from +the YAP library. +@cindex environment variables + +@findex YAPBINDIR +@itemize @bullet +@item +YAP usually boots from a saved state. The saved state will use the default +installation directory to search for the YAP binary unless you define +the environment variable YAPBINDIR. + +@findex YAPLIBDIR +@item +YAP always tries to find saved states from the current directory +first. If it cannot it will use the environment variable YAPLIBDIR, if +defined, or search the default library directory. + +@findex YAPSHAREDIR +@item +YAP will try to find library files from the YAPSHAREDIR/library +directory. +@end itemize + +@node Running Prolog Files, Running YAP Interactively, , Run +@section Running Prolog Files + +YAP can also be used to run Prolog files as scripts, at least in +Unix-like environments. A simple example is shown next (do not forget +that the shell comments are very important): + +@example +@cartouche +#!/usr/local/bin/yap -L -- +# +# Hello World script file using YAP +# +# put a dot because of syntax errors . + +:- write('Hello World'), nl. + +@end cartouche +@end example + +The @code{#!} characters specify that the script should call the binary +file YAP. Notice that many systems will require the complete path to the +YAP binary. The @code{-L} flag indicates that YAP should consult the +current file when booting and then halt. The remaining arguments are +then passed to YAP. Note that YAP will skip the first lines if they +start with @code{#} (the comment sign for Unix's shell). YAP will +consult the file and execute any commands. + +A slightly more sophisticated example is: + +@example +@cartouche +#!/usr/bin/yap -L -- +# +# Hello World script file using YAP +# . + +:- initialization(main). + +main :- write('Hello World'), nl. + +@end cartouche +@end example + +The @code{initialization} directive tells YAP to execute the goal main +after consulting the file. Source code is thus compiled and @code{main} +executed at the end. The @code{.} is useful while debugging the script +as a Prolog program: it guarantees that the syntax error will not +propagate to the Prolog code. + +Notice that the @code{--} is required so that the shell passes the extra +arguments to YAP. As an example, consider the following script +@code{dump_args}: + +@example +@cartouche +#!/usr/bin/yap -L -- +#. + +main( [] ). +main( [H|T] ) :- + write( H ), nl, + main( T ). + +:- unix( argv(AllArgs) ), main( AllArgs ). + +@end cartouche +@end example + +If you this run this script with the arguments: +@example +./dump_args -s 10000 +@end example +@noindent +the script will start an YAP process with stack size @code{10MB}, and +the list of arguments to the process will be empty. + +Often one wants to run the script as any other program, and for this it +is convenient to ignore arguments to YAP. This is possible by using +@code{L --} as in the next version of @code{dump_args}: + +@example +@cartouche +#!/usr/bin/yap -L -- + +main( [] ). +main( [H|T] ) :- + write( H ), nl, + main( T ). + +:- unix( argv(AllArgs) ), main( AllArgs ). + +@end cartouche +@end example + +The @code{--} indicates the next arguments are not for YAP. Instead, +they must be sent directly to the @code{argv} built-in. Hence, running +@example +./dump_args test +@end example +@noindent +will write @code{test} on the standard output. + + diff --git a/docs/swi.tex b/docs/swi.tex index 1c40880c1..4268dc238 100644 --- a/docs/swi.tex +++ b/docs/swi.tex @@ -310,7 +310,7 @@ enumeration is undefined. Delete the named global variable. @end table -@section Compatibility of Global Variables +@subsubsection Compatibility of Global Variables Global variables have been introduced by various Prolog implementations recently. YAP follows their implementation in SWI-Prolog, itself diff --git a/docs/yap.bib b/docs/yap.bib new file mode 100644 index 000000000..64f001862 --- /dev/null +++ b/docs/yap.bib @@ -0,0 +1,13 @@ +@book{TheArtOfProlog, + Author = "Sterling, Leon and Shapiro, Ehud", + Title = "The Art of Prolog", + Publisher = "MIT Press", + Year = "1986" } + +@Book{ProgrammingInProlog, + Author ="William F. Clocksin and Christopher S. Mellish", + Title ={Programming in Prolog}, + Publisher ={Springer-Verlag}, + Year =1986 +} + diff --git a/docs/yap.tex b/docs/yap.tex index 1e06e747e..83d2becc9 100644 --- a/docs/yap.tex +++ b/docs/yap.tex @@ -376,10 +376,9 @@ with SICStus Prolog. The document is intended neither as an introduction to Prolog nor to the implementation aspects of the compiler. A good introduction to -programming in Prolog is the book @cite{The Art of Prolog}, by +programming in Prolog is the book @cite{TheArtOfProlog}, by L. Sterling and E. Shapiro, published by "The MIT Press, Cambridge -MA". Other references should include the classical @cite{Programming in -Prolog}, by W.F. Clocksin and C.S. Mellish, published by +MA". Other references should include the classical @cite{ProgrammingInProlog}, by W.F. Clocksin and C.S. Mellish, published by Springer-Verlag. YAP 4.3 is known to build with many versions of gcc (<= gcc-2.7.2, >= @@ -387,7 +386,7 @@ gcc-2.8.1, >= egcs-1.0.1, gcc-2.95.*) and on a variety of Unixen: SunOS 4.1, Solaris 2.*, Irix 5.2, HP-UX 10, Dec Alpha Unix, Linux 1.2 and Linux 2.* (RedHat 4.0 thru 5.2, Debian 2.*) in both the x86 and alpha platforms. It has been built on Windows NT 4.0 using Cygwin from -Cygnus Solutions (see README.nt) and using Visual C++ 6.0. +Cygnus Solutions (see @file{README.nt}) and using Visual C++ 6.0. The overall copyright and permission notice for YAP4.3 can be found in the Artistic file in this directory. YAP follows the Perl Artistic @@ -441,7 +440,7 @@ Madrid by the CLIP group. This package is distributed under the FSF's LGPL. Documentation on this package is distributed separately from yap.tex. -@item The @code{yap2swi} library implements some of the functionality of +@item The @file{yap2swi} library implements some of the functionality of SWI's PL interface. Please do refer to the SWI-Prolog home page: @url{http://www.swi-prolog.org} @@ -451,8277 +450,15 @@ foreign language interface. @end itemize -@node Install, Run, Intro, Top -@chapter Installing YAP -@cindex installation +@include install.tex +@include run.tex -@menu -* Configuration Options:: Tuning the Functionality of YAP Machine -* Machine Options:: Tuning YAP for a Particular Machine and Compiler -@end menu +@include syntax.tex -To compile YAP it should be sufficient to: +@include load.tex -@enumerate -@item @code{mkdir ARCH}. - -@item @code{cd ARCH}. - -@item @code{../configure ...options...}. - -Notice that by default @code{configure} gives you a vanilla -configuration. For instance, in order to use co-routining and/or CLP -you need to do - -@example -../configure --enable-coroutining ...options... -@end example -Please @pxref{Configuration Options} for extra options. - -@item check the Makefile for any extensions or changes you want to -make. - -YAP uses @code{autoconf}. Recent versions of YAP try to follow GNU -conventions on where to place software. - -@itemize @bullet -@item The main executable is placed at @code{BINDIR}. This executable is -actually a script that calls the Prolog engine, stored at @code{LIBDIR}. - -@item @code{LIBDIR} is the directory where libraries are stored. YAPLIBDIR is a -subdirectory that contains the Prolog engine and a Prolog library. - -@item @code{INCLUDEDIR} is used if you want to use YAP as a library. - -@item @code{INFODIR} is where to store @code{info} files. Usually -@code{/usr/local/info}, @code{/usr/info}, or @code{/usr/share/info}. -@end itemize - -@item @code{make}. - -@item If the compilation succeeds, try @code{./yap}. - -@item If you feel satisfied with the result, do @code{make install}. - -@item @code{make install-info} will create the info files in the -standard info directory. - -@item @code{make html} will create documentation in html format in the -predefined directory. - -In most systems you will need to be superuser in order to do @code{make -install} and @code{make info} on the standard directories. -@end enumerate - -@node Configuration Options, Machine Options, ,Install -@section Tuning the Functionality of YAP -@cindex syntax - -Compiling YAP with the standard options give you a plain vanilla -Prolog. You can tune YAP to include extra functionality by calling -@code{configure} with the appropriate options: - -@itemize @bullet - @item @code{--enable-rational-trees=yes} gives you support for infinite -rational trees. - - @item @code{--enable-coroutining=yes} gives you support for coroutining, -including freezing of goals, attributed variables, and -constraints. This will also enable support for infinite rational -trees. - - @item @code{--enable-depth-limit=yes} allows depth limited evaluation, say for -implementing iterative deepening. - - @item @code{--enable-low-level-tracer=yes} allows support for tracing all calls, -retries, and backtracks in the system. This can help in debugging your -application, but results in performance loss. - - @item @code{--enable-wam-profile=yes} allows profiling of abstract machine -instructions. This is useful when developing YAP, should not be so -useful for normal users. - - @item @code{--enable-condor=yes} allows using the Condor system that -support High Throughput Computing (HTC) on large collections of -distributively owned computing resources. - - @item @code{--enable-tabling=yes} allows tabling support. This option -is still experimental. - - @item @code{--enable-parallelism=@{env-copy,sba,a-cow@}} allows -or-parallelism supported by one of these three forms. This option is -still highly experimental. - - @item @code{--with-max-workers} allows definition of the maximum -number of parallel processes (its value can be consulted at runtime -using the flag @code{max_workers}). - - @item @code{--with-gmp[=DIR]} give a path to where one can find the -@code{GMP} library if not installed in the default path. - - @item @code{--enable-threads} allows using of the multi-threading -predicates provided by YAP. Depending on the operating system, the -option @code{--enable-pthread-locking} may also need to be used. - - @item @code{--with-max-threads} allows definition of the maximum -number of threads (the default value is 1024; its value can be consulted -at runtime using the flag @code{max_threads}). - -@end itemize - -Next section discusses machine dependent details. - -@node Machine Options, , Configuration Options,Install -@section Tuning YAP for a Particular Machine and Compiler -@cindex machine optimizations - -The default options should give you best performance under -@code{GCC}. Although the system is tuned for this compiler -we have been able to compile versions of YAP under lcc in Linux, -Sun's cc compiler, IBM's xlc, SGI's cc, and Microsoft's Visual C++ -6.0. - -@menu -* Tuning for GCC:: Using the GNUCC compiler -* Compiling Under Visual C++:: Using Microsoft's Visual C++ environment -* Tuning for SGI cc:: Compiling Under SGI's @code{cc} -@end menu - - -@node Tuning for GCC, Compiling Under Visual C++, , Machine Options -@section Tuning YAP for @code{GCC}. - -YAP has been developed to take advantage of @code{GCC} (but not to -depend on it). The major advantage of @code{GCC} is threaded code and -explicit register reservation. - -YAP is set by default to compile with the best compilation flags we -know. Even so, a few specific options reduce portability. The option -@itemize @bullet - @item @code{--enable-max-performance=yes} will try to support the best -available flags for a specific architectural model. Currently, the option -assumes a recent version of @code{GCC}. - @item @code{--enable-debug-yap} compiles YAP so that it can be debugged -by tools such as @code{dbx} or @code{gdb}. -@end itemize - -Here follow a few hints: - -On x86 machines the flags: - -@example -YAP_EXTRAS= ... -DBP_FREE=1 -@end example - -tells us to use the @code{%bp} register (frame-pointer) as the emulator's -program counter. This seems to be stable and is now default. - -On Sparc/Solaris2 use: - -@example -YAP_EXTRAS= ... -mno-app-regs -DOPTIMISE_ALL_REGS_FOR_SPARC=1 -@end example - -and YAP will get two extra registers! This trick does not work on -SunOS 4 machines. - -Note that versions of GCC can be tweaked to recognize different -processors within the same instruction set, e.g. 486, Pentium, and -PentiumPro for the x86; or Ultrasparc, and Supersparc for -Sparc. Unfortunately, some of these tweaks do may make YAP run slower or -not at all in other machines with the same instruction set, so they -cannot be made default. - -Last, the best options also depends on the version of GCC you are using, and -it is a good idea to consult the GCC manual under the menus "Invoking -GCC"/"Submodel Options". Specifically, you should check -@code{-march=XXX} for recent versions of GCC/EGCS. In the case of -@code{GCC2.7} and other recent versions of @code{GCC} you can check: - -@table @code - -@item 486: -In order to take advantage of 486 specific optimizations in GCC 2.7.*: - -@example -YAP_EXTRAS= ... -m486 -DBP_FREE=1 -@end example - -@item Pentium: -@example -YAP_EXTRAS= ... -m486 -malign-loops=2 -malign-jumps=2 \ - -malign-functions=2 -@end example - -@item PentiumPro and other recent Intel and AMD machines: -PentiumPros are known not to require alignment. Check your version of -@code{GCC} for the best @code{-march} option. - -@item Super and UltraSparcs: -@example -YAP_EXTRAS= ... -msupersparc -@end example - -@item MIPS: if have a recent machine and you need a 64 bit wide address -space you can use the abi 64 bits or eabi option, as in: -@example -CC="gcc -mabi=64" ./configure --... -@end example -Be careful. At least for some versions of @code{GCC}, compiling with -@code{-g} seems to result in broken code. - -@item WIN32: GCC is distributed in the MINGW32 and CYGWIN packages. - -The Mingw32 environment is available from the URL: - -@code{http://www.mingw.org} - -You will need to install the @code{msys} and @code{mingw} -packages. You should be able to do configure, make and make install. - -If you use mingw32 you may want to search the contributed packages for -the @code{gmp} multi-precision arithmetic library. If you do setup YAP -with @code{gmp} note that @code{libgmp.dll} must be in the path, -otherwise YAP will not be able to execute. - -CygWin environment is available from the URL: - -@code{http://www.cygwin.com} - -@noindent -and mirrors. We suggest using recent versions of the cygwin shell. The -compilation steps under the cygwin shell are as follows: - -@example -mkdir cyg -$YAPSRC/configure --enable-coroutining \\ - --enable-depth-limit \\ - --enable-max-performance -make -make install -@end example - -By default, YAP will use the @code{-mno-cygwin} option to -disable the use of the cygwin dll and to enable the mingw32 subsystem -instead. YAP thus will not need the cygwin dll. It instead accesses -the system's @code{CRTDLL.DLL} @code{C} run time library supplied with -Win32 platforms through the mingw32 interface. Note that some older -WIN95 systems may not have @code{CRTDLL.DLL}, in this case it should -be sufficient to import the file from a newer WIN95 or WIN98 machine. - -You should check the default installation path which is set to -@code{/YAP} in the standard Makefile. This string will usually -be expanded into @code{c:\YAP} by Windows. - -The cygwin environment does not provide @t{gmp} on the MINGW -subsystem. You can fetch a dll for the @t{gmp} library from -@url{http://www.sf.net/projects/mingwrep}. - -It is also possible to configure YAP to be a part of the cygwin -environment. In this case you should use: -@example -mkdir cyg -$YAPSRC/configure --enable-max-performance \\ - --enable-cygwin=yes -make -make install -@end example -YAP will then compile using the cygwin library and will be installed -in cygwin's @code{/usr/local}. You can use YAP from a cygwin console, -or as a standalone application as long as it can find -@code{cygwin1.dll} in its path. Note that you may use to use -@code{--enable-depth-limit} for Aleph compatibility, and that you may -want to be sure that GMP is installed. - -@end table - -@node Compiling Under Visual C++, Tuning for SGI cc, Tuning for GCC, Machine Options -@subsection Compiling Under Visual C++ - -YAP compiles cleanly under Microsoft's Visual C++ release 6.0. We next -give a step-by-step tutorial on how to compile YAP manually using this -environment. - -First, it is a good idea to build YAP as a DLL: - -@enumerate - -@item create a project named yapdll using File.New. The project will be a -DLL project, initially empty. - -Notice that either the project is named yapdll or you must replace the -preprocessors variable @var{YAPDLL_EXPORTS} to match your project names -in the files @code{YAPInterface.h} and @code{c_interface.c}. - -@item add all .c files in the @var{$YAPSRC/C} directory and in the -@var{$YAPSRC\OPTYAP} directory to the Project's @code{Source Files} (use -FileView). - -@item add all .h files in the @var{$YAPSRC/H} directory, -@var{$YAPSRC\include} directory and in the @var{$YAPSRC\OPTYAP} -subdirectory to the Project's @code{Header Files}. - -@item Ideally, you should now use @code{m4} to generate extra .h from .m4 files and use -@code{configure} to create a @code{config.h}. Or, you can be lazy, and -fetch these files from @var{$YAPSRC\VC\include}. - -@item You may want to go to @code{Build.Set Active Configuration} and set @code{Project -Type} to @code{Release} - -@item To use YAP's own include directories you have to set the Project -option @code{Project.Project Settings.C/C++.Preprocessor.Additional -Include Directories} to include the directories @var{$YAPSRC\H}, -@var{$YAPSRC\VC\include}, @var{$YAPSRC\OPTYAP} and -@var{$YAPSRC\include}. The syntax is: - -@example -$YAPSRC\H, $YAPSRC\VC\include, $YAPSRC\OPTYAP, $YAPSRC\include -@end example - -@item Build: the system should generate an @code{yapdll.dll} and an @code{yapdll.lib}. - -@item Copy the file @code{yapdll.dll} to your path. The file -@code{yapdll.lib} should also be copied to a location where the linker can find it. -@end enumerate - -Now you are ready to create a console interface for YAP: -@enumerate -@item create a second project say @code{wyap} with @code{File.New}. The project will be a -WIN32 console project, initially empty. - -@item add @var{$YAPSRC\console\yap.c} to the @code{Source Files}. - -@item add @var{$YAPSRC\VC\include\config.h} and the files in @var{$YAPSRC\include} to -the @code{Header Files}. - -@item You may want to go to @code{Build.Set Active Configuration} and set -@code{Project Type} to @code{Release}. - -@item you will eventually need to bootstrap the system by booting from -@code{boot.yap}, so write: - -@example - -b $YAPSRC\pl\boot.yap -@end example - - in @code{Project.Project Settings.Debug.Program Arguments}. - -@item You need the sockets and yap libraries. Add - -@example -ws2_32.lib yapdll.lib to -@end example - -to - -to @code{Project.Project Settings.Link.Object/Library Modules} - -You may also need to set the @code{Link Path} so that VC++ will find @code{yapdll.lib}. - -@item set @code{Project.Project Settings.C/C++.Preprocessor.Additional -Include Directories} to include the @var{$YAPSRC/VC/include} and -@var{$YAPSRC/include}. - -The syntax is: - -@example -$YAPSRC\VC\include, $YAPSRC\include -@end example - -@item Build the system. - -@item Use @code{Build.Start Debug} to boot the system, and then create the saved state with - -@example -['$YAPSRC\\pl\\init']. -qsave_program('startup.yss'). -^Z -@end example - -That's it, you've got YAP and the saved state! -@end enumerate - -The $YAPSRC\VC directory has the make files to build YAP4.3.17 under VC++ 6.0. - -@node Tuning for SGI cc, , Compiling Under Visual C++ ,Machine Options -@subsection Compiling Under SGI's cc - -YAP should compile under the Silicon Graphic's @code{cc} compiler, -although we advise using the GNUCC compiler, if available. - -@table @code -@item 64 bit -Support for 64 bits should work by using (under Bourne shell syntax): -@example -CC="cc -64" $YAP_SRC_PATH/configure --... -@end example -@end table - -@node Run, Syntax, Install, Top -@chapter Running YAP - -@menu -* Running YAP Interactively:: Interacting with YAP -* Running Prolog Files:: Running Prolog files as scripts -@end menu - -@cindex booting -We next describe how to invoke YAP in Unix systems. - -@node Running YAP Interactively, ,Running Prolog Files,Run -@section Running YAP Interactively - -Most often you will want to use YAP in interactive mode. Assuming that -YAP is in the user's search path, the top-level can be invoked under -Unix with the following command: - -@example -yap [-s n] [-h n] [-a n] [-c IP_HOST port ] [filename] -@end example - -@noindent -All the arguments and flags are optional and have the following meaning: -@table @code -@item -? -print a short error message. -@item -s@var{Size} -allocate @var{Size} KBytes for local and global stacks. The user may - specify @t{M} bytes. -@item -h@var{Size} -allocate @var{Size} KBytes for heap and auxiliary stacks -@item -t@var{Size} -allocate @var{Size} KBytes for the trail stack -@item -L@var{Size} -SWI-compatible option to allocate @var{Size} K bytes for local and global stacks, the local stack - cannot be expanded. To avoid confusion with the load option, @var{Size} - must immediately follow the letter @code{L}. -@item -G@var{Size} -SWI-compatible option to allocate @var{Size} K bytes for local and global stacks; the global -stack cannot be expanded -@item -T@var{Size} -SWI-compatible option to allocate @var{Size} K bytes for the trail stack; the trail cannot be expanded. -@item -l @var{YAP_FILE} -compile the Prolog file @var{YAP_FILE} before entering the top-level. -@item -L @var{YAP_FILE} -compile the Prolog file @var{YAP_FILE} and then halt. This option is -useful for implementing scripts. -@item -g @var{Goal} -run the goal @var{Goal} before top-level. The goal is converted from -an atom to a Prolog term. -@item -z @var{Goal} -run the goal @var{Goal} as top-level. The goal is converted from -an atom to a Prolog term. -@item -b @var{BOOT_FILE} -boot code is in Prolog file @var{BOOT_FILE}. The filename must define -the predicate @code{'$live'/0}. -@item -c @t{IP_HOST} @t{port} -connect standard streams to host @t{IP_HOST} at port @t{port} -@item filename -restore state saved in the given file -@item -f -do not consult initial files -@item -q -do not print informational messages -@item -- -separator for arguments to Prolog code. These arguments are visible -through the @code{unix/1} built-in predicate. -@end table - -Note that YAP will output an error message on the following conditions: - -@itemize @bullet -@item -a file name was given but the file does not exist or is not a saved -YAP state; -@item -the necessary amount of memory could not be allocated; -@item -the allocated memory is not enough to restore the state. -@end itemize - -When restoring a saved state, YAP will allocate the -same amount of memory as that in use when the state was saved, unless a -different amount is specified by flags in the command line. By default, -YAP restores the file @samp{startup.yss} from the current directory or from -the YAP library. -@cindex environment variables - -@findex YAPBINDIR -@itemize @bullet -@item -YAP usually boots from a saved state. The saved state will use the default -installation directory to search for the YAP binary unless you define -the environment variable YAPBINDIR. - -@findex YAPLIBDIR -@item -YAP always tries to find saved states from the current directory -first. If it cannot it will use the environment variable YAPLIBDIR, if -defined, or search the default library directory. - -@findex YAPSHAREDIR -@item -YAP will try to find library files from the YAPSHAREDIR/library -directory. -@end itemize - -@node Running Prolog Files, Running YAP Interactively, , Run -@section Running Prolog Files - -YAP can also be used to run Prolog files as scripts, at least in -Unix-like environments. A simple example is shown next (do not forget -that the shell comments are very important): - -@example -@cartouche -#!/usr/local/bin/yap -L -- -# -# Hello World script file using YAP -# -# put a dot because of syntax errors . - -:- write('Hello World'), nl. - -@end cartouche -@end example - -The @code{#!} characters specify that the script should call the binary -file YAP. Notice that many systems will require the complete path to the -YAP binary. The @code{-L} flag indicates that YAP should consult the -current file when booting and then halt. The remaining arguments are -then passed to YAP. Note that YAP will skip the first lines if they -start with @code{#} (the comment sign for Unix's shell). YAP will -consult the file and execute any commands. - -A slightly more sophisticated example is: - -@example -@cartouche -#!/usr/bin/yap -L -- -# -# Hello World script file using YAP -# . - -:- initialization(main). - -main :- write('Hello World'), nl. - -@end cartouche -@end example - -The @code{initialization} directive tells YAP to execute the goal main -after consulting the file. Source code is thus compiled and @code{main} -executed at the end. The @code{.} is useful while debugging the script -as a Prolog program: it guarantees that the syntax error will not -propagate to the Prolog code. - -Notice that the @code{--} is required so that the shell passes the extra -arguments to YAP. As an example, consider the following script -@code{dump_args}: - -@example -@cartouche -#!/usr/bin/yap -L -- -#. - -main( [] ). -main( [H|T] ) :- - write( H ), nl, - main( T ). - -:- unix( argv(AllArgs) ), main( AllArgs ). - -@end cartouche -@end example - -If you this run this script with the arguments: -@example -./dump_args -s 10000 -@end example -@noindent -the script will start an YAP process with stack size @code{10MB}, and -the list of arguments to the process will be empty. - -Often one wants to run the script as any other program, and for this it -is convenient to ignore arguments to YAP. This is possible by using -@code{L --} as in the next version of @code{dump_args}: - -@example -@cartouche -#!/usr/bin/yap -L -- - -main( [] ). -main( [H|T] ) :- - write( H ), nl, - main( T ). - -:- unix( argv(AllArgs) ), main( AllArgs ). - -@end cartouche -@end example - -The @code{--} indicates the next arguments are not for YAP. Instead, -they must be sent directly to the @code{argv} built-in. Hence, running -@example -./dump_args test -@end example -@noindent -will write @code{test} on the standard output. - - -@node Syntax, Loading Programs, Run, Top -@chapter Syntax - -We will describe the syntax of YAP at two levels. We first will -describe the syntax for Prolog terms. In a second level we describe -the @i{tokens} from which Prolog @i{terms} are -built. - -@menu -* Formal Syntax:: Syntax of terms -* Tokens:: Syntax of Prolog tokens -* Encoding:: How characters are encoded and Wide Character Support -@end menu - -@node Formal Syntax, Tokens, ,Syntax -@section Syntax of Terms -@cindex syntax - -Below, we describe the syntax of YAP terms from the different -classes of tokens defined above. The formalism used will be @emph{BNF}, -extended where necessary with attributes denoting integer precedence or -operator type. - -@example - -@code{ - term ----> subterm(1200) end_of_term_marker - - subterm(N) ----> term(M) [M <= N] - - term(N) ----> op(N, fx) subterm(N-1) - | op(N, fy) subterm(N) - | subterm(N-1) op(N, xfx) subterm(N-1) - | subterm(N-1) op(N, xfy) subterm(N) - | subterm(N) op(N, yfx) subterm(N-1) - | subterm(N-1) op(N, xf) - | subterm(N) op(N, yf) - - term(0) ----> atom '(' arguments ')' - | '(' subterm(1200) ')' - | '@{' subterm(1200) '@}' - | list - | string - | number - | atom - | variable - - arguments ----> subterm(999) - | subterm(999) ',' arguments - - list ----> '[]' - | '[' list_expr ']' - - list_expr ----> subterm(999) - | subterm(999) list_tail - - list_tail ----> ',' list_expr - | ',..' subterm(999) - | '|' subterm(999) -} -@end example - -@noindent -Notes: - -@itemize @bullet - -@item -@i{op(N,T)} denotes an atom which has been previously declared with type -@i{T} and base precedence @i{N}. - -@item -Since ',' is itself a pre-declared operator with type @i{xfy} and -precedence 1000, is @i{subterm} starts with a '(', @i{op} must be -followed by a space to avoid ambiguity with the case of a functor -followed by arguments, e.g.: - -@example -@code{ + (a,b) [the same as '+'(','(a,b)) of arity one]} -@end example -versus -@example -@code{ +(a,b) [the same as '+'(a,b) of arity two]} -@end example - -@item -In the first rule for term(0) no blank space should exist between -@i{atom} and '('. - -@item -@cindex end of term -Each term to be read by the YAP parser must end with a single -dot, followed by a blank (in the sense mentioned in the previous -paragraph). When a name consisting of a single dot could be taken for -the end of term marker, the ambiguity should be avoided by surrounding the -dot with single quotes. - -@end itemize - -@node Tokens, Encoding, Formal Syntax, Syntax -@section Prolog Tokens -@cindex token - -Prolog tokens are grouped into the following categories: - -@menu -* Numbers:: Integer and Floating-Point Numbers -* Strings:: Sequences of Characters -* Atoms:: Atomic Constants -* Variables:: Logical Variables -* Punctuation Tokens:: Tokens that separate other tokens -* Layout:: Comments and Other Layout Rules -@end menu - -@node Numbers, Strings, ,Tokens -@subsection Numbers -@cindex number - -Numbers can be further subdivided into integer and floating-point numbers. - -@menu -* Integers:: How Integers are read and represented -* Floats:: Floating Point Numbers -@end menu - -@node Integers, Floats, ,Numbers -@subsubsection Integers -@cindex integer - -Integer numbers -are described by the following regular expression: - -@example -@code{ - := @{+|0@{xXo@}@}+ -} -@end example -@noindent -where @{...@} stands for optionality, @i{+} optional repetition (one or -more times), @i{} denotes one of the characters 0 ... 9, @i{|} -denotes or, and @i{} denotes the character "'". The digits -before the @i{} character, when present, form the number -basis, that can go from 0, 1 and up to 36. Letters from @code{A} to -@code{Z} are used when the basis is larger than 10. - -Note that if no basis is specified then base 10 is assumed. Note also -that the last digit of an integer token can not be immediately followed -by one of the characters 'e', 'E', or '.'. - -Following the ISO standard, YAP also accepts directives of the -form @code{0x} to represent numbers in hexadecimal base and of the form -@code{0o} to represent numbers in octal base. For usefulness, -YAP also accepts directives of the form @code{0X} to represent -numbers in hexadecimal base. - -Example: -the following tokens all denote the same integer -@example -@code{10 2'1010 3'101 8'12 16'a 36'a 0xa 0o12} -@end example - -Numbers of the form @code{0'a} are used to represent character -constants. So, the following tokens denote the same integer: -@example -@code{0'd 100} -@end example - -YAP (version @value{VERSION}) supports integers that can fit -the word size of the machine. This is 32 bits in most current machines, -but 64 in some others, such as the Alpha running Linux or Digital -Unix. The scanner will read larger or smaller integers erroneously. - -@node Floats, , Integers,Numbers -@subsubsection Floating-point Numbers -@cindex floating-point number - -Floating-point numbers are described by: - -@example -@code{ - := +@{+@} - @{@}+ - |++ - @{@{@}+@} -} -@end example - -@noindent -where @i{} denotes the decimal-point character '.', -@i{} denotes one of 'e' or 'E', and @i{} denotes -one of '+' or '-'. - -Examples: -@example -@code{10.0 10e3 10e-3 3.1415e+3} -@end example - -Floating-point numbers are represented as a double in the target -machine. This is usually a 64-bit number. - -@node Strings, Atoms, Numbers,Tokens -@subsection Character Strings -@cindex string - -Strings are described by the following rules: -@example - string --> '"' string_quoted_characters '"' - - string_quoted_characters --> '"' '"' string_quoted_characters - string_quoted_characters --> '\' - escape_sequence string_quoted_characters - string_quoted_characters --> - string_character string_quoted_characters - - escape_sequence --> 'a' | 'b' | 'r' | 'f' | 't' | 'n' | 'v' - escape_sequence --> '\' | '"' | ''' | '`' - escape_sequence --> at_most_3_octal_digit_seq_char '\' - escape_sequence --> 'x' at_most_2_hexa_digit_seq_char '\' -@end example -where @code{string_character} in any character except the double quote -and escape characters. - -Examples: -@example -@code{"" "a string" "a double-quote:""" } -@end example - -The first string is an empty string, the last string shows the use of -double-quoting. The implementation of YAP represents strings as -lists of integers. Since YAP 4.3.0 there is no static limit on string -size. - -Escape sequences can be used to include the non-printable characters -@code{a} (alert), @code{b} (backspace), @code{r} (carriage return), -@code{f} (form feed), @code{t} (horizontal tabulation), @code{n} (new -line), and @code{v} (vertical tabulation). Escape sequences also be -include the meta-characters @code{\}, @code{"}, @code{'}, and -@code{`}. Last, one can use escape sequences to include the characters -either as an octal or hexadecimal number. - -The next examples demonstrates the use of escape sequences in YAP: - -@example -@code{"\x0c\" "\01\" "\f" "\\" } -@end example - -The first three examples return a list including only character 12 (form -feed). The last example escapes the escape character. - -Escape sequences were not available in C-Prolog and in original -versions of YAP up to 4.2.0. Escape sequences can be disable by using: -@example -@code{:- yap_flag(character_escapes,false).} -@end example - - -@node Atoms, Variables, Strings, Tokens -@subsection Atoms -@cindex atom - -Atoms are defined by one of the following rules: -@example - atom --> solo-character - atom --> lower-case-letter name-character* - atom --> symbol-character+ - atom --> single-quote single-quote - atom --> ''' atom_quoted_characters ''' - - - atom_quoted_characters --> ''' ''' atom_quoted_characters - atom_quoted_characters --> '\' atom_sequence string_quoted_characters - atom_quoted_characters --> character string_quoted_characters - -@end example - -where: -@example - denotes one of: ! ; - denotes one of: # & * + - . / : < - = > ? @@ \ ^ ` ~ - denotes one of: a...z - denotes one of: _ a...z A...Z 0....9 - denotes: ' -@end example - -and @code{string_character} denotes any character except the double quote -and escape characters. Note that escape sequences in strings and atoms -follow the same rules. - -Examples: -@example -@code{a a12x '$a' ! => '1 2'} -@end example - - -Version @code{4.2.0} of YAP removed the previous limit of 256 -characters on an atom. Size of an atom is now only limited by the space -available in the system. - -@node Variables, Punctuation Tokens, Atoms, Tokens -@subsection Variables -@cindex variable - -Variables are described by: -@example - + -@end example -where -@example - denotes one of: _ A...Z - denotes one of: _ a...z A...Z -@end example - -@cindex anonymous variable -If a variable is referred only once in a term, it needs not to be named -and one can use the character @code{_} to represent the variable. These -variables are known as anonymous variables. Note that different -occurrences of @code{_} on the same term represent @emph{different} -anonymous variables. - -@node Punctuation Tokens, Layout, Variables, Tokens -@subsection Punctuation Tokens -@cindex punctuation token - -Punctuation tokens consist of one of the following characters: -@example -( ) , [ ] @{ @} | -@end example - -These characters are used to group terms. - -@node Layout, ,Punctuation Tokens, Tokens -@subsection Layout -@cindex comment -Any characters with ASCII code less than or equal to 32 appearing before -a token are ignored. - -All the text appearing in a line after the character @i{%} is taken to -be a comment and ignored (including @i{%}). Comments can also be -inserted by using the sequence @code{/*} to start the comment and -@code{*/} to finish it. In the presence of any sequence of comments or -layout characters, the YAP parser behaves as if it had found a -single blank character. The end of a file also counts as a blank -character for this purpose. - -@node Encoding, , Tokens, Syntax -@section Wide Character Support -@cindex encodings - -@menu -* Stream Encoding:: How Prolog Streams can be coded -* BOM:: The Byte Order Mark -@end menu - -@cindex UTF-8 -@cindex Unicode -@cindex UCS -@cindex internationalization -YAP now implements a SWI-Prolog compatible interface to wide -characters and the Universal Character Set (UCS). The following text -was adapted from the SWI-Prolog manual. - -YAP now supports wide characters, characters with character -codes above 255 that cannot be represented in a single byte. -@emph{Universal Character Set} (UCS) is the ISO/IEC 10646 standard -that specifies a unique 31-bits unsigned integer for any character in -any language. It is a superset of 16-bit Unicode, which in turn is -a superset of ISO 8859-1 (ISO Latin-1), a superset of US-ASCII. UCS -can handle strings holding characters from multiple languages and -character classification (uppercase, lowercase, digit, etc.) and -operations such as case-conversion are unambiguously defined. - -For this reason YAP, following SWI-Prolog, has two representations for -atoms. If the text fits in ISO Latin-1, it is represented as an array -of 8-bit characters. Otherwise the text is represented as an array of -wide chars, which may take 16 or 32 bits. This representational issue -is completely transparent to the Prolog user. Users of the foreign -language interface sometimes need to be aware of these issues though. - -Character coding comes into view when characters of strings need to be -read from or written to file or when they have to be communicated to -other software components using the foreign language interface. In this -section we only deal with I/O through streams, which includes file I/O -as well as I/O through network sockets. - - -@node Stream Encoding, , BOM, Encoding -@subsection Wide character encodings on streams - - - -Although characters are uniquely coded using the UCS standard -internally, streams and files are byte (8-bit) oriented and there are a -variety of ways to represent the larger UCS codes in an 8-bit octet -stream. The most popular one, especially in the context of the web, is -UTF-8. Bytes 0...127 represent simply the corresponding US-ASCII -character, while bytes 128...255 are used for multi-byte -encoding of characters placed higher in the UCS space. Especially on -MS-Windows the 16-bit Unicode standard, represented by pairs of bytes is -also popular. - -Prolog I/O streams have a property called @emph{encoding} which -specifies the used encoding that influence @code{get_code/2} and -@code{put_code/2} as well as all the other text I/O predicates. - -The default encoding for files is derived from the Prolog flag -@code{encoding}, which is initialised from the environment. If the -environment variable @env{LANG} ends in "UTF-8", this encoding is -assumed. Otherwise the default is @code{text} and the translation is -left to the wide-character functions of the C-library (note that the -Prolog native UTF-8 mode is considerably faster than the generic -@code{mbrtowc()} one). The encoding can be specified explicitly in -@code{load_files/2} for loading Prolog source with an alternative -encoding, @code{open/4} when opening files or using @code{set_stream/2} on -any open stream (not yet implemented). For Prolog source files we also -provide the @code{encoding/1} directive that can be used to switch -between encodings that are compatible to US-ASCII (@code{ascii}, -@code{iso_latin_1}, @code{utf8} and many locales). -@c See also -@c \secref{intsrcfile} for writing Prolog files with non-US-ASCII -@c characters and \secref{unicodesyntax} for syntax issues. -For -additional information and Unicode resources, please visit -@uref{http://www.unicode.org/}. - -YAP currently defines and supports the following encodings: - -@table @code -@item octet -Default encoding for @emph{binary} streams. This causes -the stream to be read and written fully untranslated. - -@item ascii -7-bit encoding in 8-bit bytes. Equivalent to @code{iso_latin_1}, -but generates errors and warnings on encountering values above -127. - -@item iso_latin_1 -8-bit encoding supporting many western languages. This causes -the stream to be read and written fully untranslated. - -@item text -C-library default locale encoding for text files. Files are read and -written using the C-library functions @code{mbrtowc()} and -@code{wcrtomb()}. This may be the same as one of the other locales, -notably it may be the same as @code{iso_latin_1} for western -languages and @code{utf8} in a UTF-8 context. - -@item utf8 -Multi-byte encoding of full UCS, compatible to @code{ascii}. -See above. - -@item unicode_be -Unicode Big Endian. Reads input in pairs of bytes, most -significant byte first. Can only represent 16-bit characters. - -@item unicode_le -Unicode Little Endian. Reads input in pairs of bytes, least -significant byte first. Can only represent 16-bit characters. -@end table - -Note that not all encodings can represent all characters. This implies -that writing text to a stream may cause errors because the stream -cannot represent these characters. The behaviour of a stream on these -errors can be controlled using @code{open/4} or @code{set_stream/2} (not -implemented). Initially the terminal stream write the characters using -Prolog escape sequences while other streams generate an I/O exception. - - -@node BOM, Stream Encoding, , Encoding -@subsection BOM: Byte Order Mark - -@cindex BOM -@cindex Byte Order Mark -From @ref{Stream Encoding}, you may have got the impression text-files are -complicated. This section deals with a related topic, making live often -easier for the user, but providing another worry to the programmer. -@strong{BOM} or @emph{Byte Order Marker} is a technique for -identifying Unicode text-files as well as the encoding they use. Such -files start with the Unicode character @code{0xFEFF}, a non-breaking, -zero-width space character. This is a pretty unique sequence that is not -likely to be the start of a non-Unicode file and uniquely distinguishes -the various Unicode file formats. As it is a zero-width blank, it even -doesn't produce any output. This solves all problems, or ... - -Some formats start of as US-ASCII and may contain some encoding mark to -switch to UTF-8, such as the @code{encoding="UTF-8"} in an XML header. -Such formats often explicitly forbid the the use of a UTF-8 BOM. In -other cases there is additional information telling the encoding making -the use of a BOM redundant or even illegal. - -The BOM is handled by the @code{open/4} predicate. By default, text-files are -probed for the BOM when opened for reading. If a BOM is found, the -encoding is set accordingly and the property @code{bom(true)} is -available through @code{stream_property/2}. When opening a file for -writing, writing a BOM can be requested using the option -@code{bom(true)} with @code{open/4}. - -@node Loading Programs, Modules, Syntax, Top -@chapter Loading Programs - -@menu - -Loading Programs -* Compiling:: Program Loading and Updating -* Setting the Compiler:: Changing the compiler's parameters -* Conditional Compilation:: Compiling program fragments -* Saving:: Saving and Restoring Programs - -@end menu - - -@node Compiling, Setting the Compiler, , Loading Programs -@section Program loading and updating - -@table @code - -@item consult(@var{+F}) -@findex consult/1 -@snindex consult/1 -@cyindex consult/1 -Adds the clauses written in file @var{F} or in the list of files @var{F} -to the program. - -In YAP @code{consult/1} does not remove previous clauses for -the procedures defined in @var{F}. Moreover, note that all code in YAP -is compiled. - -@item reconsult(@var{+F}) -@findex reconsult/1 -@snindex reconsult/1 -@cyindex reconsult/1 -Updates the program replacing the -previous definitions for the predicates defined in @var{F}. - - -@item [@var{+F}] -@findex []/1 -@saindex []/1 -@cyindex []/1 -The same as @code{consult(F)}. - -@item [-@var{+F}] -@findex [-]/1 -@saindex [-]/1 -@cyindex [-]/1 -The same as @code{reconsult(F)} - -Example: - -@example -?- [file1, -file2, -file3, file4]. -@end example -@noindent -will consult @code{file1} @code{file4} and reconsult @code{file2} and -@code{file3}. - -@item compile(@var{+F}) -@findex compile/1 -@syindex compile/1 -@cnindex compile/1 -@noindent -In YAP, the same as @code{reconsult/1}. - -@item load_files(@var{+Files}, @var{+Options}) -@findex load_files/2 -@syindex load_files/2 -@cnindex load_files/2 -@noindent -General implementation of @code{consult}. Execution is controlled by the -following flags: - -@table @code -@item autoload(+@var{Autoload}) -SWI-compatible option where if @var{Autoload} is @code{true} predicates -are loaded on first call. Currently -not supported. -@item derived_from(+@var{File}) - SWI-compatible option to control make. Currently - not supported. -@item encoding(+@var{Encoding}) -Character encoding used in consulting files. Please @pxref{Encoding} for -supported encodings. - -@item expand(+@var{Bool}) - Not yet implemented. In SWI-Prolog, if @code{true}, run the - filenames through @code{expand_file_name/2} and load the returned - files. Default is false, except for @code{consult/1} which is - intended for interactive use. - -@item if(+@var{Condition}) - Load the file only if the specified @var{Condition} is - satisfied. The value @code{true} the file unconditionally, - @code{changed} loads the file if it was not loaded before, or has - been modified since it was loaded the last time, @code{not_loaded} - loads the file if it was not loaded before. - -@item imports(+@var{ListOrAll}) - If @code{all} and the file is a module file, import all public - predicates. Otherwise import only the named predicates. Each - predicate is referred to as @code{/}. This option has - no effect if the file is not a module file. - -@item must_be_module(+@var{Bool}) - If true, raise an error if the file is not a module file. Used by - @code{use_module/[1,2]}. - -@c qcompile(Bool) -@c If this call appears in a directive of a file that is compiled into Quick Load Format using qcompile/1 and this flag is true, the contents of the argument files are included in the .qlf file instead of the loading directive. - -@item silent(+@var{Bool}) - If true, load the file without printing a message. The specified value is the default for all files loaded as a result of loading the specified files. - -@item stream(+@var{Input}) - This SWI-Prolog extension compiles the data from the stream - @var{Input}. If this option is used, @var{Files} must be a single - atom which is used to identify the source-location of the loaded - clauses as well as remove all clauses if the data is re-consulted. - - This option is added to allow compiling from non-file locations such as databases, the web, the user (see consult/1) or other servers. - -@item compilation_mode(+@var{Mode}) - This extension controls how procedures are compiled. If @var{Mode} - is @code{compact} clauses are compiled and no source code is stored; - if it is @code{source} clauses are compiled and source code is stored; - if it is @code{assert_all} clauses are asserted into the data-base. - -@item comnsult(+@var{Mode}) - This extension controls the type of file to load. If @var{Mode} - is @code{consult}, clauses are added to the data-base, - is @code{reconsult}, clauses are recompiled, - is @code{db}, these are facts that need to be added to the data-base, - is @code{exo}, these are facts with atoms and integers that need a very compact representation. -@end table - -@item ensure_loaded(@var{+F}) [ISO] -@findex ensure_loaded/1 -@syindex compile/1 -@cnindex compile/1 -When the files specified by @var{F} are module files, -@code{ensure_loaded/1} loads them if they have note been previously -loaded, otherwise advertises the user about the existing name clashes -and prompts about importing or not those predicates. Predicates which -are not public remain invisible. - -When the files are not module files, @code{ensure_loaded/1} loads them -if they have not been loaded before, does nothing otherwise. - -@var{F} must be a list containing the names of the files to load. - -@item load_db(@var{+Files}) -@findex load_db/1 -@syindex load_db/1 -@cnindex load_db/1 -@noindent -Load a database of facts with equal structure. - -@item exo_files(@var{+Files}) -@findex exo_files/1 -@syindex exo_files/1 -@cnindex exo_files/1 -@noindent -Load compactly a database of facts with equal structure. Useful when wanting to -read in a very compact way database tables. - -@item make -@findex make/0 -@snindex make/0 -@cnindex make/0 - SWI-Prolog built-in to consult all source files that have been - changed since they were consulted. It checks all loaded source - files. make/0 can be combined with the compiler to speed up the - development of large packages. In this case compile the package - using - -@example - sun% pl -g make -o my_program -c file ... -@end example - - If `my_program' is started it will first reconsult all source files - that have changed since the compilation. - -@item include(@var{+F}) [ISO] -@findex include/1 (directive) -@snindex compile/1 (directive) -@cnindex compile/1 (directive) -The @code{include} directive includes the text files or sequence of text -files specified by @var{F} into the file being currently consulted. - -@end table - -@node Setting the Compiler, Conditional Compilation, Compiling, Loading Programs -@section Changing the Compiler's Behavior - -This section presents a set of built-ins predicates designed to set the -environment for the compiler. - -@table @code - -@item source_mode(-@var{O},+@var{N}) -@findex source_mode/2 -@snindex source_mode/2 -@cnindex source_mode/2 -The state of source mode can either be on or off. When the source mode -is on, all clauses are kept both as compiled code and in a "hidden" -database. @var{O} is unified with the previous state and the mode is set -according to @var{N}. - -@item source -@findex source/0 -@snindex source/0 -@cnindex source/0 -After executing this goal, YAP keeps information on the source -of the predicates that will be consulted. This enables the use of -@code{listing/0}, @code{listing/1} and @code{clause/2} for those -clauses. - -The same as @code{source_mode(_,on)} or as declaring all newly defined -static procedures as @code{public}. - -@item no_source -@findex no_source/0 -@snindex no_source/0 -@cnindex no_source/0 -The opposite to @code{source}. - -The same as @code{source_mode(_,off)}. - -@item compile_expressions -@findex compile_expressions/0 -@snindex compile_expressions/0 -@cnindex compile_expressions/0 -After a call to this predicate, arithmetical expressions will be compiled. -(see example below). This is the default behavior. - -@item do_not_compile_expressions -@findex do_not_compile_expressions/0 -@snindex do_not_compile_expressions/0 -@cnindex do_not_compile_expressions/0 -After a call to this predicate, arithmetical expressions will not be compiled. -@example -?- source, do_not_compile_expressions. -yes -?- [user]. -| p(X) :- X is 2 * (3 + 8). -| :- end_of_file. -?- compile_expressions. -yes -?- [user]. -| q(X) :- X is 2 * (3 + 8). -| :- end_of_file. -:- listing. - -p(A):- - A is 2 * (3 + 8). - -q(A):- - A is 22. -@end example - -@item hide(+@var{Atom}) -@findex hide/1 -@snindex hide/1 -@cnindex hide/1 -Make atom @var{Atom} invisible. - -@item unhide(+@var{Atom}) -@findex unhide/1 -@snindex unhide/1 -@cnindex unhide/1 -Make hidden atom @var{Atom} visible. - - -@item hide_predicate(+@var{Pred}) -@findex hide_predicate/1 -@snindex hide_predicate/1 -@cnindex hide_predicate/1 -Make predicate @var{Pred} invisible to @code{current_predicate/2}, -@code{listing}, and friends. - -@item stash_predicate(+@var{Pred}) -@findex stash_predicate/1 -@snindex stash_predicate/1 -@cnindex stash_predicate/1 -Make predicate @var{Pred} invisible to new code, and to @code{current_predicate/2}, -@code{listing}, and friends. New predicates with the same name and -functor can be declared. - -@item expand_exprs(-@var{O},+@var{N}) -@findex expand_exprs/2 -@snindex expand_exprs/2 -@cyindex expand_exprs/2 -Puts YAP in state @var{N} (@code{on} or @code{off}) and unify -@var{O} with the previous state, where @var{On} is equivalent to -@code{compile_expressions} and @code{off} is equivalent to -@code{do_not_compile_expressions}. This predicate was kept to maintain -compatibility with C-Prolog. - -@item path(-@var{D}) -@findex path/1 -@snindex path/1 -@cnindex path/1 -Unifies @var{D} with the current directory search-path of YAP. -Note that this search-path is only used by YAP to find the -files for @code{consult/1}, @code{reconsult/1} and @code{restore/1} and -should not be taken for the system search path. - -@item add_to_path(+@var{D}) -@findex add_to_path/1 -@snindex path/1 -@cnindex path/1 -Adds @var{D} to the end of YAP's directory search path. - -@item add_to_path(+@var{D},+@var{N}) -@findex add_to_path/2 -@snindex path/1 -@cnindex path/1 -Inserts @var{D} in the position, of the directory search path of -YAP, specified by @var{N}. @var{N} must be either of -@code{first} or @code{last}. - -@item remove_from_path(+@var{D}) -@findex remove_from_path/1 -@snindex remove_from_path/1 -@cnindex remove_from_path/1 -Remove @var{D} from YAP's directory search path. - -@item style_check(+@var{X}) -@findex style_check/1 -@snindex style_check/1 -@cnindex style_check/1 -Turns on style checking according to the attribute specified by @var{X}, -which must be one of the following: -@table @code -@item single_var -Checks single occurrences of named variables in a clause. -@item discontiguous -Checks non-contiguous clauses for the same predicate in a file. -@item multiple -Checks the presence of clauses for the same predicate in more than one -file when the predicate has not been declared as @code{multifile} -@item all -Performs style checking for all the cases mentioned above. -@end table -By default, style checking is disabled in YAP unless we are in -@code{sicstus} or @code{iso} language mode. - -The @code{style_check/1} built-in is now deprecated. Please use the -@code{set_prolog_flag/1} instead. - -@item no_style_check(+@var{X}) -@findex no_style_check/1 -@snindex style_check/1 -@cnindex style_check/1 -Turns off style checking according to the attribute specified by -@var{X}, which has the same meaning as in @code{style_check/1}. - -The @code{no_style_check/1} built-in is now deprecated. Please use the -@code{set_prolog_flag/1} instead. - -@item multifile @var{P} [ISO] -@findex multifile/1 (directive) -@syindex multifile/1 (directive) -@cnindex multifile/1 (directive) -Instructs the compiler about the declaration of a predicate @var{P} in -more than one file. It must appear in the first of the loaded files -where the predicate is declared, and before declaration of any of its -clauses. - -Multifile declarations affect @code{reconsult/1} and @code{compile/1}: -when a multifile predicate is reconsulted, only the clauses from the -same file are removed. - -Since YAP4.3.0 multifile procedures can be static or dynamic. - -@item discontiguous(+@var{G}) [ISO] -@findex discontiguous/1 (directive) -@syindex discontiguous/1 (directive) -@cnindex discontiguous/1 (directive) - -Declare that the arguments are discontiguous procedures, that is, -clauses for discontigous procedures may be separated by clauses from -other procedures. - -@item initialization(+@var{G}) [ISO] -@findex initialization/1 (directive) -@snindex initialization/1 (directive) -@cnindex initialization/1 (directive) -The compiler will execute goals @var{G} after consulting the current -file. - -@item initialization(+@var{Goal},+@var{When}) -@findex initialization/2 (directive) -@snindex initialization/2 (directive) -@cnindex initialization/2 (directive) -Similar to @code{initialization/1}, but allows for specifying when -@var{Goal} is executed while loading the program-text: - -@table @code -@item now - Execute @var{Goal} immediately. -@item after_load - Execute @var{Goal} after loading program-text. This is the same as initialization/1. -@item restore - Do not execute @var{Goal} while loading the program, but only when - restoring a state (not implemented yet). -@end table - -@item library_directory(+@var{D}) -@findex library_directory/1 -@snindex library_directory/1 -@cnindex library_directory/1 -Succeeds when @var{D} is a current library directory name. Library -directories are the places where files specified in the form -@code{library(@var{File})} are searched by the predicates -@code{consult/1}, @code{reconsult/1}, @code{use_module/1} or -@code{ensure_loaded/1}. - -@item file_search_path(+@var{NAME},-@var{DIRECTORY}) -@findex file_search_path/2 -@syindex file_search_path/2 -@cnindex file_search_path/2 -Allows writing file names as compound terms. The @var{NAME} and - @var{DIRECTORY} must be atoms. The predicate may generate multiple -solutions. The predicate is originally defined as follows: - -@example -file_search_path(library,A) :- - library_directory(A). -file_search_path(system,A) :- - prolog_flag(host_type,A). -@end example - -Thus, @code{[library(A)]} will search for a file using -@code{library_directory/1} to obtain the prefix. - -@item library_directory(+@var{D}) -@findex library_directory/1 -@snindex library_directory/1 -@cnindex library_directory/1 -Succeeds when @var{D} is a current library directory name. Library -directories are the places where files specified in the form -@code{library(@var{File})} are searched by the predicates -@code{consult/1}, @code{reconsult/1}, @code{use_module/1} or -@code{ensure_loaded/1}. - -@item prolog_file_name(+@var{Name},-@var{FullPath}) -@findex prolog_file_name/2 -@syindex prolog_file_name/1 -@cnindex prolog_file_name/2 -Unify @var{FullPath} with the absolute path YAP would use to consult -file @var{Name}. - -@item prolog_to_os_filename(+@var{PrologPath},-@var{OsPath}) -@findex prolog_to_os_filename/2 -@snindex prolog_to_os_filename/2 -@cnindex prolog_to_os_filename/2 - -This is an SWI-Prolog built-in. Converts between the internal Prolog -pathname conventions and the operating-system pathname conventions. The -internal conventions are Unix and this predicates is equivalent to =/2 -(unify) on Unix systems. On DOS systems it will change the -directory-separator, limit the filename length map dots, except for the -last one, onto underscores. - -@item expand_file_name(+@var{WildCard},-@var{List}) -@findex expand_file_name/2 -@snindex expand_file_name/2 -@cnindex expand_file_name/2 - -This is an SWI-Prolog built-in. Unify @var{List} with a sorted list of -files or directories matching @var{WildCard}. The normal Unix wildcard -constructs @t{?}, @t{*}, @t{[ ... ]} and @t{@{...@}} are recognised. The -interpretation of @t{@{...@}} is interpreted slightly different from the -C shell (csh(1)). The comma separated argument can be arbitrary -patterns, including @t{@{...@}} patterns. The empty pattern is legal as -well: @t{@{.pl,@}} matches either @t{.pl} or the empty string. - -If the pattern contains wildcard characters, only existing files and -directories are returned. Expanding a @emph{pattern'} without wildcard -characters returns the argument, regardless on whether or not it exists. - -Before expanding wildcards, the construct $var is expanded to the value -of the environment variable var and a possible leading ~ character is -expanded to the user's home directory. In Windows, the home directory is -determined as follows: if the environment variable @code{HOME} exists, -this is used. If the variables @code{HOMEDRIVE} and @code{HOMEPATH} -exist (Windows-NT), these are used. At initialisation, the system will -set the environment variable @code{HOME} to point to the YAP home -directory if neither @code{HOME} nor @code{HOMEPATH} and -@code{HOMEDRIVE} are defined. - - -@item public @var{P} [ISO extension] -@findex public/1 (directive) -@snindex public/1 (directive) -@cnindex public/1 (directive) -Instructs the compiler that the source of a predicate of a list of -predicates @var{P} must be kept. This source is then accessible through -the @code{clause/2} procedure and through the @code{listing} family of -built-ins. - -Note that all dynamic procedures are public. The @code{source} directive -defines all new or redefined predicates to be public. - -Since YAP4.3.0 multifile procedures can be static or dynamic. - -@end table - -@node Conditional Compilation, Saving, Setting the Compiler, Loading Programs - -@section Conditional Compilation - -@c \index{if, directive}% -Conditional compilation builds on the same principle as -@code{term_expansion/2}, @code{goal_expansion/2} and the expansion of -grammar rules to compile sections of the source-code -conditionally. One of the reasons for introducing conditional -compilation is to simplify writing portable code. -@c See \secref{dialect} -@c for more information. Here is a simple example: - -@c @table code -@c :- if(\+source_exports(library(lists), suffix/2)). - -@c suffix(Suffix, List) :- -@c append(_, Suffix, List). - -@c :- endif. -@c \end{code} - -Note that these directives can only be appear as separate terms in the -input. Typical usage scenarios include: - -@itemize @bullet - @item Load different libraries on different dialects - @item Define a predicate if it is missing as a system predicate - @item Realise totally different implementations for a particular - part of the code due to different capabilities. - @item Realise different configuration options for your software. -@end itemize - - -@table @code -@item if(+@var{Goal}) -@findex if/1 directive -@snindex if/1 -@cnindex if/1 -Compile subsequent code only if @var{Goal} succeeds. For enhanced -portability, @var{Goal} is processed by @code{expand_goal/2} before execution. -If an error occurs, the error is printed and processing proceeds as if -@var{Goal} has failed. - -@item else -@findex else/0 directive -@snindex else/0 -@cnindex else/0 -Start `else' branch. - -@item endif -@findex endif/0 directive -@snindex endif/0 -@cnindex endif/0 -End of conditional compilation. - -@item elif(+@var{Goal}) -@findex elif/1 directive -@snindex elif/1 -@cnindex elif/1 -Equivalent to @code{:- else. :-if(Goal) ... :- endif.} In a sequence -as below, the section below the first matching elif is processed, If -no test succeeds the else branch is processed. - -@example -:- if(test1). -section_1. -:- elif(test2). -section_2. -:- elif(test3). -section_3. -:- else. -section_else. -:- endif. -@end example - -@end table - -@node Saving, , Conditional Compilation, Loading Programs -@section Saving and Loading Prolog States - -@table @code -@item save(+@var{F}) -@findex save/1 -@snindex save/1 -@cyindex save/1 -Saves an image of the current state of YAP in file @var{F}. From -@strong{YAP4.1.3} onwards, YAP saved states are executable -files in the Unix ports. - -@item save(+@var{F},-@var{OUT}) -@findex save/2 -@snindex save/2 -@cnindex save/2 -Saves an image of the current state of YAP in file @var{F}. From -@strong{YAP4.1.3} onwards, YAP saved states are executable -files in the Unix ports. - -Unify @var{OUT} with 1 when saving the file and @var{OUT} with 0 when -restoring the saved state. - -@item save_program(+@var{F}) -@findex save_program/1 -@syindex save_program/1 -@cnindex save_program/1 -Saves an image of the current state of the YAP database in file -@var{F}. - -@item save_program(+@var{F}, :@var{G}) -@findex save_program/2 -@syindex save_program/2 -@cnindex save_program/2 -Saves an image of the current state of the YAP database in file -@var{F}, and guarantee that execution of the restored code will start by -trying goal @var{G}. - -@item qsave_program(+@var{F}, +@var{ListOfOpts}) -@findex qsave_program/2 -@syindex qsave_program/2 -@cnindex qsave_program/2 - -Saves the current state of the program to the file @var{File}. The -result is a resource archive containing a saved state that expresses -all Prolog data from the running program and all user-defined -resources. Depending on the stand_alone option, the resource is headed -by the emulator, a Unix shell script or nothing. Options is a list of -additional options: - -@table @code -@item stack(+@var{KBytes}) -Limit for the local and global stack. -@item trail(+@var{KBytes}) -Limit for the trail stack. -@item goal(:@var{Callable}) -Initialization goal for the new executable (see -g). -@c @item toplevel(:@var{Callable}) -@c Top-level goal for the new executable (see -t). -@item init_file(+@var{Atom}) -Default initialization file for the new executable. See -f. -@c class(+Class) -@c If runtime, only read resources from the state (default). If kernel, lock all predicates as system predicates. If development, save the predicates in their current state and keep reading resources from their source (if present). See also resource/3. -@c autoload(+Boolean) -@c If true (default), run autoload/0 first. -@c map(+File) -@c Dump a human-readable trace of what has been saved in File. -@c op(+Action) -@c One of save (default) to save the current operator table or standard to use the initial table of the emulator. -@c stand_alone(+Boolean) -@c If true, the emulator is the first part of the state. If the emulator is started it will test whether a boot-file (state) is attached to the emulator itself and load this state. Provided the application has all libraries loaded, the resulting executable is completely independent of the runtime environment or location where it was built. See also section 2.10.2.4. -@c emulator(+File) -@c File to use for the emulator. Default is the running Prolog image. -@c foreign(+Action) -@c If save, include shared objects (DLLs) into the saved state. See current_foreign_library/2. If the program strip is available, this is first used to reduce the size of the shared object. If a state is started, use_foreign_library/1 first tries to locate the foreign resource in the executable. When found it copies the content of the resource to a temporary file and loads it. If possible (Unix), the temporary object is deleted immediately after opening.106 -@end table - -@item restore(+@var{F}) -@findex restore/1 -@syindex restore/1 -@cnindex restore/1 -Restores a previously saved state of YAP from file @var{F}. - -YAP always tries to find saved states from the current directory -first. If it cannot it will use the environment variable YAPLIBDIR, if -defined, or search the default library directory. -@end table - - -@node Modules, Built-ins, Loading Programs, Top -@chapter The Module System - -Module systems are quite important for the development of large -applications. YAP implements a module system compatible with the Quintus -Prolog module system. - -The YAP module system is predicate-based. This means a module consists -of a set of predicates (or procedures), such that some predicates are -public and the others are local to a module. Atoms and terms in general -are global to the system. Moreover, the module system is flat, meaning -that we do not support a hierarchy of modules. Modules can -automatically import other modules, though. For compatibility with other -module systems the YAP module system is non-strict, meaning both that -there is a way to access predicates private to a module and that it -is possible to declare predicates for a module from some other module. - -YAP allows one to ignore the module system if one does not want to use -it. Last note that using the module system does not introduce any -significant overheads. - -@menu - -* Module Concepts:: The Key Ideas in Modules -* Defining Modules:: How To Define a New Module -* Using Modules:: How to Use a Module -* Meta-Predicates in Modules:: How to Handle New Meta-Predicates -* Re-Exporting Modules:: How to Re-export Predicates From Other Modules - -@end menu - -@node Module Concepts, Defining Modules, , Modules -@section Module Concepts - -The YAP module system applies to predicates. All predicates belong to a -module. System predicates belong to the module @code{primitives}, and by -default new predicates belong to the module @code{user}. Predicates from -the module @code{primitives} are automatically visible to every module. - -Every predicate must belong to a module. This module is called its -@emph{source module}. - -By default, the source module for a clause occurring in a source file -with a module declaration is the declared module. For goals typed in -a source file without module declarations, their module is the module -the file is being loaded into. If no module declarations exist, this is -the current @emph{type-in module}. The default type-in module is -@code{user}, but one can set the current module by using the built-in -@code{module/1}. - -Note that in this module system one can explicitly specify the source -mode for a clause by prefixing a clause with its module, say: -@example -user:(a :- b). -@end example -@noindent -In fact, to specify the source module for a clause it is sufficient to -specify the source mode for the clause's head: -@example -user:a :- b. -@end example -@noindent - -The rules for goals are similar. If a goal appears in a text file with a -module declaration, the goal's source module is the declared -module. Otherwise, it is the module the file is being loaded into or the -type-in module. - -One can override this rule by prefixing a goal with the module it is -supposed to be executed in, say: -@example -nasa:launch(apollo,13). -@end example -will execute the goal @code{launch(apollo,13)} as if the current source -module was @code{nasa}. - -Note that this rule breaks encapsulation and should be used with care. - -@node Defining Modules, Using Modules, Module Concepts, Modules -@section Defining a New Module - -A new module is defined by a @code{module} declaration: - -@table @code - -@item module(+@var{M},+@var{L}) -@findex module/2 (directive) -@syindex module/2 (directive) -@cnindex module/2 (directive) -This directive defines the file where it appears as a module file; it -must be the first declaration in the file. -@var{M} must be an atom specifying the module name; @var{L} must be a list -containing the module's public predicates specification, in the form -@code{[predicate_name/arity,...]}. - -The public predicates of a module file can be made accessible by other -files through the directives @code{use_module/1}, @code{use_module/2}, -@code{ensure_loaded/1} and the predicates @code{consult/1} or -@code{reconsult/1}. The non-public predicates -of a module file are not visible by other files; they can, however, be -accessed by prefixing the module name with the -@code{:/2} operator. - -@end table - -The built-in @code{module/1} sets the current source module: -@table @code - -@item module(+@var{M},+@var{L}, +@var{Options}) -@findex module/3 (directive) -@syindex module/3 (directive) -@cnindex module/3 (directive) -Similar to @code{module/2}, this directive defines the file where it -appears in as a module file; it must be the first declaration in the file. -@var{M} must be an atom specifying the module name; @var{L} must be a -list containing the module's public predicates specification, in the -form @code{[predicate_name/arity,...]}. - -The last argument @var{Options} must be a list of options, which can be: - -@table @code -@item filename - the filename for a module to import into the current module. - -@item library(file) - a library file to import into the current module. - -@item hide(@var{Opt}) - if @var{Opt} is @code{false}, keep source code for current module, if -@code{true}, disable. -@end table - -@item module(+@var{M}) -@findex module/1 -@syindex module/1 -@cnindex module/1 -Defines @var{M} to be the current working or type-in module. All files -which are not bound to a module are assumed to belong to the working -module (also referred to as type-in module). To compile a non-module -file into a module which is not the working one, prefix the file name -with the module name, in the form @code{@var{Module}:@var{File}}, when -loading the file. - -@item export(+@var{PredicateIndicator}) -@findex export/1 -@snindex export/1 -@cnindex export/1 - -Add predicates to the public list of the context module. This implies -the predicate will be imported into another module if this module is -imported with @code{use_module/[1,2]}. Note that predicates are normally -exported using the directive @code{module/2}. @code{export/1} is meant -to handle export from dynamically created modules. The directive argument -may also be a list of predicates. - -@item export_list(?@var{Mod},?@var{ListOfPredicateIndicator}) -@findex export_list/2 -@snindex export_list/2 -@cnindex export_list/2 - -The list @var{ListOfPredicateIndicator} contains all predicates exported -by module @var{Mod}. - -@end table - -@node Using Modules, Meta-Predicates in Modules, Defining Modules, Modules -@section Using Modules - -By default, all procedures to consult a file will load the modules -defined therein. The two following declarations allow one to import a -module explicitly. They differ on whether one imports all predicate -declared in the module or not. - -@table @code - -@item use_module(+@var{F}) -@findex use_module/1 -@syindex use_module/1 -@cnindex use_module/1 -Loads the files specified by @var{F}, importing all their public -predicates. Predicate name clashes are resolved by asking the user about -importing or not the predicate. A warning is displayed when @var{F} is -not a module file. - -@item use_module(+@var{F},+@var{L}) -@findex use_module/2 -@syindex use_module/2 -@cnindex use_module/2 -Loads the files specified by @var{F}, importing the predicates specified -in the list @var{L}. Predicate name clashes are resolved by asking the -user about importing or not the predicate. A warning is displayed when -@var{F} is not a module file. - -@item use_module(?@var{M},?@var{F},+@var{L}) -@findex use_module/3 -@syindex use_module/3 -@cnindex use_module/3 -If module @var{M} has been defined, import the procedures in @var{L} to -the current module. Otherwise, load the files specified by @var{F}, -importing the predicates specified in the list @var{L}. -@end table - - -@node Meta-Predicates in Modules, Re-Exporting Modules, Using Modules, Modules -@section Meta-Predicates in Modules - -The module system must know whether predicates operate on goals or -clauses. Otherwise, such predicates would call a goal in the module they -were defined, instead of calling it in the module they are currently -executing. So, for instance, consider a file example.pl: -@example -:- module(example,[a/1]). - -a(G) :- call(G) -@end example - -We import this module with @code{use_module(example)} into module -@code{user}. The expected behavior for a goal @code{a(p)} is to -execute goal @code{p} within the module @code{user}. However, -@code{a/1} will call @code{p} within module @code{example}. - -The @code{meta_predicate/1} declaration informs the system that some -arguments of a predicate are goals, clauses, clauses heads or other -terms related to a module, and that these arguments must be prefixed -with the current source module: - -@table @code - -@item meta_predicate @var{G1},....,@var{Gn} -@findex meta_predicate/1 (directive) -@syindex meta_predicate/1 (directive) -@cnindex meta_predicate/1 (directive) -Each @var{Gi} is a mode specification. - -If the argument is @code{:}, it does not refer directly to a predicate -but must be module expanded. If the argument is an integer, the argument -is a goal or a closure and must be expanded. Otherwise, the argument is -not expanded. Note that the system already includes declarations for all -built-ins. - -For example, the declaration for @code{call/1} and @code{setof/3} are: - -@example -:- meta_predicate call(0), setof(?,0,?). -@end example - -@end table - -The previous example is expanded to the following code which explains, -why the goal @code{a(p)} calls @code{p} in @code{example} and not in -@code{user}. The goal @code{call(G)} is expanded because of the -meta-predicate declaration for @code{call/1}. - -@example -:- module(example,[a/1]). - -a(G) :- call(example:G) -@end example - -By adding a meta-predicate declaration for @code{a/1}, the goal -@code{a(p)} in module user will be expanded to @code{a(user:p)} -thereby preserving the module information. - -@example -:- module(example,[a/1]). - -:- meta_predicate a(:). -a(G) :- call(G) -@end example - -An alternate mechanism is the directive @code{module_transparent/1} -offered for compatibility with SWI-Prolog. - -@table @code - -@item module_transparent +@var{Preds} -@findex module_transparent/1 (directive) -@syindex module_transparent/1 (directive) -@cnindex module_transparent/1 (directive) - @var{Preds} is a comma separated sequence of name/arity predicate - indicators (like - @code{dynamic/1}). Each goal associated with a transparent declared - predicate will inherit the context module from its parent goal. -@end table - - -@node Re-Exporting Modules, , Meta-Predicates in Modules, Modules -@section Re-Exporting Predicates From Other Modules - -It is sometimes convenient to re-export predicates originally defined in -a different module. This is often useful if you are adding to the -functionality of a module, or if you are composing a large module with -several small modules. The following declarations can be used for that purpose: - -@table @code - -@item reexport(+@var{F}) -@findex reexport/1 -@snindex reexport/1 -@cnindex reexport/1 -Export all predicates defined in file @var{F} as if they were defined in -the current module. - -@item reexport(+@var{F},+@var{Decls}) -@findex reexport/2 -@snindex reexport/2 -@cnindex reexport/2 -Export predicates defined in file @var{F} according to @var{Decls}. The -declarations may be of the form: -@itemize @bullet -@item A list of predicate declarations to be exported. Each declaration -may be a predicate indicator or of the form ``@var{PI} @code{as} -@var{NewName}'', meaning that the predicate with indicator @var{PI} is -to be exported under name @var{NewName}. -@item @code{except}(@var{List}) -In this case, all predicates not in @var{List} are exported. Moreover, -if ``@var{PI} @code{as} @var{NewName}'' is found, the predicate with -indicator @var{PI} is to be exported under name @var{NewName}@ as -before. -@end itemize -@end table - -Re-exporting predicates must be used with some care. Please, take into -account the following observations: - -@itemize @bullet -@item -The @code{reexport} declarations must be the first declarations to -follow the @code{module} declaration. -@item -It is possible to use both @code{reexport} and @code{use_module}, but -all predicates reexported are automatically available for use in the -current module. -@item -In order to obtain efficient execution, YAP compiles dependencies -between re-exported predicates. In practice, this means that changing a -@code{reexport} declaration and then @strong{just} recompiling the file -may result in incorrect execution. -@end itemize - - -@node Built-ins, Library, Modules, Top - -@chapter Built-In Predicates - -@menu - -Built-ins, Debugging, Syntax, Top -* Control:: Controlling the Execution of Prolog Programs -* Undefined Procedures:: Handling calls to Undefined Procedures -* Messages:: Message Handling in YAP -* Testing Terms:: Predicates on Terms -* Predicates on Atoms:: Manipulating Atoms -* Predicates on Characters:: Manipulating Characters -* Comparing Terms:: Comparison of Terms -* Arithmetic:: Arithmetic in YAP -* I/O:: Input/Output with YAP -* Database:: Modifying Prolog's Database -* Sets:: Finding All Possible Solutions -* Grammars:: Grammar Rules -* Preds:: Predicate Information -* OS:: Access to Operating System Functionality -* Term Modification:: Updating Prolog Terms -* Global Variables:: Manipulating Global Variables -* Profiling:: Profiling Prolog Execution -* Call Counting:: Limiting the Maximum Number of Reductions -* Arrays:: Supporting Global and Local Arrays -* Preds:: Information on Predicates -* Misc:: Miscellaneous Predicates - -@end menu - -@node Control, Undefined Procedures, , Top -@section Control Predicates - - -This chapter describes the predicates for controlling the execution of -Prolog programs. - -In the description of the arguments of functors the following notation -will be used: - -@itemize @bullet -@item -a preceding plus sign will denote an argument as an "input argument" - -it cannot be a free variable at the time of the call; -@item - a preceding minus sign will denote an "output argument"; -@item -an argument with no preceding symbol can be used in both ways. -@end itemize - - -@table @code - -@item +@var{P}, +@var{Q} [ISO] -@findex ,/2 -@syindex ,/2 -@cyindex ,/2 -Conjunction of goals (and). - -@noindent -Example: -@example - p(X) :- q(X), r(X). -@end example - -@noindent -should be read as "p(@var{X}) if q(@var{X}) and r(@var{X})". - -@item +@var{P} ; +@var{Q} [ISO] -@findex ;/2 -@syindex ;/2 -@cyindex ;/2 -Disjunction of goals (or). - -@noindent -Example: -@example - p(X) :- q(X); r(X). -@end example -@noindent -should be read as "p(@var{X}) if q(@var{X}) or r(@var{X})". - -@item true [ISO] -@findex true/0 -@syindex true/0 -@cyindex true/0 -Succeeds once. - -@item fail [ISO] -@findex fail/0 -@syindex fail/0 -@cyindex fail/0 -Fails always. - -@item false [ISO] -@findex false/0 -@syindex false/0 -@cnindex false/0 -The same as fail - -@item ! [ISO] -@findex !/0 -@syindex !/0 -@cyindex !/0 - Read as "cut". Cuts any choices taken in the current procedure. -When first found "cut" succeeds as a goal, but if backtracking should -later return to it, the parent goal (the one which matches the head of -the clause containing the "cut", causing the clause activation) will -fail. This is an extra-logical predicate and cannot be explained in -terms of the declarative semantics of Prolog. - -example: - -@example - member(X,[X|_]). - member(X,[_|L]) :- member(X,L). -@end example - -@noindent -With the above definition - -@example - ?- member(X,[1,2,3]). -@end example - -@noindent -will return each element of the list by backtracking. With the following -definition: - -@example - member(X,[X|_]) :- !. - member(X,[_|L]) :- member(X,L). -@end example - -@noindent -the same query would return only the first element of the -list, since backtracking could not "pass through" the cut. - -@item \+ +@var{P} [ISO] -@findex \+/1 -@syindex \+/1 -@cyindex \+/1 -Goal @var{P} is not provable. The execution of this predicate fails if -and only if the goal @var{P} finitely succeeds. It is not a true logical -negation, which is impossible in standard Prolog, but -"negation-by-failure". - -@noindent -This predicate might be defined as: -@example - \+(P) :- P, !, fail. - \+(_). -@end example -@noindent -if @var{P} did not include "cuts". - -@item not +@var{P} -@findex not/1 -@snindex not/1 -@cyindex not/1 -Goal @var{P} is not provable. The same as @code{'\+ @var{P}'}. - -This predicate is kept for compatibility with C-Prolog and previous -versions of YAP. Uses of @code{not/1} should be replace by -@code{(\+)/1}, as YAP does not implement true negation. - -@item +@var{P} -> +@var{Q} [ISO] -@findex ->/2 -@syindex ->/2 -@cnindex ->/2 -Read as "if-then-else" or "commit". This operator is similar to the -conditional operator of imperative languages and can be used alone or -with an else part as follows: - -@table @code -@item +P -> +Q -"if P then Q". -@item +P -> +Q; +R -"if P then Q else R". -@end table - -@noindent -These two predicates could be defined respectively in Prolog as: -@example - (P -> Q) :- P, !, Q. -@end example -@noindent -and -@example - (P -> Q; R) :- P, !, Q. - (P -> Q; R) :- R. -@end example -@noindent -if there were no "cuts" in @var{P}, @var{Q} and @var{R}. - -Note that the commit operator works by "cutting" any alternative -solutions of @var{P}. - -Note also that you can use chains of commit operators like: -@example - P -> Q ; R -> S ; T. -@end example -@noindent -Note that @code{(->)/2} does not affect the scope of cuts in its -arguments. - -@item +@var{Condition} *-> +@var{Action} ; +@var{Else} -@findex ->*/2 -@snindex ->*/2 -@cnindex ->*/2 -This construct implements the so-called @emph{soft-cut}. The control is - defined as follows: If @var{Condition} succeeds at least once, the - semantics is the same as (@var{Condition}, @var{Action}). If - @var{Condition} does not succeed, the semantics is that of (\+ - @var{Condition}, @var{Else}). In other words, If @var{Condition} - succeeds at least once, simply behave as the conjunction of - @var{Condition} and @var{Action}, otherwise execute @var{Else}. - - The construct @var{A *-> B}, i.e. without an @var{Else} branch, is -translated as the normal conjunction @var{A}, @var{B}. - -@item repeat [ISO] -@findex repeat/0 -@syindex repeat/0 -@cyindex repeat/0 -Succeeds repeatedly. - -In the next example, @code{repeat} is used as an efficient way to implement -a loop. The next example reads all terms in a file: - -@example - a :- repeat, read(X), write(X), nl, X=end_of_file, !. -@end example -@noindent -the loop is effectively terminated by the cut-goal, when the test-goal -@code{X=end} succeeds. While the test fails, the goals @code{read(X)}, -@code{write(X)}, and @code{nl} are executed repeatedly, because -backtracking is caught by the @code{repeat} goal. - -The built-in @code{repeat/1} could be defined in Prolog by: -@example - repeat. - repeat :- repeat. -@end example - -@item call(+@var{P}) [ISO] -@findex call/1 -@syindex call/1 -@cyindex call/1 - If @var{P} is instantiated to an atom or a compound term, the goal -@code{call(@var{P})} is executed as if the value of @code{P} was found -instead of the call to @code{call/1}, except that any "cut" occurring in -@var{P} only cuts alternatives in the execution of @var{P}. - -@item incore(+@var{P}) -@findex incore/1 -@syindex incore/1 -@cnindex incore/1 -The same as @code{call/1}. - -@item call(+@var{Closure},...,?@var{Ai},...) [ISO] -@findex call/n -@snindex call/n -@cnindex call/n -Meta-call where @var{Closure} is a closure that is converted into a goal by -appending the @var{Ai} additional arguments. The number of arguments varies -between 0 and 10. - -@item call_with_args(+@var{Name},...,?@var{Ai},...) -@findex call_with_args/n -@snindex call_with_args/n -@cnindex call_with_args/n -Meta-call where @var{Name} is the name of the procedure to be called and -the @var{Ai} are the arguments. The number of arguments varies between 0 -and 10. New code should use @code{call/N} for better portability. - -If @var{Name} is a complex term, then @code{call_with_args/n} behaves as -@code{call/n}: - -@example -call(p(X1,...,Xm), Y1,...,Yn) :- p(X1,...,Xm,Y1,...,Yn). -@end example - - -@item +@var{P} - The same as @code{call(@var{P})}. This feature has been kept to provide -compatibility with C-Prolog. When compiling a goal, YAP -generates a @code{call(@var{X})} whenever a variable @var{X} is found as -a goal. - -@example - a(X) :- X. -@end example -@noindent -is converted to: -@example - a(X) :- call(X). -@end example - -@item if(?@var{G},?@var{H},?@var{I}) -@findex if/3 -@syindex if/3 -@cnindex if/3 -Call goal @var{H} once per each solution of goal @var{H}. If goal -@var{H} has no solutions, call goal @var{I}. - -The built-in @code{if/3} is similar to @code{->/3}, with the difference -that it will backtrack over the test goal. Consider the following -small data-base: - -@example -a(1). b(a). c(x). -a(2). b(b). c(y). -@end example - -Execution of an @code{if/3} query will proceed as follows: - -@example - ?- if(a(X),b(Y),c(Z)). - -X = 1, -Y = a ? ; - -X = 1, -Y = b ? ; - -X = 2, -Y = a ? ; - -X = 2, -Y = b ? ; - -no -@end example - - -@noindent -The system will backtrack over the two solutions for @code{a/1} and the -two solutions for @code{b/1}, generating four solutions. - -Cuts are allowed inside the first goal @var{G}, but they will only prune -over @var{G}. - -If you want @var{G} to be deterministic you should use if-then-else, as -it is both more efficient and more portable. - -@item once(:@var{G}) [ISO] -@findex once/1 -@snindex once/1 -@cnindex once/1 -Execute the goal @var{G} only once. The predicate is defined by: - -@example - once(G) :- call(G), !. -@end example - -@noindent -Note that cuts inside @code{once/1} can only cut the other goals inside -@code{once/1}. - -@item forall(:@var{Cond},:@var{Action}) -@findex forall/2 -@snindex forall/2 -@cnindex forall/2 -For all alternative bindings of @var{Cond} @var{Action} can be -proven. The example verifies that all arithmetic statements in the list -@var{L} are correct. It does not say which is wrong if one proves wrong. - -@example -?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), - Result =:= Formula). -@end example - -@item ignore(:@var{Goal}) -@findex ignore/1 -@snindex ignore/1 -@cnindex ignore/1 -Calls @var{Goal} as @code{once/1}, but succeeds, regardless of whether -@code{Goal} succeeded or not. Defined as: - -@example -ignore(Goal) :- - Goal, !. -ignore(_). -@end example - -@item abort -@findex abort/0 -@syindex abort/0 -@cyindex abort/0 -Abandons the execution of the current goal and returns to top level. All -break levels (see @code{break/0} below) are terminated. It is mainly -used during debugging or after a serious execution error, to return to -the top-level. - - -@item break -@findex break/0 -@syindex break/0 -@cyindex break/0 -Suspends the execution of the current goal and creates a new execution -level similar to the top level, displaying the following message: - -@example - [ Break (level ) ] -@end example -@noindent -telling the depth of the break level just entered. To return to the -previous level just type the end-of-file character or call the -end_of_file predicate. This predicate is especially useful during -debugging. - -@item halt [ISO] -@findex halt/0 -@syindex halt/0 -@cyindex halt/0 -Halts Prolog, and exits to the calling application. In YAP, -@code{halt/0} returns the exit code @code{0}. - -@item halt(+ @var{I}) [ISO] -@findex halt/1 -@syindex halt/1 -@cnindex halt/1 -Halts Prolog, and exits to the calling application returning the code -given by the integer @var{I}. - -@item catch(+@var{Goal},+@var{Exception},+@var{Action}) [ISO] -@findex catch/3 -@snindex catch/3 -@cnindex catch/3 -The goal @code{catch(@var{Goal},@var{Exception},@var{Action})} tries to -execute goal @var{Goal}. If during its execution, @var{Goal} throws an -exception @var{E'} and this exception unifies with @var{Exception}, the -exception is considered to be caught and @var{Action} is executed. If -the exception @var{E'} does not unify with @var{Exception}, control -again throws the exception. - -The top-level of YAP maintains a default exception handler that -is responsible to capture uncaught exceptions. - -@item throw(+@var{Ball}) [ISO] -@findex throw/1 -@snindex throw/1 -@cnindex throw/1 -The goal @code{throw(@var{Ball})} throws an exception. Execution is -stopped, and the exception is sent to the ancestor goals until reaching -a matching @code{catch/3}, or until reaching top-level. - -@item garbage_collect -@findex garbage_collect/0 -@syindex garbage_collect/0 -@cnindex garbage_collect/0 -The goal @code{garbage_collect} forces a garbage collection. - -@item garbage_collect_atoms -@findex garbage_collect_atoms/0 -@syindex garbage_collect_atoms/0 -@cnindex garbage_collect_atoms/0 -The goal @code{garbage_collect} forces a garbage collection of the atoms -in the data-base. Currently, only atoms are recovered. - -@item gc -@findex gc/0 -@syindex gc/0 -@cnindex gc/0 -The goal @code{gc} enables garbage collection. The same as -@code{yap_flag(gc,on)}. - -@item nogc -@findex nogc/0 -@syindex nogc/0 -@cnindex nogc/0 -The goal @code{nogc} disables garbage collection. The same as -@code{yap_flag(gc,off)}. - -@item grow_heap(+@var{Size}) -@snindex grow_heap/1 -@cnindex grow_heap/1 -Increase heap size @var{Size} kilobytes. - -@item grow_stack(+@var{Size}) -@findex grow_stack/1 -@snindex grow_stack/1 -@cnindex grow_stack/1 -Increase stack size @var{Size} kilobytes. - -@end table - -@node Undefined Procedures, Messages, Control, Top -@section Handling Undefined Procedures - -A predicate in a module is said to be undefined if there are no clauses -defining the predicate, and if the predicate has not been declared to be -dynamic. What YAP does when trying to execute undefined predicates can -be specified in three different ways: -@itemize @bullet -@item By setting an YAP flag, through the @code{yap_flag/2} or -@code{set_prolog_flag/2} built-ins. This solution generalizes the -ISO standard. -@item By using the @code{unknown/2} built-in (this solution is -compatible with previous releases of YAP). -@item By defining clauses for the hook predicate -@code{user:unknown_predicate_handler/3}. This solution is compatible -with SICStus Prolog. -@end itemize - -In more detail: -@table @code -@item unknown(-@var{O},+@var{N}) -@findex unknown/2 -@saindex unknown/2 -@cnindex unknown/2 -Specifies an handler to be called is a program tries to call an -undefined static procedure @var{P}. - -The arity of @var{N} may be zero or one. If the arity is @code{0}, the -new action must be one of @code{fail}, @code{warning}, or -@code{error}. If the arity is @code{1}, @var{P} is an user-defined -handler and at run-time, the argument to the handler @var{P} will be -unified with the undefined goal. Note that @var{N} must be defined prior -to calling @code{unknown/2}, and that the single argument to @var{N} must -be unbound. - -In YAP, the default action is to @code{fail} (note that in the ISO -Prolog standard the default action is @code{error}). - -After defining @code{undefined/1} by: -@example -undefined(A) :- format('Undefined predicate: ~w~n',[A]), fail. -@end example -@noindent -and executing the goal: -@example -unknown(U,undefined(X)). -@end example -@noindent -a call to a predicate for which no clauses were defined will result in -the output of a message of the form: -@example -Undefined predicate: user:xyz(A1,A2) -@end example -@noindent -followed by the failure of that call. - -@item yap_flag(unknown,+@var{SPEC}) -Alternatively, one can use @code{yap_flag/2}, -@code{current_prolog_flag/2}, or @code{set_prolog_flag/2}, to set this -functionality. In this case, the first argument for the built-ins should -be @code{unknown}, and the second argument should be either -@code{error}, @code{warning}, @code{fail}, or a goal. - -@item user:unknown_predicate_handler(+G,+M,?NG) -@findex unknown_predicate_handler/3 -@syindex unknown_predicate_handler/3 -@cnindex unknown_predicate_handler/3 -The user may also define clauses for -@code{user:unknown_predicate_handler/3} hook predicate. This -user-defined procedure is called before any system processing for the -undefined procedure, with the first argument @var{G} set to the current -goal, and the second @var{M} set to the current module. The predicate -@var{G} will be called from within the user module. - -If @code{user:unknown_predicate_handler/3} succeeds, the system will -execute @var{NG}. If @code{user:unknown_predicate_handler/3} fails, the -system will execute default action as specified by @code{unknown/2}. - -@item exception(+@var{Exception}, +@var{Context}, -@var{Action}) -@findex exception/3 -@syindex exception/3 -@cnindex exception/3 - Dynamic predicate, normally not defined. Called by the Prolog system on run-time exceptions that can be repaired `just-in-time'. The values for @var{Exception} are described below. See also @code{catch/3} and @code{throw/1}. -If this hook predicate succeeds it must instantiate the @var{Action} argument to the atom @code{fail} to make the operation fail silently, @code{retry} to tell Prolog to retry the operation or @code{error} to make the system generate an exception. The action @code{retry} only makes sense if this hook modified the environment such that the operation can now succeed without error. - -@table @code -@item undefined_predicate -@var{Context} is instantiated to a predicate-indicator (@var{Module:Name/Arity}). If the predicate fails Prolog will generate an existence_error exception. The hook is intended to implement alternatives to the SWI built-in autoloader, such as autoloading code from a database. Do not use this hook to suppress existence errors on predicates. See also @code{unknown}. -@item undefined_global_variable -@var{Context} is instantiated to the name of the missing global variable. The hook must call @code{nb_setval/2} or @code{b_setval/2} before returning with the action retry. -@end table - -@end table - -@node Messages, Testing Terms, Undefined Procedures, Top -@section Message Handling - -The interaction between YAP and the user relies on YAP's ability to -portray messages. These messages range from prompts to error -information. All message processing is performed through the builtin -@code{print_message/2}, in two steps: - -@itemize @bullet -@item The message is processed into a list of commands -@item The commands in the list are sent to the @code{format/3} builtin -in sequence. -@end itemize - -The first argument to @code{print_message/2} specifies the importance of -the message. The options are: - -@table @code -@item error -error handling -@item warning -compilation and run-time warnings, -@item informational -generic informational messages -@item help -help messages (not currently implemented in YAP) -@item query -query used in query processing (not currently implemented in YAP) -@item silent -messages that do not produce output but that can be intercepted by hooks. -@end table - -The next table shows the main predicates and hooks associated to message -handling in YAP: -@table @code -@item print_message(+@var{Kind}, @var{Term}) -@findex print_message/2 -@syindex print_message/2 -@cnindex print_message/2 -The predicate print_message/2 is used to print messages, notably from -exceptions in a human-readable format. @var{Kind} is one of -@code{informational}, @code{banner}, @code{warning}, @code{error}, -@code{help} or @code{silent}. A human-readable message is printed to -the stream @code{user_error}. - -@c \index{silent}\index{quiet}% -If the Prolog flag @code{verbose} is @code{silent}, messages with -@var{Kind} @code{informational}, or @code{banner} are treated as -silent.@c See \cmdlineoption{-q}. - -This predicate first translates the @var{Term} into a list of `message -lines' (see @code{print_message_lines/3} for details). Next it will -call the hook @code{message_hook/3} to allow the user intercepting the -message. If @code{message_hook/3} fails it will print the message unless -@var{Kind} is silent. - -@c The print_message/2 predicate and its rules are in the file -@c \file{/boot/messages.pl}, which may be inspected for more -@c information on the error messages and related error terms. -If you need to report errors from your own predicates, we advise you to -stick to the existing error terms if you can; but should you need to -invent new ones, you can define corresponding error messages by -asserting clauses for @code{prolog:message/2}. You will need to declare -the predicate as multifile. - -@c See also message_to_string/2. - -@item print_message_lines(+@var{Stream}, +@var{Prefix}, +@var{Lines}) -@findex print_message_lines/3 -@syindex print_message_lines/3 -@cnindex print_message_lines/3 -Print a message (see @code{print_message/2}) that has been translated to -a list of message elements. The elements of this list are: - -@table @code - @item @code{}-@code{} - Where @var{Format} is an atom and @var{Args} is a list - of format argument. Handed to @code{format/3}. - @item @code{flush} - If this appears as the last element, @var{Stream} is flushed - (see @code{flush_output/1}) and no final newline is generated. - @item @code{at_same_line} - If this appears as first element, no prefix is printed for - the first line and the line-position is not forced to 0 - (see @code{format/1}, @code{~N}). - @item @code{} - Handed to @code{format/3} as @code{format(Stream, Format, [])}. - @item nl - A new line is started and if the message is not complete - the @var{Prefix} is printed too. -@end table - -@item user:message_hook(+@var{Term}, +@var{Kind}, +@var{Lines}) -@findex message_hook/3 -@syindex message_hook/3 -@cnindex message_hook/3 -Hook predicate that may be define in the module @code{user} to intercept -messages from @code{print_message/2}. @var{Term} and @var{Kind} are the -same as passed to @code{print_message/2}. @var{Lines} is a list of -format statements as described with @code{print_message_lines/3}. - -This predicate should be defined dynamic and multifile to allow other -modules defining clauses for it too. - -@item message_to_string(+@var{Term}, -@var{String}) -@findex message_to_string/2 -@snindex message_to_string/2 -@cnindex message_to_string/2 -Translates a message-term into a string object. Primarily intended for SWI-Prolog emulation. -@end table - -@node Testing Terms, Predicates on Atoms, Messages, Top -@section Predicates on terms - -@table @code - -@item var(@var{T}) [ISO] -@findex var/1 -@syindex var/1 -@cyindex var/1 -Succeeds if @var{T} is currently a free variable, otherwise fails. - -@item atom(@var{T}) [ISO] -@findex atom/1 -@syindex atom/1 -@cyindex atom/1 -Succeeds if and only if @var{T} is currently instantiated to an atom. - -@item atomic(T) [ISO] -@findex atomic/1 -@syindex atomic/1 -@cyindex atomic/1 -Checks whether @var{T} is an atomic symbol (atom or number). - -@item compound(@var{T}) [ISO] -@findex compound/1 -@syindex compound/1 -@cnindex compound/1 -Checks whether @var{T} is a compound term. - -@item db_reference(@var{T}) -@findex db_reference/1C -@syindex db_reference/1 -@cyindex db_reference/1 -Checks whether @var{T} is a database reference. - -@item float(@var{T}) [ISO] -@findex float/1 -@syindex float/1 -@cnindex float/1 -Checks whether @var{T} is a floating point number. - -@item rational(@var{T}) -@findex rational/1 -@syindex rational/1 -@cyindex rational/1 -Checks whether @code{T} is a rational number. - -@item integer(@var{T}) [ISO] -@findex integer/1 -@syindex integer/1 -@cyindex integer/1 -Succeeds if and only if @var{T} is currently instantiated to an integer. - -@item nonvar(@var{T}) [ISO] -@findex nonvar/1 -@syindex nonvar/1 -@cyindex nonvar/1 -The opposite of @code{var(@var{T})}. - -@item number(@var{T}) [ISO] -@findex number/1 -@syindex number/1 -@cyindex number/1 -Checks whether @code{T} is an integer, rational or a float. - -@item primitive(@var{T}) -@findex primitive/1 -@syindex primitive/1 -@cyindex primitive/1 -Checks whether @var{T} is an atomic term or a database reference. - -@item simple(@var{T}) -@findex simple/1 -@syindex simple/1 -@cnindex simple/1 -Checks whether @var{T} is unbound, an atom, or a number. - -@item callable(@var{T}) [ISO] -@findex callable/1 -@syindex callable/1 -@cnindex callable/1 -Checks whether @var{T} is a callable term, that is, an atom or a -compound term. - -@item numbervars(@var{T},+@var{N1},-@var{Nn}) -@findex numbervars/3 -@syindex numbervars/3 -@cnindex numbervars/3 -Instantiates each variable in term @var{T} to a term of the form: -@code{'$VAR'(@var{I})}, with @var{I} increasing from @var{N1} to @var{Nn}. - -@item unnumbervars(@var{T},+@var{NT}) -@findex unnumbervars/2 -@syindex unnumbervars/2 -@cnindex unnumbervars/2 -Replace every @code{'$VAR'(@var{I})} by a free variable. - -@item ground(@var{T}) [ISO] -@findex ground/1 -@syindex ground/1 -@cnindex ground/1 -Succeeds if there are no free variables in the term @var{T}. - -@item acyclic_term(@var{T}) [ISO] -@findex acyclic_term/1 -@snindex acyclic_term/1 -@cnindex acyclic_term/1 -Succeeds if there are loops in the term @var{T}, that is, it is an infinite term. - -@item arg(+@var{N},+@var{T},@var{A}) [ISO] -@findex arg/3 -@syindex arg/3 -@cnindex arg/3 -Succeeds if the argument @var{N} of the term @var{T} unifies with -@var{A}. The arguments are numbered from 1 to the arity of the term. - -The current version will generate an error if @var{T} or @var{N} are -unbound, if @var{T} is not a compound term, of if @var{N} is not a positive -integer. Note that previous versions of YAP would fail silently -under these errors. - -@item functor(@var{T},@var{F},@var{N}) [ISO] -@findex functor/3 -@syindex functor/3 -@cyindex functor/3 -The top functor of term @var{T} is named @var{F} and has arity @var{N}. - -When @var{T} is not instantiated, @var{F} and @var{N} must be. If -@var{N} is 0, @var{F} must be an atomic symbol, which will be unified -with @var{T}. If @var{N} is not 0, then @var{F} must be an atom and -@var{T} becomes instantiated to the most general term having functor -@var{F} and arity @var{N}. If @var{T} is instantiated to a term then -@var{F} and @var{N} are respectively unified with its top functor name -and arity. - -In the current version of YAP the arity @var{N} must be an -integer. Previous versions allowed evaluable expressions, as long as the -expression would evaluate to an integer. This feature is not available -in the ISO Prolog standard. - -@item @var{T} =.. @var{L} [ISO] -@findex =../2 -@syindex =../2 -@cyindex =../2 -The list @var{L} is built with the functor and arguments of the term -@var{T}. If @var{T} is instantiated to a variable, then @var{L} must be -instantiated either to a list whose head is an atom, or to a list -consisting of just a number. - -@item @var{X} = @var{Y} [ISO] -@findex =/2 -@syindex =/2 -@cnindex =/2 -Tries to unify terms @var{X} and @var{Y}. - -@item @var{X} \= @var{Y} [ISO] -@findex \=/2 -@snindex \=/2 -@cnindex \=/2 -Succeeds if terms @var{X} and @var{Y} are not unifiable. - -@item unify_with_occurs_check(?T1,?T2) [ISO] -@findex unify_with_occurs_check/2 -@syindex unify_with_occurs_check/2 -@cnindex unify_with_occurs_check/2 -Obtain the most general unifier of terms @var{T1} and @var{T2}, if there -is one. - -This predicate implements the full unification algorithm. An example:n -@example -unify_with_occurs_check(a(X,b,Z),a(X,A,f(B)). -@end example -@noindent -will succeed with the bindings @code{A = b} and @code{Z = f(B)}. On the -other hand: -@example -unify_with_occurs_check(a(X,b,Z),a(X,A,f(Z)). -@end example -@noindent -would fail, because @code{Z} is not unifiable with @code{f(Z)}. Note that -@code{(=)/2} would succeed for the previous examples, giving the following -bindings @code{A = b} and @code{Z = f(Z)}. - - -@item copy_term(?@var{TI},-@var{TF}) [ISO] -@findex copy_term/2 -@syindex copy_term/2 -@cnindex copy_term/2 -Term @var{TF} is a variant of the original term @var{TI}, such that for -each variable @var{V} in the term @var{TI} there is a new variable @var{V'} -in term @var{TF}. Notice that: - -@itemize @bullet -@item suspended goals and attributes for attributed variables in - @var{TI} are also duplicated; -@item ground terms are shared between the new and the old term. -@end itemize - -If you do not want any sharing to occur please use -@code{duplicate_term/2}. - -@item duplicate_term(?@var{TI},-@var{TF}) -@findex duplicate_term/2 -@syindex duplicate_term/2 -@cnindex duplicate_term/2 -Term @var{TF} is a variant of the original term @var{TI}, such that -for each variable @var{V} in the term @var{TI} there is a new variable -@var{V'} in term @var{TF}, and the two terms do not share any -structure. All suspended goals and attributes for attributed variables -in @var{TI} are also duplicated. - -Also refer to @code{copy_term/2}. - -@item is_list(+@var{List}) -@findex is_list/1 -@syindex is_list/1 -@cnindex is_list/1 -True when @var{List} is a proper list. That is, @var{List} -is bound to the empty list (nil) or a term with functor '.' and arity 2. - -@item ?@var{Term1} =@@= ?@var{Term2} -@findex =@=/2 -@syindex =@=/2 -@cnindex =@=/2 - -Same as @code{variant/2}, succeeds if @var{Term1} and @var{Term2} are variant terms. - - -@item subsumes_term(?@var{Subsumer}, ?@var{Subsumed}) -@findex subsumes_term/2 -@syindex subsumes_term/2 -@cnindex subsumes_term/2 - -Succeed if @var{Submuser} subsumes @var{Subsuned} but does not bind any -variable in @var{Subsumer}. - -@item term_subsumer(?@var{T1}, ?@var{T2}, ?@var{Subsumer}) -@findex term_subsumer/2 -@syindex term_subsumer/2 -@cnindex term_subsumer/2 - -Succeed if @var{Subsumer} unifies with the least general -generalization over @var{T1} and -@var{T2}. - -@item term_variables(?@var{Term}, -@var{Variables}) [ISO] -@findex term_variables/2 -@syindex term_variables/2 -@cnindex term_variables/2 - -Unify @var{Variables} with the list of all variables of term -@var{Term}. The variables occur in the order of their first -appearance when traversing the term depth-first, left-to-right. - -@item rational_term_to_tree(?@var{TI},-@var{TF}) -@findex rational_term_to_tree/2 -@syindex rational_term_to_term/2 -@cnindex rational_term_to_tree/2 -The term @var{TF} is a tree representation (without cycles) for the - Prolog term @var{TI}. Loops are replaced by terms of the form - @code{_LOOP_(@var{LevelsAbove})} where @var{LevelsAbove} is the size of - the loop. - -@item tree_to_rational_term(?@var{TI},-@var{TF}) -@findex tree_to_rational_term/2 -@syindex tree_to_rational_term/2 -@cnindex tree_to_rational_term/2 -Inverse of above. The term @var{TI} is a tree representation (without - cycles) for the Prolog term @var{TF}. Loops replace terms of the form - @code{_LOOP_(@var{LevelsAbove})} where @var{LevelsAbove} is the size of - the loop. - - -@end table - -@node Predicates on Atoms, Predicates on Characters, Testing Terms, Top -@section Predicates on Atoms - -The following predicates are used to manipulate atoms: - -@table @code -@item name(@var{A},@var{L}) -@findex name/2 -@syindex name/2 -@cyindex name/2 -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument @var{A} will -be unified with an atomic symbol and @var{L} with the list of the ASCII -codes for the characters of the external representation of @var{A}. - -@example - name(yap,L). -@end example -@noindent -will return: -@example - L = [121,97,112]. -@end example -@noindent -and -@example - name(3,L). -@end example -@noindent -will return: -@example - L = [51]. -@end example - -@item atom_chars(?@var{A},?@var{L}) [ISO] -@findex atom_chars/2 -@saindex atom_chars/2 -@cnindex atom_chars/2 -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument @var{A} must -be unifiable with an atom, and the argument @var{L} with the list of the -characters of @var{A}. - -@item atom_codes(?@var{A},?@var{L}) [ISO] -@findex atom_codes/2 -@syindex atom_codes/2 -@cnindex atom_codes/2 -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument @var{A} will -be unified with an atom and @var{L} with the list of the ASCII -codes for the characters of the external representation of @var{A}. - -@item atom_concat(+@var{As},?@var{A}) -@findex atom_concat/2 -@syindex atom_concat/2 -@cnindex atom_concat/2 -The predicate holds when the first argument is a list of atoms, and the -second unifies with the atom obtained by concatenating all the atoms in -the first list. - -@item atomic_concat(+@var{As},?@var{A}) -@findex atomic_concat/2 -@snindex atomic_concat/2 -@cnindex atomic_concat/2 -The predicate holds when the first argument is a list of atomic terms, and -the second unifies with the atom obtained by concatenating all the -atomic terms in the first list. The first argument thus may contain -atoms or numbers. - -@item atomic_list_concat(+@var{As},?@var{A}) -@findex atomic_list_concat/2 -@snindex atomic_list_concat/2 -@cnindex atomic_list_concat/2 -The predicate holds when the first argument is a list of atomic terms, and -the second unifies with the atom obtained by concatenating all the -atomic terms in the first list. The first argument thus may contain -atoms or numbers. - -@item atomic_list_concat(?@var{As},+@var{Separator},?@var{A}) -@findex atomic_list_concat/3 -@snindex atomic_list_concat/3 -@cnindex atomic_list_concat/3 -Creates an atom just like @code{atomic_list_concat/2}, but inserts -@var{Separator} between each pair of atoms. For example: - -@example -?- atomic_list_concat([gnu, gnat], ', ', A). - -A = 'gnu, gnat' -@end example - -YAP emulates the SWI-Prolog version of this predicate that can also be -used to split atoms by instantiating @var{Separator} and @var{Atom} as -shown below. - -@example -?- atomic_list_concat(L, -, 'gnu-gnat'). - -L = [gnu, gnat] -@end example - -@item atom_length(+@var{A},?@var{I}) [ISO] -@findex atom_length/2 -@snindex atom_length/2 -@cnindex atom_length/2 -The predicate holds when the first argument is an atom, and the second -unifies with the number of characters forming that atom. - -@item atom_concat(?@var{A1},?@var{A2},?@var{A12}) [ISO] -@findex atom_concat/3 -@snindex atom_concat/3 -@cnindex atom_concat/3 -The predicate holds when the third argument unifies with an atom, and -the first and second unify with atoms such that their representations -concatenated are the representation for @var{A12}. - -If @var{A1} and @var{A2} are unbound, the built-in will find all the atoms -that concatenated give @var{A12}. - -@item number_chars(?@var{I},?@var{L}) [ISO] -@findex number_chars/2 -@saindex number_chars/2 -@cnindex number_chars/2 - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument @var{I} must -be unifiable with a number, and the argument @var{L} with the list of the -characters of the external representation of @var{I}. - -@item number_codes(?@var{A},?@var{L}) [ISO] -@findex number_codes/2 -@syindex number_codes/2 -@cnindex number_codes/2 -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument @var{A} -will be unified with a number and @var{L} with the list of the ASCII -codes for the characters of the external representation of @var{A}. - -@item atom_number(?@var{Atom},?@var{Number}) -@findex atom_number/2 -@syindex atom_number/2 -@cnindex atom_number/2 -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). If the argument -@var{Atom} is an atom, @var{Number} must be the number corresponding -to the characters in @var{Atom}, otherwise the characters in -@var{Atom} must encode a number @var{Number}. - -@item number_atom(?@var{I},?@var{L}) -@findex number_atom/2 -@snindex number_atom/2 -@cnindex number_atom/2 - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument @var{I} must -be unifiable with a number, and the argument @var{L} must be unifiable -with an atom representing the number. - -@item sub_atom(+@var{A},?@var{Bef}, ?@var{Size}, ?@var{After}, ?@var{At_out}) [ISO] -@findex sub_atom/5 -@snindex sub_atom/5 -@cnindex sub_atom/5 -True when @var{A} and @var{At_out} are atoms such that the name of -@var{At_out} has size @var{Size} and is a sub-string of the name of -@var{A}, such that @var{Bef} is the number of characters before and -@var{After} the number of characters afterwards. - -Note that @var{A} must always be known, but @var{At_out} can be unbound when -calling this built-in. If all the arguments for @code{sub_atom/5} but @var{A} -are unbound, the built-in will backtrack through all possible -sub-strings of @var{A}. - -@end table - -@node Predicates on Characters, Comparing Terms, Predicates on Atoms, Top -@section Predicates on Characters - -The following predicates are used to manipulate characters: - -@table @code -@item char_code(?@var{A},?@var{I}) [ISO] -@findex char_code/2 -@syindex char_code/2 -@cnindex char_code/2 -The built-in succeeds with @var{A} bound to character represented as an -atom, and @var{I} bound to the character code represented as an -integer. At least, one of either @var{A} or @var{I} must be bound before -the call. - -@item char_type(?@var{Char}, ?@var{Type}) -@findex char_type/2 -@snindex char_type/2 -@cnindex char_type/2 - Tests or generates alternative @var{Types} or @var{Chars}. The - character-types are inspired by the standard @code{C} - @code{} primitives. - -@table @code -@item alnum - @var{Char} is a letter (upper- or lowercase) or digit. - -@item alpha - @var{Char} is a letter (upper- or lowercase). - -@item csym - @var{Char} is a letter (upper- or lowercase), digit or the underscore (_). These are valid C- and Prolog symbol characters. - -@item csymf - @var{Char} is a letter (upper- or lowercase) or the underscore (_). These are valid first characters for C- and Prolog symbols - -@item ascii - @var{Char} is a 7-bits ASCII character (0..127). - -@item white - @var{Char} is a space or tab. E.i. white space inside a line. - -@item cntrl - @var{Char} is an ASCII control-character (0..31). - -@item digit - @var{Char} is a digit. - -@item digit(@var{Weight}) - @var{Char} is a digit with value - @var{Weight}. I.e. @code{char_type(X, digit(6))} yields @code{X = - '6'}. Useful for parsing numbers. - -@item xdigit(@var{Weight}) - @var{Char} is a hexa-decimal digit with value @var{Weight}. I.e. char_type(a, xdigit(X) yields X = '10'. Useful for parsing numbers. - -@item graph - @var{Char} produces a visible mark on a page when printed. Note that the space is not included! - -@item lower - @var{Char} is a lower-case letter. - -@item lower(Upper) - @var{Char} is a lower-case version of @var{Upper}. Only true if - @var{Char} is lowercase and @var{Upper} uppercase. - -@item to_lower(Upper) - @var{Char} is a lower-case version of Upper. For non-letters, or letter without case, @var{Char} and Lower are the same. See also upcase_atom/2 and downcase_atom/2. - -@item upper - @var{Char} is an upper-case letter. - -@item upper(Lower) - @var{Char} is an upper-case version of Lower. Only true if @var{Char} is uppercase and Lower lowercase. - -@item to_upper(Lower) - @var{Char} is an upper-case version of Lower. For non-letters, or letter without case, @var{Char} and Lower are the same. See also upcase_atom/2 and downcase_atom/2. - -@item punct - @var{Char} is a punctuation character. This is a graph character that is not a letter or digit. - -@item space - @var{Char} is some form of layout character (tab, vertical-tab, newline, etc.). - -@item end_of_file - @var{Char} is -1. - -@item end_of_line - @var{Char} ends a line (ASCII: 10..13). - -@item newline - @var{Char} is a the newline character (10). - -@item period - @var{Char} counts as the end of a sentence (.,!,?). - -@item quote - @var{Char} is a quote-character (", ', `). - -@item paren(Close) - @var{Char} is an open-parenthesis and Close is the corresponding close-parenthesis. -@end table - -@item code_type(?@var{Code}, ?@var{Type}) -@findex code_type/2 -@snindex code_type/2 -@cnindex code_type/2 - As @code{char_type/2}, but uses character-codes rather than - one-character atoms. Please note that both predicates are as - flexible as possible. They handle either representation if the - argument is instantiated and only will instantiate with an integer - code or one-character atom depending of the version used. See also - the prolog-flag @code{double_quotes} and the built-in predicates - @code{atom_chars/2} and @code{atom_codes/2}. - -@end table - -@node Comparing Terms, Arithmetic, Predicates on Characters, Top -@section Comparing Terms - -The following predicates are used to compare and order terms, using the -standard ordering: - -@itemize @bullet -@item -variables come before numbers, numbers come before atoms which in turn -come before compound terms, i.e.: variables @@< numbers @@< atoms @@< -compound terms. -@item -Variables are roughly ordered by "age" (the "oldest" variable is put -first); -@item -Floating point numbers are sorted in increasing order; -@item -Rational numbers are sorted in increasing order; -@item -Integers are sorted in increasing order; -@item -Atoms are sorted in lexicographic order; -@item -Compound terms are ordered first by arity of the main functor, then by -the name of the main functor, and finally by their arguments in -left-to-right order. -@end itemize - -@table @code - -@item compare(@var{C},@var{X},@var{Y}) [ISO] -@findex compare/3 -@syindex compare/3 -@cyindex compare/3 -As a result of comparing @var{X} and @var{Y}, @var{C} may take one of -the following values: - -@itemize @bullet -@item -@code{=} if @var{X} and @var{Y} are identical; -@item -@code{<} if @var{X} precedes @var{Y} in the defined order; -@item -@code{>} if @var{Y} precedes @var{X} in the defined order; -@end itemize - -@item @var{X} == @var{Y} [ISO] -@findex ==/2 -@syindex ==/2 -@cyindex ==/2 -Succeeds if terms @var{X} and @var{Y} are strictly identical. The -difference between this predicate and @code{=/2} is that, if one of the -arguments is a free variable, it only succeeds when they have already -been unified. - -@example -?- X == Y. -@end example -@noindent -fails, but, -@example -?- X = Y, X == Y. -@end example -@noindent -succeeds. -@example -?- X == 2. -@end example -@noindent -fails, but, -@example -?- X = 2, X == 2. -@end example -@noindent -succeeds. - - -@item @var{X} \== @var{Y} [ISO] -@findex \==/2 -@syindex \==/2 -@cyindex \==/2 -Terms @var{X} and @var{Y} are not strictly identical. - -@item @var{X} @@< @var{Y} [ISO] -@findex @@ @var{Y} [ISO] -@findex @@>/2 -@syindex @@>/2 -@cyindex @@>/2 -Term @var{X} follows term @var{Y} in the standard order. - -@item @var{X} @@>= @var{Y} [ISO] -@findex @@>=/2 -@syindex @@>=/2 -@cyindex @@>=/2 -Term @var{X} does not precede term @var{Y} in the standard order. - -@item sort(+@var{L},-@var{S}) [ISO] -@findex sort/2 -@syindex sort/2 -@cyindex sort/2 -Unifies @var{S} with the list obtained by sorting @var{L} and merging -identical (in the sense of @code{==}) elements. - -@item keysort(+@var{L},@var{S}) [ISO] -@findex keysort/2 -@syindex keysort/2 -@cyindex keysort/2 -Assuming L is a list of the form @code{@var{Key}-@var{Value}}, -@code{keysort(+@var{L},@var{S})} unifies @var{S} with the list obtained -from @var{L}, by sorting its elements according to the value of -@var{Key}. -@example -?- keysort([3-a,1-b,2-c,1-a,1-b],S). -@end example -@noindent -would return: -@example -S = [1-b,1-a,1-b,2-c,3-a] -@end example - -@item predsort(+@var{Pred}, +@var{List}, -@var{Sorted}) -@findex predsort/3 -@snindex predsort/3 -@cnindex predsort/3 -Sorts similar to sort/2, but determines the order of two terms by -calling @var{Pred}(-@var{Delta}, +@var{E1}, +@var{E2}) . This call must -unify @var{Delta} with one of @code{<}, @code{>} or @code{=}. If -built-in predicate compare/3 is used, the result is the same as -sort/2. - -@item length(?@var{L},?@var{S}) -@findex length/2 -@syindex length/2 -@cyindex length/2 -Unify the well-defined list @var{L} with its length. The procedure can -be used to find the length of a pre-defined list, or to build a list -of length @var{S}. - -@end table - -@node Arithmetic, I/O, Comparing Terms, Top -@section Arithmetic - -YAP now supports several different numeric types: - -@table @code -@item integers - When YAP is built using the GNU multiple precision arithmetic - library (GMP), integer arithmetic is unbounded, which means that - the size of integers is limited by available memory only. Without - GMP, SWI-Prolog integers have the same size as an address. The - type of integer support can be detected using the Prolog flags - bounded, min_integer and max_integer. As the use of GMP is - default, most of the following descriptions assume unbounded - integer arithmetic. - - Internally, SWI-Prolog has three integer representations. Small - integers (defined by the Prolog flag max_tagged_integer) are - encoded directly. Larger integers are represented as cell values - on the global stack. Integers that do not fit in 64-bit are - represented as serialised GNU MPZ structures on the global stack. - -@item number - Rational numbers (Q) are quotients of two integers. Rational - arithmetic is only provided if GMP is used (see above). Rational - numbers that are returned from is/2 are canonical, which means M - is positive and N and M have no common divisors. Rational numbers - are introduced in the computation using the rational/1, - rationalize/1 or the rdiv/2 (rational division) function. - -@item float - Floating point numbers are represented using the C-type double. On most today platforms these are 64-bit IEEE floating point numbers. - -@end table - -Arithmetic functions that require integer arguments accept, in addition -to integers, rational numbers with denominator `1' and floating point -numbers that can be accurately converted to integers. If the required -argument is a float the argument is converted to float. Note that -conversion of integers to floating point numbers may raise an overflow -exception. In all other cases, arguments are converted to the same type -using the order integer to rational number to floating point number. - - -Arithmetic expressions in YAP may use the following operators or -@i{evaluable predicates}: - -@table @code - -@item +@var{X} [ISO] -The value of @var{X} itself. - -@item -@var{X} [ISO] -Symmetric value. - -@item @var{X}+@var{Y} [ISO] -Sum. - -@item @var{X}-@var{Y} [ISO] -Difference. - -@item @var{X}*@var{Y} [ISO] -Product. - -@item @var{X}/@var{Y} [ISO] -Quotient. - -@item @var{X}//@var{Y} [ISO] -Integer quotient. - -@item @var{X} mod @var{Y} [ISO] -Integer module operator, always positive. - -@item @var{X} rem @var{Y} [ISO] -Integer remainder, similar to @code{mod} but always has the same sign -@code{X}. - -@item @var{X} div @var{Y} [ISO] -Integer division, as if defined by @code{(@var{X} - @var{X} mod @var{Y}) -// @var{Y}}. - -@item exp(@var{X}) [ISO] -Natural exponential. - -@item log(@var{X}) [ISO] -Natural logarithm. - -@item log10(@var{X}) -Decimal logarithm. - -@item sqrt(@var{X}) [ISO] -Square root. - -@item sin(@var{X}) [ISO] -Sine. - -@item cos(@var{X}) [ISO] -Cosine. - -@item tan(@var{X}) [ISO] -Tangent. - -@item asin(@var{X}) [ISO] -Arc sine. - -@item acos(@var{X}) [ISO] -Arc cosine. - -@item atan(@var{X}) [ISO] -Arc tangent. - -@item atan(@var{X},@var{Y}) -Four-quadrant arc tangent. Also available as @code{atan2/2}. - -@item atan2(@var{X},@var{Y}) [ISO] -Four-quadrant arc tangent. - -@item sinh(@var{X}) -Hyperbolic sine. - -@item cosh(@var{X}) -Hyperbolic cosine. - -@item tanh(@var{X}) -Hyperbolic tangent. - -@item asinh(@var{X}) -Hyperbolic arc sine. - -@item acosh(@var{X}) -Hyperbolic arc cosine. - -@item atanh(@var{X}) -Hyperbolic arc tangent. - -@item lgamma(@var{X}) -Logarithm of gamma function. - -@item erf(@var{X}) -Gaussian error function. - -@item erfc(@var{X}) -Complementary gaussian error function. - -@item random(@var{X}) [ISO] -An integer random number between 0 and @var{X}. - -In @code{iso} language mode the argument must be a floating -point-number, the result is an integer and it the float is equidistant -it is rounded up, that is, to the least integer greater than @var{X}. - -@item integer(@var{X}) -If @var{X} evaluates to a float, the integer between the value of @var{X} -and 0 closest to the value of @var{X}, else if @var{X} evaluates to an -integer, the value of @var{X}. - -@item float(@var{X}) [ISO] -If @var{X} evaluates to an integer, the corresponding float, else the float -itself. - -@item float_fractional_part(@var{X}) [ISO] -The fractional part of the floating point number @var{X}, or @code{0.0} -if @var{X} is an integer. In the @code{iso} language mode, -@var{X} must be an integer. - -@item float_integer_part(@var{X}) [ISO] -The float giving the integer part of the floating point number @var{X}, -or @var{X} if @var{X} is an integer. In the @code{iso} language mode, -@var{X} must be an integer. - -@item abs(@var{X}) [ISO] -The absolute value of @var{X}. - -@item ceiling(@var{X}) [ISO] -The integer that is the smallest integral value not smaller than @var{X}. - -In @code{iso} language mode the argument must be a floating -point-number and the result is an integer. - -@item floor(@var{X}) [ISO] -The integer that is the greatest integral value not greater than @var{X}. - -In @code{iso} language mode the argument must be a floating -point-number and the result is an integer. - -@item round(@var{X}) [ISO] -The nearest integral value to @var{X}. If @var{X} is -equidistant to two integers, it will be rounded to the closest even -integral value. - -In @code{iso} language mode the argument must be a floating -point-number, the result is an integer and it the float is equidistant -it is rounded up, that is, to the least integer greater than @var{X}. - -@item sign(@var{X}) [ISO] -Return 1 if the @var{X} evaluates to a positive integer, 0 it if -evaluates to 0, and -1 if it evaluates to a negative integer. If @var{X} -evaluates to a floating-point number return 1.0 for a positive @var{X}, -0.0 for 0.0, and -1.0 otherwise. - -@item truncate(@var{X}) [ISO] -The integral value between @var{X} and 0 closest to -@var{X}. - -@item rational(@var{X}) -Convert the expression @var{X} to a rational number or integer. The -function returns the input on integers and rational numbers. For -floating point numbers, the returned rational number exactly represents -the float. As floats cannot exactly represent all decimal numbers the -results may be surprising. In the examples below, doubles can represent -@code{0.25} and the result is as expected, in contrast to the result of -@code{rational(0.1)}. The function @code{rationalize/1} gives a more -intuitive result. - -@example -?- A is rational(0.25). - -A is 1 rdiv 4 -?- A is rational(0.1). -A = 3602879701896397 rdiv 36028797018963968 -@end example - -@item rationalize(@var{X}) -Convert the Expr to a rational number or integer. The function is -similar to @code{rational/1}, but the result is only accurate within the -rounding error of floating point numbers, generally producing a much -smaller denominator. - -@example -?- A is rationalize(0.25). - -A = 1 rdiv 4 -?- A is rationalize(0.1). - -A = 1 rdiv 10 -@end example - - -@item max(@var{X},@var{Y}) [ISO] -The greater value of @var{X} and @var{Y}. - -@item min(@var{X},@var{Y}) [ISO] -The lesser value of @var{X} and @var{Y}. - -@item @var{X} ^ @var{Y} [ISO] -@var{X} raised to the power of @var{Y}, (from the C-Prolog syntax). - -@item exp(@var{X},@var{Y}) -@var{X} raised to the power of @var{Y}, (from the Quintus Prolog syntax). - -@item @var{X} ** @var{Y} [ISO] -@var{X} raised to the power of @var{Y} (from ISO). - -@item @var{X} /\ @var{Y} [ISO] -Integer bitwise conjunction. - -@item @var{X} \/ @var{Y} [ISO] -Integer bitwise disjunction. - -@item @var{X} # @var{Y} -@item @var{X} >< @var{Y} -@item xor(@var{X} , @var{Y}) [ISO] -Integer bitwise exclusive disjunction. - -@item @var{X} << @var{Y} -Integer bitwise left logical shift of @var{X} by @var{Y} places. - -@item @var{X} >> @var{Y} [ISO] -Integer bitwise right logical shift of @var{X} by @var{Y} places. - -@item \ @var{X} [ISO] -Integer bitwise negation. - -@item gcd(@var{X},@var{Y}) -The greatest common divisor of the two integers @var{X} and @var{Y}. - -@item msb(@var{X}) -The most significant bit of the non-negative integer @var{X}. - -@item lsb(@var{X}) -The least significant bit of the non-negative integer @var{X}. - -@item popcount(@var{X}) -The number of bits set to @code{1} in the binary representation of the -non-negative integer @var{X}. - -@item [@var{X}] -Evaluates to @var{X} for expression @var{X}. Useful because character -strings in Prolog are lists of character codes. - -@example -X is Y*10+C-"0" -@end example -@noindent -is the same as -@example -X is Y*10+C-[48]. -@end example -@noindent -which would be evaluated as: -@example -X is Y*10+C-48. -@end example - -@end table - -Besides numbers and the arithmetic operators described above, certain -atoms have a special meaning when present in arithmetic expressions: - -@table @code -@item pi [ISO] -The value of @emph{pi}, the ratio of a circle's circumference to its -diameter. - -@item e -The base of the natural logarithms. - -@item epsilon -The difference between the float @code{1.0} and the first larger floating point -number. - -@item inf -Infinity according to the IEEE Floating-Point standard. Note that -evaluating this term will generate a domain error in the @code{iso} -language mode. - -@item nan -Not-a-number according to the IEEE Floating-Point standard. Note that -evaluating this term will generate a domain error in the @code{iso} -language mode. - -@item cputime -CPU time in seconds, since YAP was invoked. - -@item heapused -Heap space used, in bytes. - -@item local -Local stack in use, in bytes. - -@item global -Global stack in use, in bytes. - -@item random -A "random" floating point number between 0 and 1. - -@end table - -The primitive YAP predicates involving arithmetic expressions are: - -@table @code - -@item @var{X} is +@var{Y} [2] -@findex is/2 -@syindex is/2 -@caindex is/2 -This predicate succeeds iff the result of evaluating the expression -@var{Y} unifies with @var{X}. This is the predicate normally used to -perform evaluation of arithmetic expressions: - -@example -X is 2+3*4 -@end example -@noindent -succeeds with @code{X = 14}. - -@item +@var{X} < +@var{Y} [ISO] -@findex +@var{Y} [ISO] -@findex >/2 -@syindex >/2 -@cyindex >/2 -The value of the expression @var{X} is greater than the value of -expression @var{Y}. - -@item +@var{X} >= +@var{Y} [ISO] -@findex >=/2 -@syindex >=/2 -@cyindex >=/2 -The value of the expression @var{X} is greater than or equal to the -value of expression @var{Y}. - -@item +@var{X} =:= +@var{Y} [ISO] -@findex =:=/2 -@syindex =:=/2 -@cyindex =:=/2 -The value of the expression @var{X} is equal to the value of expression -@var{Y}. - -@item +@var{X} =\= +@var{Y} [ISO] -@findex =\=/2 -@syindex =\=/2 -@cyindex =\=/2 -The value of the expression @var{X} is different from the value of -expression @var{Y}. - -@item srandom(+@var{X}) -@findex srandom/1 -@snindex srandom/1 -@cnindex srandom/1 -Use the argument @var{X} as a new seed for YAP's random number -generator. The argument should be an integer, but floats are acceptable. -@end table - -@noindent -@strong{Notes:} - -@itemize @bullet -@item -Since YAP4, YAP @emph{does not} convert automatically between integers -and floats. -@item -arguments to trigonometric functions are expressed in radians. -@item -if a (non-instantiated) variable occurs in an arithmetic expression YAP -will generate an exception. If no error handler is available, execution -will be thrown back to the top-level. -@end itemize - - -The following predicates provide counting: - -@table @code - -@item between(+@var{Low}, +@var{High}, ?@var{Value}) -@findex between/3 -@syindex between/3 -@cnindex between/3 - - @var{Low} and @var{High} are integers, @var{High} >=@var{Low}. If - @var{Value} is an integer, @var{Low} =<@var{Value} - =<@var{High}. When @var{Value} is a variable it is successively - bound to all integers between @var{Low} and @var{High}. If - @var{High} is inf or infinite @code{between/3} is true iff - @var{Value} >= @var{Low}, a feature that is particularly interesting - for generating integers from a certain value. - -@item succ(?@var{Int1}, ?@var{Int2}) -@findex succ/3 -@syindex succ/3 -@cnindex succ/3 - - True if @var{Int2} = @var{Int1} + 1 and @var{Int1} >= 0. At least - one of the arguments must be instantiated to a natural number. This - predicate raises the domain-error not_less_than_zero if called with - a negative integer. E.g. @code{succ(X, 0)} fails silently and succ(X, -1) - raises a domain-error. The behaviour to deal with natural numbers - only was defined by Richard O'Keefe to support the common - count-down-to-zero in a natural way. - -@item plus(?@var{Int1}, ?@var{Int2}, ?@var{Int3}) -@findex plus/3 -@syindex plus/3 -@cnindex plus/3 - True if @var{Int3} = @var{Int1} + @var{Int2}. At least two of the - three arguments must be instantiated to integers. - -@item logsum(+@var{Log1}, +@var{Log2}, -@var{Out} ) -@findex logsum/3 -@snindex logsum/3 -@cnindex logsum/3 - True if @var{Log1} is the logarithm of the positive number @var{A1}, - @var{Log2} is the logarithm of the positive number @var{A2}, and - @var{Out} is the logarithm of the sum of the numbers @var{A1} and - @var{A2}. Useful in probability computation. - -@item isnan(+@var{Float}) -@findex isnan/1 -@snindex isnan/1 -@cnindex isnan/1 - True if @var{Float} is not a number. - -@item isinf(+@var{Float}) -@findex isinf/1 -@snindex isinf/1 -@cnindex isinf/1 - True if floating point expression @var{Float} evaluates to infinity. - - -@end table - -@node I/O, Database, Arithmetic, Top -@section I/O Predicates - -Some of the I/O predicates described below will in certain conditions -provide error messages and abort only if the file_errors flag is set. -If this flag is cleared the same predicates will just fail. Details on -setting and clearing this flag are given under 7.7. - -@menu - -Subnodes of Input/Output -* Streams and Files:: Handling Streams and Files -* C-Prolog File Handling:: C-Prolog Compatible File Handling -* I/O of Terms:: Input/Output of terms -* I/O of Characters:: Input/Output of Characters -* I/O for Streams:: Input/Output using Streams -* C-Prolog to Terminal:: C-Prolog compatible Character I/O to terminal -* I/O Control:: Controlling your Input/Output -* Sockets:: Using Sockets from YAP - -@end menu - -@node Streams and Files, C-Prolog File Handling, , I/O -@subsection Handling Streams and Files - -@table @code - -@item open(+@var{F},+@var{M},-@var{S}) [ISO] -@findex open/3 -@syindex open/3 -@cnindex open/3 -Opens the file with name @var{F} in mode @var{M} ('read', 'write' or -'append'), returning @var{S} unified with the stream name. - -At most, there are 17 streams opened at the same time. Each stream is -either an input or an output stream but not both. There are always 3 -open streams: @code{user_input} for reading, @code{user_output} for writing -and @code{user_error} for writing. If there is no ambiguity, the atoms -@code{user_input} and @code{user_output} may be referred to as @code{user}. - -The @code{file_errors} flag controls whether errors are reported when in -mode 'read' or 'append' the file @var{F} does not exist or is not -readable, and whether in mode 'write' or 'append' the file is not -writable. - -@item open(+@var{F},+@var{M},-@var{S},+@var{Opts}) [ISO] -@findex open/4 -@saindex open/4 -@cnindex open/4 -Opens the file with name @var{F} in mode @var{M} ('read', 'write' or -'append'), returning @var{S} unified with the stream name, and following -these options: - -@table @code - -@item type(+@var{T}) [ISO] -Specify whether the stream is a @code{text} stream (default), or a -@code{binary} stream. - -@item reposition(+@var{Bool}) [ISO] -Specify whether it is possible to reposition the stream (@code{true}), or -not (@code{false}). By default, YAP enables repositioning for all -files, except terminal files and sockets. - -@item eof_action(+@var{Action}) [ISO] -Specify the action to take if attempting to input characters from a -stream where we have previously found an @code{end_of_file}. The possible -actions are @code{error}, that raises an error, @code{reset}, that tries to -reset the stream and is used for @code{tty} type files, and @code{eof_code}, -which generates a new @code{end_of_file} (default for non-tty files). - -@item alias(+@var{Name}) [ISO] -Specify an alias to the stream. The alias @t{Name} must be an atom. The -alias can be used instead of the stream descriptor for every operation -concerning the stream. - -The operation will fail and give an error if the alias name is already -in use. YAP allows several aliases for the same file, but only -one is returned by @code{stream_property/2} - -@item bom(+@var{Bool}) -If present and @code{true}, a BOM (@emph{Byte Order Mark}) was -detected while opening the file for reading or a BOM was written while -opening the stream. See @ref{BOM} for details. - -@item encoding(+@var{Encoding}) -Set the encoding used for text. See @ref{Encoding} for an overview of -wide character and encoding issues. - -@item representation_errors(+@var{Mode}) -Change the behaviour when writing characters to the stream that cannot -be represented by the encoding. The behaviour is one of @code{error} -(throw and I/O error exception), @code{prolog} (write @code{\u...\} -escape code or @code{xml} (write @code{&#...;} XML character entity). -The initial mode is @code{prolog} for the user streams and -@code{error} for all other streams. See also @ref{Encoding}. - -@item expand_filename(+@var{Mode}) -If @var{Mode} is @code{true} then do filename expansion, then ask Prolog -to do file name expansion before actually trying to opening the file: -this includes processing @code{~} characters and processing @code{$} -environment variables at the beginning of the file. Otherwise, just try -to open the file using the given name. - -The default behavior is given by the Prolog flag -@code{open_expands_filename}. - -@end table - -@item close(+@var{S}) [ISO] -@findex close/1 -@syindex close/1 -@cyindex close/1 -Closes the stream @var{S}. If @var{S} does not stand for a stream -currently opened an error is reported. The streams @code{user_input}, -@code{user_output}, and @code{user_error} can never be closed. - -@c By default, give a file name, @code{close/1} will also try to close a -@c corresponding open stream. This feature is not available in ISO or -@c SICStus languages mode and is deprecated. - -@item close(+@var{S},+@var{O}) [ISO] -@findex close/2 -@saindex close/2 -@cnindex close/2 -Closes the stream @var{S}, following options @var{O}. - -The only valid options are @code{force(true)} and @code{force(false)}. -YAP currently ignores these options. - -@item time_file(+@var{File},-@var{Time}) -@findex time_file/2 -@snindex time_file/2 -@cnindex time_file/2 -Unify the last modification time of @var{File} with -@var{Time}. @var{Time} is a floating point number expressing the seconds -elapsed since Jan 1, 1970. - -@item absolute_file_name(+@var{Name},+@var{Options}, -@var{FullPath}) -@item absolute_file_name(+@var{Name}, -@var{FullPath},+@var{Options}) -@findex absolute_file_name/3 -@syindex absolute_file_name/3 -@cnindex absolute_file_name/3 - -Converts the given file specification into an absolute path. -@var{Option} is a list of options to guide the conversion: - -@table @code - @item extensions(+@var{ListOfExtensions}) -List of file-extensions to try. Default is @samp{''}. For each -extension, @code{absolute_file_name/3} will first add the extension and then -verify the conditions imposed by the other options. If the condition -fails, the next extension of the list is tried. Extensions may be -specified both as @code{.ext} or plain @code{ext}. - - @item relative_to(+@var{FileOrDir}) -Resolve the path relative to the given directory or directory the -holding the given file. Without this option, paths are resolved -relative to the working directory (see @code{working_directory/2}) or, -if @var{Spec} is atomic and @code{absolute_file_name/[2,3]} is executed -in a directive, it uses the current source-file as reference. - - @item access(+@var{Mode}) -Imposes the condition access_file(@var{File}, @var{Mode}). @var{Mode} -is on of @code{read}, @code{write}, @code{append}, @code{exist} or -@code{none} (default). -See also @code{access_file/2}. - - @item file_type(+@var{Type}) -Defines extensions. Current mapping: @code{txt} implies @code{['']}, -@code{prolog} implies @code{['.yap', '.pl', '.prolog', '']}, @code{executable} -implies @code{['.so', '']}, @code{qlf} implies @code{['.qlf', '']} and -@code{directory} implies @code{['']}. The file-type @code{source} -is an alias for @code{prolog} for compatibility to SICStus Prolog. -See also @code{prolog_file_type/2}. Notice also that this predicate only -returns non-directories, unless the option @code{file_type(directory)} is -specified, or unless @code{access(none)}. - - @item file_errors(@code{fail}/@code{error}) -If @code{error} (default), throw and @code{existence_error} exception -if the file cannot be found. If @code{fail}, stay silent. - - @item solutions(@code{first}/@code{all}) -If @code{first} (default), the predicates leaves no choice-point. -Otherwise a choice-point will be left and backtracking may yield -more solutions. - - @item expand(@code{true}/@code{false}) - If @code{true} (default is @code{false}) and @var{Spec} is atomic, - call @code{expand_file_name/2} followed by @code{member/2} on @var{Spec} before - proceeding. This is originally a SWI-Prolog extension. -@end table - -@c The Prolog flag @code{verbose_file_search} can be set to @code{true} -@c to help debugging Prolog's search for files. - -Compatibility considerations to common argument-order in ISO as well -as SICStus @code{absolute_file_name/3} forced us to be flexible here. -If the last argument is a list and the 2nd not, the arguments are -swapped, making the call @code{absolute_file_name}(+@var{Spec}, -@var{Path}, -+@var{Options}) valid as well. - -@item absolute_file_name(+@var{Name},-@var{FullPath}) -@findex absolute_file_name/2 -@syindex absolute_file_name/2 -@cnindex absolute_file_name/2 -Give the path a full path @var{FullPath} YAP would use to consult a file -named @var{Name}. Unify @var{FullPath} with @code{user} if the file -name is @code{user}. - -@item file_base_name(+@var{Name},-@var{FileName}) -@findex file_base_name/2 -@snindex file_base_name/2 -@cnindex file_base_name/2 -Give the path a full path @var{FullPath} extract the @var{FileName}. - -@item file_name_extension(?@var{Base},?@var{Extension}, ?@var{Name}) -@findex file_name_extension/3 -@snindex file_name_extension/3 -@cnindex file_name_extension/3 - -This predicate is used to add, remove or test filename extensions. The -main reason for its introduction is to deal with different filename -properties in a portable manner. If the file system is -case-insensitive, testing for an extension will be done -case-insensitive too. @var{Extension} may be specified with or -without a leading dot (.). If an @var{Extension} is generated, it -will not have a leading dot. - -@item current_stream(@var{F},@var{M},@var{S}) -@findex current_stream/3 -@syindex current_stream/3 -@cnindex current_stream/3 -Defines the relation: The stream @var{S} is opened on the file @var{F} -in mode @var{M}. It might be used to obtain all open streams (by -backtracking) or to access the stream for a file @var{F} in mode -@var{M}, or to find properties for a stream @var{S}. Notice that some -streams might not be associated to a file: in this case YAP tries to -return the file number. If that is not available, YAP unifies @var{F} -with @var{S}. - -@item is_stream(@var{S}) -@findex is_stream/1 -@snindex is_stream/1 -@cnindex is_stream/1 -Succeeds if @var{S} is a currently open stream. - -@item flush_output [ISO] -@findex flush_output/0 -@syindex flush_output/0 -@cnindex flush_output/0 -Send out all data in the output buffer of the current output stream. - -@item flush_output(+@var{S}) [ISO] -@findex flush_output/1 -@syindex flush_output/1 -@cnindex flush_output/1 -Send all data in the output buffer for stream @var{S}. - -@item set_input(+@var{S}) [ISO] -@findex set_input/1 -@syindex set_input/1 -@cnindex set_input/1 -Set stream @var{S} as the current input stream. Predicates like @code{read/1} -and @code{get/1} will start using stream @var{S}. - -@item set_output(+@var{S}) [ISO] -@findex set_output/1 -@syindex set_output/1 -@cnindex set_output/1 -Set stream @var{S} as the current output stream. Predicates like -@code{write/1} and @code{put/1} will start using stream @var{S}. - -@item stream_select(+@var{STREAMS},+@var{TIMEOUT},-@var{READSTREAMS}) -@findex stream_select/3 -@syindex stream_select/3 -@cnindex stream_select/3 -Given a list of open @var{STREAMS} opened in read mode and a @var{TIMEOUT} -return a list of streams who are now available for reading. - -If the @var{TIMEOUT} is instantiated to @code{off}, -@code{stream_select/3} will wait indefinitely for a stream to become -open. Otherwise the timeout must be of the form @code{SECS:USECS} where -@code{SECS} is an integer gives the number of seconds to wait for a timeout -and @code{USECS} adds the number of micro-seconds. - -This built-in is only defined if the system call @code{select} is -available in the system. - -@item current_input(-@var{S}) [ISO] -@findex current_input/1 -@syindex current_input/1 -@cnindex current_input/1 -Unify @var{S} with the current input stream. - -@item current_output(-@var{S}) [ISO] -@findex current_output/1 -@syindex current_output/1 -@cnindex current_output/1 -Unify @var{S} with the current output stream. - -@item at_end_of_stream [ISO] -@findex at_end_of_stream/0 -@syindex at_end_of_stream/0 -@cnindex at_end_of_stream/0 -Succeed if the current stream has stream position end-of-stream or -past-end-of-stream. - -@item at_end_of_stream(+@var{S}) [ISO] -@findex at_end_of_stream/1 -@syindex at_end_of_stream/1 -@cnindex at_end_of_stream/1 -Succeed if the stream @var{S} has stream position end-of-stream or -past-end-of-stream. Note that @var{S} must be a readable stream. - -@item set_stream_position(+@var{S}, +@var{POS}) [ISO] -@findex set_stream_position/2 -@syindex set_stream_position/2 -@cnindex set_stream_position/2 -Given a stream position @var{POS} for a stream @var{S}, set the current -stream position for @var{S} to be @var{POS}. - -@item stream_property(?@var{Stream},?@var{Prop}) [ISO] -@findex stream_property/2 -@snindex stream_property/2 -@cnindex stream_property/2 - -Obtain the properties for the open streams. If the first argument is -unbound, the procedure will backtrack through all open -streams. Otherwise, the first argument must be a stream term (you may -use @code{current_stream} to obtain a current stream given a file name). - -The following properties are recognized: - -@table @code - -@item file_name(@var{P}) -An atom giving the file name for the current stream. The file names are -@code{user_input}, @code{user_output}, and @code{user_error} for the -standard streams. - -@item mode(@var{P}) -The mode used to open the file. It may be one of @code{append}, -@code{read}, or @code{write}. - -@item input -The stream is readable. - -@item output -The stream is writable. - -@item alias(@var{A}) -ISO-Prolog primitive for stream aliases. @t{YAP} returns one of the -existing aliases for the stream. - -@item position(@var{P}) -A term describing the position in the stream. - -@item end_of_stream(@var{E}) -Whether the stream is @code{at} the end of stream, or it has found the -end of stream and is @code{past}, or whether it has @code{not} yet -reached the end of stream. - -@item eof_action(@var{A}) -The action to take when trying to read after reaching the end of -stream. The action may be one of @code{error}, generate an error, -@code{eof_code}, return character code @code{-1}, or @code{reset} the -stream. - -@item reposition(@var{B}) -Whether the stream can be repositioned or not, that is, whether it is -seekable. - -@item type(@var{T}) -Whether the stream is a @code{text} stream or a @code{binary} stream. - -@item bom(+@var{Bool}) -If present and @code{true}, a BOM (@emph{Byte Order Mark}) was -detected while opening the file for reading or a BOM was written while -opening the stream. See @ref{BOM} for details. - -@item encoding(+@var{Encoding}) -Query the encoding used for text. See @ref{Encoding} for an -overview of wide character and encoding issues in YAP. - -@item representation_errors(+@var{Mode}) -Behaviour when writing characters to the stream that cannot be -represented by the encoding. The behaviour is one of @code{error} -(throw and I/O error exception), @code{prolog} (write @code{\u...\} -escape code or @code{xml} (write @code{&#...;} XML character entity). -The initial mode is @code{prolog} for the user streams and -@code{error} for all other streams. See also @ref{Encoding} and -@code{open/4}. - -@end table - -@item current_line_number(-@var{LineNumber}) -@findex current_line_number/1 -@saindex current_line_number/1 -@cnindex current_line_number/1 -Unify @var{LineNumber} with the line number for the current stream. - -@item current_line_number(+@var{Stream},-@var{LineNumber}) -@findex current_line_number/2 -@saindex current_line_number/2 -@cnindex current_line_number/2 -Unify @var{LineNumber} with the line number for the @var{Stream}. - -@item line_count(+@var{Stream},-@var{LineNumber}) -@findex line_count/2 -@syindex line_count/2 -@cnindex line_count/2 -Unify @var{LineNumber} with the line number for the @var{Stream}. - -@item character_count(+@var{Stream},-@var{CharacterCount}) -@findex character_count/2 -@syindex character_count/2 -@cnindex character_count/2 -Unify @var{CharacterCount} with the number of characters written to or -read to @var{Stream}. - -@item line_position(+@var{Stream},-@var{LinePosition}) -@findex line_position/2 -@syindex line_position/2 -@cnindex line_position/2 -Unify @var{LinePosition} with the position on current text stream -@var{Stream}. - -@item stream_position(+@var{Stream},-@var{StreamPosition}) -@findex stream_position/2 -@syindex stream_position/2 -@cnindex stream_position/2 -Unify @var{StreamPosition} with the packaged information of position on -current stream @var{Stream}. Use @code{stream_position_data/3} to -retrieve information on character or line count. - -@item stream_position_data(+@var{Field},+@var{StreamPosition},-@var{Info}) -@findex stream_position_data/3 -@syindex stream_position_data/3 -@cnindex stream_position_data/3 -Given the packaged stream position term @var{StreamPosition}, unify -@var{Info} with @var{Field} @code{line_count}, @code{byte_count}, or -@code{char_count}. - -@end table - -@node C-Prolog File Handling, I/O of Terms, Streams and Files, I/O -@subsection Handling Streams and Files - -@table @code - -@item tell(+@var{S}) -@findex tell/1 -@syindex tell/1 -@cyindex tell/1 -If @var{S} is a currently opened stream for output, it becomes the -current output stream. If @var{S} is an atom it is taken to be a -filename. If there is no output stream currently associated with it, -then it is opened for output, and the new output stream created becomes -the current output stream. If it is not possible to open the file, an -error occurs. If there is a single opened output stream currently -associated with the file, then it becomes the current output stream; if -there are more than one in that condition, one of them is chosen. - -Whenever @var{S} is a stream not currently opened for output, an error -may be reported, depending on the state of the file_errors flag. The -predicate just fails, if @var{S} is neither a stream nor an atom. - -@item telling(-@var{S}) -@findex telling/1 -@syindex telling/1 -@cyindex telling/1 -The current output stream is unified with @var{S}. - -@item told -@findex told/0 -@syindex told/0 -@cyindex told/0 -Closes the current output stream, and the user's terminal becomes again -the current output stream. It is important to remember to close streams -after having finished using them, as the maximum number of -simultaneously opened streams is 17. - -@item see(+@var{S}) -@findex see/1 -@syindex see/1 -@cyindex see/1 -If @var{S} is a currently opened input stream then it is assumed to be -the current input stream. If @var{S} is an atom it is taken as a -filename. If there is no input stream currently associated with it, then -it is opened for input, and the new input stream thus created becomes -the current input stream. If it is not possible to open the file, an -error occurs. If there is a single opened input stream currently -associated with the file, it becomes the current input stream; if there -are more than one in that condition, then one of them is chosen. - -When @var{S} is a stream not currently opened for input, an error may be -reported, depending on the state of the @code{file_errors} flag. If -@var{S} is neither a stream nor an atom the predicates just fails. - -@item seeing(-@var{S}) -@findex seeing/1 -@syindex seeing/1 -@cyindex seeing/1 -The current input stream is unified with @var{S}. - -@item seen -@findex seen/0 -@syindex seen/0 -@cyindex seen/0 -Closes the current input stream (see 6.7.). - -@end table - -@node I/O of Terms, I/O of Characters, C-Prolog File Handling, I/O -@subsection Handling Input/Output of Terms - -@table @code - -@item read(-@var{T}) [ISO] -@findex read/1 -@syindex read/1 -@cyindex read/1 -Reads the next term from the current input stream, and unifies it with -@var{T}. The term must be followed by a dot ('.') and any blank-character -as previously defined. The syntax of the term must match the current -declarations for operators (see op). If the end-of-stream is reached, -@var{T} is unified with the atom @code{end_of_file}. Further reads from of -the same stream may cause an error failure (see @code{open/3}). - -@item read_term(-@var{T},+@var{Options}) [ISO] -@findex read_term/2 -@saindex read_term/2 -@cnindex read_term/2 -Reads term @var{T} from the current input stream with execution -controlled by the following options: - -@table @code - -@item term_position(-@var{Position}) -@findex term_position/1 (read_term/2 option) -Unify @var{Position} with a term describing the position of the stream -at the start of parse. Use @code{stream_position_data/3} to obtain extra -information. - -@item singletons(-@var{Names}) -@findex singletons/1 (read_term/2 option) -Unify @var{Names} with a list of the form @var{Name=Var}, where -@var{Name} is the name of a non-anonymous singleton variable in the -original term, and @code{Var} is the variable's representation in -YAP. -The variables occur in left-to-right traversal order. - -@item syntax_errors(+@var{Val}) -@findex syntax_errors/1 (read_term/2 option) -Control action to be taken after syntax errors. See @code{yap_flag/2} -for detailed information. - -@item variable_names(-@var{Names}) -@findex variable_names/1 (read_term/2 option) -Unify @var{Names} with a list of the form @var{Name=Var}, where @var{Name} is -the name of a non-anonymous variable in the original term, and @var{Var} -is the variable's representation in YAP. -The variables occur in left-to-right traversal order. - -@item variables(-@var{Names}) -@findex variables/1 (read_term/2 option) -Unify @var{Names} with a list of the variables in term @var{T}. -The variables occur in left-to-right traversal order. - -@end table - -@item char_conversion(+@var{IN},+@var{OUT}) [ISO] -@findex char_conversion/2 -@syindex char_conversion/2 -@cnindex char_conversion/2 -While reading terms convert unquoted occurrences of the character -@var{IN} to the character @var{OUT}. Both @var{IN} and @var{OUT} must be -bound to single characters atoms. - -Character conversion only works if the flag @code{char_conversion} is -on. This is default in the @code{iso} and @code{sicstus} language -modes. As an example, character conversion can be used for instance to -convert characters from the ISO-LATIN-1 character set to ASCII. - -If @var{IN} is the same character as @var{OUT}, @code{char_conversion/2} -will remove this conversion from the table. - -@item current_char_conversion(?@var{IN},?@var{OUT}) [ISO] -@findex current_char_conversion/2 -@syindex current_char_conversion/2 -@cnindex current_char_conversion/2 -If @var{IN} is unbound give all current character -translations. Otherwise, give the translation for @var{IN}, if one -exists. - -@item write(@var{T}) [ISO] -@findex write/1 -@syindex write/1 -@cyindex write/1 -The term @var{T} is written to the current output stream according to -the operator declarations in force. - -@item writeln(@var{T}) [ISO] -@findex writeln/1 -@snindex writeln/1 -@cnindex writeln/1 -Same as @code{write/1} followed by @code{nl/0}. - -@item display(+@var{T}) -@findex display/1 -@syindex display/1 -@cyindex display/1 -Displays term @var{T} on the current output stream. All Prolog terms are -written in standard parenthesized prefix notation. - -@item write_canonical(+@var{T}) [ISO] -@findex display/1 -@syindex display/1 -@cnindex display/1 -Displays term @var{T} on the current output stream. Atoms are quoted -when necessary, and operators are ignored, that is, the term is written -in standard parenthesized prefix notation. - -@item write_term(+@var{T}, +@var{Opts}) [ISO] -@findex write_term/2 -@syindex write_term/2 -@cnindex write_term/2 -Displays term @var{T} on the current output stream, according to the -following options: - -@table @code -@item quoted(+@var{Bool}) [ISO] -If @code{true}, quote atoms if this would be necessary for the atom to -be recognized as an atom by YAP's parser. The default value is -@code{false}. - -@item ignore_ops(+@var{Bool}) [ISO] -If @code{true}, ignore operator declarations when writing the term. The -default value is @code{false}. - -@item numbervars(+@var{Bool}) [ISO] -If @code{true}, output terms of the form -@code{'$VAR'(N)}, where @var{N} is an integer, as a sequence of capital -letters. The default value is @code{false}. - -@item portrayed(+@var{Bool}) -If @code{true}, use @t{portray/1} to portray bound terms. The default -value is @code{false}. - -@item portray(+@var{Bool}) -If @code{true}, use @t{portray/1} to portray bound terms. The default -value is @code{false}. - -@item max_depth(+@var{Depth}) -If @code{Depth} is a positive integer, use @t{Depth} as -the maximum depth to portray a term. The default is @code{0}, that is, -unlimited depth. - -@item priority(+@var{Piority}) -If @code{Priority} is a positive integer smaller than @code{1200}, -give the context priority. The default is @code{1200}. - -@item cycles(+@var{Bool}) -Do not loop in rational trees (default). -@end table - -@item writeq(@var{T}) [ISO] -@findex writeq/1 -@syindex writeq/1 -@cyindex writeq/1 - Writes the term @var{T}, quoting names to make the result acceptable to -the predicate 'read' whenever necessary. - -@item print(@var{T}) -@findex print/1 -@syindex print/1 -@cyindex print/1 -Prints the term @var{T} to the current output stream using @code{write/1} -unless T is bound and a call to the user-defined predicate -@code{portray/1} succeeds. To do pretty printing of terms the user should -define suitable clauses for @code{portray/1} and use @code{print/1}. - -@item format(+@var{T},+@var{L}) -@findex format/2 -@saindex format/2 -@cnindex format/2 -Print formatted output to the current output stream. The arguments in -list @var{L} are output according to the string or atom @var{T}. - -A control sequence is introduced by a @code{w}. The following control -sequences are available in YAP: - -@table @code - -@item '~~' -Print a single tilde. - -@item '~a' -The next argument must be an atom, that will be printed as if by @code{write}. - -@item '~Nc' -The next argument must be an integer, that will be printed as a -character code. The number @var{N} is the number of times to print the -character (default 1). - -@item '~Ne' -@itemx '~NE' -@itemx '~Nf' -@itemx '~Ng' -@itemx '~NG' -The next argument must be a floating point number. The float @var{F}, the number -@var{N} and the control code @code{c} will be passed to @code{printf} as: - -@example - printf("%s.Nc", F) - @end example - -As an example: - -@example -?- format("~8e, ~8E, ~8f, ~8g, ~8G~w", - [3.14,3.14,3.14,3.14,3.14,3.14]). -3.140000e+00, 3.140000E+00, 3.140000, 3.14, 3.143.14 -@end example - -@item '~Nd' -The next argument must be an integer, and @var{N} is the number of digits -after the decimal point. If @var{N} is @code{0} no decimal points will be -printed. The default is @var{N = 0}. - -@example -?- format("~2d, ~d",[15000, 15000]). -150.00, 15000 -@end example - -@item '~ND' -Identical to @code{'~Nd'}, except that commas are used to separate groups -of three digits. - -@example -?- format("~2D, ~D",[150000, 150000]). -1,500.00, 150,000 -@end example - -@item '~i' -Ignore the next argument in the list of arguments: - -@example -?- format('The ~i met the boregrove',[mimsy]). -The met the boregrove -@end example - -@item '~k' -Print the next argument with @code{write_canonical}: - -@example -?- format("Good night ~k",a+[1,2]). -Good night +(a,[1,2]) -@end example - -@item '~Nn' -Print @var{N} newlines (where @var{N} defaults to 1). - -@item '~NN' -Print @var{N} newlines if at the beginning of the line (where @var{N} -defaults to 1). - -@item '~Nr' -The next argument must be an integer, and @var{N} is interpreted as a -radix, such that @code{2 <= N <= 36} (the default is 8). - -@example -?- format("~2r, 0x~16r, ~r", - [150000, 150000, 150000]). -100100100111110000, 0x249f0, 444760 -@end example - -@noindent -Note that the letters @code{a-z} denote digits larger than 9. - -@item '~NR' -Similar to '~NR'. The next argument must be an integer, and @var{N} is -interpreted as a radix, such that @code{2 <= N <= 36} (the default is 8). - -@example -?- format("~2r, 0x~16r, ~r", - [150000, 150000, 150000]). -100100100111110000, 0x249F0, 444760 -@end example - -@noindent -The only difference is that letters @code{A-Z} denote digits larger than 9. - -@item '~p' -Print the next argument with @code{print/1}: - -@example -?- format("Good night ~p",a+[1,2]). -Good night a+[1,2] -@end example - -@item '~q' -Print the next argument with @code{writeq/1}: - -@example -?- format("Good night ~q",'Hello'+[1,2]). -Good night 'Hello'+[1,2] -@end example - -@item '~Ns' -The next argument must be a list of character codes. The system then -outputs their representation as a string, where @var{N} is the maximum -number of characters for the string (@var{N} defaults to the length of the -string). - -@example -?- format("The ~s are ~4s",["woods","lovely"]). -The woods are love -@end example - -@item '~w' -Print the next argument with @code{write/1}: - -@example -?- format("Good night ~w",'Hello'+[1,2]). -Good night Hello+[1,2] -@end example - -@end table -The number of arguments, @code{N}, may be given as an integer, or it -may be given as an extra argument. The next example shows a small -procedure to write a variable number of @code{a} characters: - -@example -write_many_as(N) :- - format("~*c",[N,0'a]). -@end example - -The @code{format/2} built-in also allows for formatted output. One can -specify column boundaries and fill the intermediate space by a padding -character: - -@table @code -@item '~N|' -Set a column boundary at position @var{N}, where @var{N} defaults to the -current position. - -@item '~N+' -Set a column boundary at @var{N} characters past the current position, where -@var{N} defaults to @code{8}. - - -@item '~Nt' -Set padding for a column, where @var{N} is the fill code (default is -@key{SPC}). - -@end table - -The next example shows how to align columns and padding. We first show -left-alignment: - -@example - -@code{ - ?- format("~n*Hello~16+*~n",[]). -*Hello * -} -@end example - -Note that we reserve 16 characters for the column. - -The following example shows how to do right-alignment: - - -@example -@code{ - ?- format("*~tHello~16+*~n",[]). -* Hello* -} - -@end example - - -The @code{~t} escape sequence forces filling before @code{Hello}. - -We next show how to do centering: - -@example -@code{ - ?- format("*~tHello~t~16+*~n",[]). -* Hello * -} -@end example - - -The two @code{~t} escape sequence force filling both before and after -@code{Hello}. Space is then evenly divided between the right and the -left sides. - - -@item format(+@var{T}) -@findex format/1 -@saindex format/1 -@cnindex format/1 -Print formatted output to the current output stream. - - -@item format(+@var{S},+@var{T},+@var{L}) -@findex format/3 -@saindex format/3 -@cnindex format/3 -Print formatted output to stream @var{S}. - -@item with_output_to(+@var{Ouput},:@var{Goal}) -@findex with_output_to/2 -@saindex with_output_to/2 -@cnindex with_output_to/2 -Run @var{Goal} as @code{once/1}, while characters written to the current -output are sent to @var{Output}. The predicate is SWI-Prolog -specific. - -Applications should generally avoid creating atoms by breaking and -concatenating other atoms as the creation of large numbers of -intermediate atoms generally leads to poor performance, even more so in -multi-threaded applications. This predicate supports creating -difference-lists from character data efficiently. The example below -defines the DCG rule @code{term/3} to insert a term in the output: - -@example - term(Term, In, Tail) :- - with_output_to(codes(In, Tail), write(Term)). - -?- phrase(term(hello), X). - -X = [104, 101, 108, 108, 111] -@end example - -@table @code -@item A Stream handle or alias - Temporary switch current output to the given stream. Redirection using with_output_to/2 guarantees the original output is restored, also if Goal fails or raises an exception. See also call_cleanup/2. -@item atom(-@var{Atom}) - Create an atom from the emitted characters. Please note the remark above. -@item string(-@var{String}) - Create a string-object (not supported in YAP). -@item codes(-@var{Codes}) - Create a list of character codes from the emitted characters, similar to atom_codes/2. -@item codes(-@var{Codes}, -@var{Tail}) - Create a list of character codes as a difference-list. -@item chars(-@var{Chars}) - Create a list of one-character-atoms codes from the emitted characters, similar to atom_chars/2. -@item chars(-@var{Chars}, -@var{Tail}) - Create a list of one-character-atoms as a difference-list. -@end table - -@end table - -@node I/O of Characters, I/O for Streams, I/O of Terms, I/O -@subsection Handling Input/Output of Characters - -@table @code - -@item put(+@var{N}) -@findex put/1 -@syindex put/1 -@cyindex put/1 -Outputs to the current output stream the character whose ASCII code is -@var{N}. The character @var{N} must be a legal ASCII character code, an -expression yielding such a code, or a list in which case only the first -element is used. - -@item put_byte(+@var{N}) [ISO] -@findex put_byte/1 -@snindex put_byte/1 -@cnindex put_byte/1 -Outputs to the current output stream the character whose code is -@var{N}. The current output stream must be a binary stream. - -@item put_char(+@var{N}) [ISO] -@findex put_char/1 -@snindex put_char/1 -@cnindex put_char/1 -Outputs to the current output stream the character who is used to build -the representation of atom @code{A}. The current output stream must be a -text stream. - -@item put_code(+@var{N}) [ISO] -@findex put_code/1 -@snindex put_code/1 -@cnindex put_code/1 -Outputs to the current output stream the character whose ASCII code is -@var{N}. The current output stream must be a text stream. The character -@var{N} must be a legal ASCII character code, an expression yielding such -a code, or a list in which case only the first element is used. - -@item get(-@var{C}) -@findex get/1 -@syindex get/1 -@cyindex get/1 -The next non-blank character from the current input stream is unified -with @var{C}. Blank characters are the ones whose ASCII codes are not -greater than 32. If there are no more non-blank characters in the -stream, @var{C} is unified with -1. If @code{end_of_stream} has already -been reached in the previous reading, this call will give an error message. - -@item get0(-@var{C}) -@findex get0/1 -@syindex get0/1 -@cyindex get0/1 -The next character from the current input stream is consumed, and then -unified with @var{C}. There are no restrictions on the possible -values of the ASCII code for the character, but the character will be -internally converted by YAP. - -@item get_byte(-@var{C}) [ISO] -@findex get_byte/1 -@snindex get_byte/1 -@cnindex get_byte/1 -If @var{C} is unbound, or is a character code, and the current stream is a -binary stream, read the next byte from the current stream and unify its -code with @var{C}. - -@item get_char(-@var{C}) [ISO] -@findex get_char/1 -@snindex get_char/1 -@cnindex get_char/1 -If @var{C} is unbound, or is an atom representation of a character, and -the current stream is a text stream, read the next character from the -current stream and unify its atom representation with @var{C}. - -@item get_code(-@var{C}) [ISO] -@findex get_code/1 -@snindex get_code/1 -@cnindex get_code/1 -If @var{C} is unbound, or is the code for a character, and -the current stream is a text stream, read the next character from the -current stream and unify its code with @var{C}. - -@item peek_byte(-@var{C}) [ISO] -@findex peek_byte/1 -@snindex peek_byte/1 -@cnindex peek_byte/1 -If @var{C} is unbound, or is a character code, and the current stream is a -binary stream, read the next byte from the current stream and unify its -code with @var{C}, while leaving the current stream position unaltered. - -@item peek_char(-@var{C}) [ISO] -@findex peek_char/1 -@syindex peek_char/1 -@cnindex peek_char/1 -If @var{C} is unbound, or is an atom representation of a character, and -the current stream is a text stream, read the next character from the -current stream and unify its atom representation with @var{C}, while -leaving the current stream position unaltered. - -@item peek_code(-@var{C}) [ISO] -@findex peek_code/1 -@snindex peek_code/1 -@cnindex peek_code/1 -If @var{C} is unbound, or is the code for a character, and -the current stream is a text stream, read the next character from the -current stream and unify its code with @var{C}, while -leaving the current stream position unaltered. - -@item skip(+@var{N}) -@findex skip/1 -@syindex skip/1 -@cyindex skip/1 -Skips input characters until the next occurrence of the character with -ASCII code @var{N}. The argument to this predicate can take the same forms -as those for @code{put} (see 6.11). - -@item tab(+@var{N}) -@findex tab/1 -@syindex tab/1 -@cyindex tab/1 -Outputs @var{N} spaces to the current output stream. - -@item nl [ISO] -@findex nl/0 -@syindex nl/0 -@cyindex nl/0 -Outputs a new line to the current output stream. - -@end table - -@node I/O for Streams, C-Prolog to Terminal, I/O of Characters, I/O -@subsection Input/Output Predicates applied to Streams - -@table @code - -@item read(+@var{S},-@var{T}) [ISO] -@findex read/2 -@syindex read/2 -@cnindex read/2 -Reads term @var{T} from the stream @var{S} instead of from the current input -stream. - -@item read_term(+@var{S},-@var{T},+@var{Options}) [ISO] -@findex read_term/3 -@saindex read_term/3 -@cnindex read_term/3 -Reads term @var{T} from stream @var{S} with execution controlled by the -same options as @code{read_term/2}. - -@item write(+@var{S},@var{T}) [ISO] -@findex write/2 -@syindex write/2 -@cnindex write/2 -Writes term @var{T} to stream @var{S} instead of to the current output -stream. - -@item write_canonical(+@var{S},+@var{T}) [ISO] -@findex write_canonical/2 -@syindex write_canonical/2 -@cnindex write_canonical/2 -Displays term @var{T} on the stream @var{S}. Atoms are quoted when -necessary, and operators are ignored. - -@item write_canonical(+@var{T}) [ISO] -@findex write_canonical/1 -@syindex write_canonical/1 -@cnindex write_canonical/1 -Displays term @var{T}. Atoms are quoted when necessary, and operators -are ignored. - -@item write_term(+@var{S}, +@var{T}, +@var{Opts}) [ISO] -@findex write_term/3 -@syindex write_term/3 -@cnindex write_term/3 -Displays term @var{T} on the current output stream, according to the same -options used by @code{write_term/3}. - -@item writeq(+@var{S},@var{T}) [ISO] -@findex writeq/2 -@syindex writeq/2 -@cnindex writeq/2 -As @code{writeq/1}, but the output is sent to the stream @var{S}. - -@item display(+@var{S},@var{T}) -@findex display/2 -@syindex display/2 -@cnindex display/2 -Like @code{display/1}, but using stream @var{S} to display the term. - -@item print(+@var{S},@var{T}) -@findex print/2 -@syindex print/2 -@cnindex print/2 -Prints term @var{T} to the stream @var{S} instead of to the current output -stream. - -@item put(+@var{S},+@var{N}) -@findex put/2 -@syindex put/2 -@cnindex put/2 -As @code{put(N)}, but to stream @var{S}. - -@item put_byte(+@var{S},+@var{N}) [ISO] -@findex put_byte/2 -@snindex put_byte/2 -@cnindex put_byte/2 -As @code{put_byte(N)}, but to binary stream @var{S}. - -@item put_char(+@var{S},+@var{A}) [ISO] -@findex put_char/2 -@snindex put_char/2 -@cnindex put_char/2 -As @code{put_char(A)}, but to text stream @var{S}. - -@item put_code(+@var{S},+@var{N}) [ISO] -@findex put_code/2 -@snindex put_code/2 -@cnindex put_code/2 -As @code{put_code(N)}, but to text stream @var{S}. - -@item get(+@var{S},-@var{C}) -@findex get/2 -@syindex get/2 -@cnindex get/2 -The same as @code{get(C)}, but from stream @var{S}. - -@item get0(+@var{S},-@var{C}) -@findex get0/2 -@syindex get0/2 -@cnindex get0/2 -The same as @code{get0(C)}, but from stream @var{S}. - -@item get_byte(+@var{S},-@var{C}) [ISO] -@findex get_byte/2 -@snindex get_byte/2 -@cnindex get_byte/2 -If @var{C} is unbound, or is a character code, and the stream @var{S} is a -binary stream, read the next byte from that stream and unify its -code with @var{C}. - -@item get_char(+@var{S},-@var{C}) [ISO] -@findex get_char/2 -@snindex get_char/2 -@cnindex get_char/2 -If @var{C} is unbound, or is an atom representation of a character, and -the stream @var{S} is a text stream, read the next character from that -stream and unify its representation as an atom with @var{C}. - -@item get_code(+@var{S},-@var{C}) [ISO] -@findex get_code/2 -@snindex get_code/2 -@cnindex get_code/2 -If @var{C} is unbound, or is a character code, and the stream @var{S} is a -text stream, read the next character from that stream and unify its -code with @var{C}. - -@item peek_byte(+@var{S},-@var{C}) [ISO] -@findex peek_byte/2 -@snindex peek_byte/2 -@cnindex peek_byte/2 -If @var{C} is unbound, or is a character code, and @var{S} is a binary -stream, read the next byte from the current stream and unify its code -with @var{C}, while leaving the current stream position unaltered. - -@item peek_char(+@var{S},-@var{C}) [ISO] -@findex peek_char/2 -@snindex peek_char/2 -@cnindex peek_char/2 -If @var{C} is unbound, or is an atom representation of a character, and -the stream @var{S} is a text stream, read the next character from that -stream and unify its representation as an atom with @var{C}, while leaving -the current stream position unaltered. - -@item peek_code(+@var{S},-@var{C}) [ISO] -@findex peek_code/2 -@snindex peek_code/2 -@cnindex peek_code/2 -If @var{C} is unbound, or is an atom representation of a character, and -the stream @var{S} is a text stream, read the next character from that -stream and unify its representation as an atom with @var{C}, while leaving -the current stream position unaltered. - -@item skip(+@var{S},-@var{C}) -@findex skip/2 -@syindex skip/2 -@cnindex skip/2 -Like @code{skip/1}, but using stream @var{S} instead of the current -input stream. - -@item tab(+@var{S},+@var{N}) -@findex tab/2 -@syindex tab/2 -@cnindex tab/2 -The same as @code{tab/1}, but using stream @var{S}. - -@item nl(+@var{S}) [ISO] -@findex nl/1 -@syindex nl/1 -@cnindex nl/1 -Outputs a new line to stream @var{S}. - -@end table - -@node C-Prolog to Terminal, I/O Control, I/O for Streams, I/O -@subsection Compatible C-Prolog predicates for Terminal I/O - -@table @code - -@item ttyput(+@var{N}) -@findex ttyput/1 -@syindex ttyput/1 -@cnindex ttyput/1 -As @code{put(N)} but always to @code{user_output}. - -@item ttyget(-@var{C}) -@findex ttyget/1 -@syindex ttyget/1 -@cnindex ttyget/1 -The same as @code{get(C)}, but from stream @code{user_input}. - -@item ttyget0(-@var{C}) -@findex ttyget0/1 -@syindex ttyget0/1 -@cnindex ttyget0/1 -The same as @code{get0(C)}, but from stream @code{user_input}. - -@item ttyskip(-@var{C}) -@findex ttyskip/1 -@syindex ttyskip/1 -@cnindex ttyskip/1 -Like @code{skip/1}, but always using stream @code{user_input}. -stream. - -@item ttytab(+@var{N}) -@findex ttytab/1 -@syindex ttytab/1 -@cnindex ttytab/1 -The same as @code{tab/1}, but using stream @code{user_output}. - -@item ttynl -@findex ttynl/0 -@syindex ttynl/0 -@cnindex ttynl/0 -Outputs a new line to stream @code{user_output}. - -@end table - -@node I/O Control, Sockets, C-Prolog to Terminal, I/O -@subsection Controlling Input/Output - -@table @code - -@item exists(+@var{F}) -@findex exists/1 -@snindex exists/1 -@cyindex exists/1 -Checks if file @var{F} exists in the current directory. - -@item nofileerrors -@findex nofileerrors/0 -@syindex nofileerrors/0 -@cyindex nofileerrors/0 -Switches off the file_errors flag, so that the predicates @code{see/1}, -@code{tell/1}, @code{open/3} and @code{close/1} just fail, instead of producing -an error message and aborting whenever the specified file cannot be -opened or closed. - -@item fileerrors -@findex fileerrors/0 -@syindex fileerrors/0 -@cyindex fileerrors/0 -Switches on the file_errors flag so that in certain error conditions -I/O predicates will produce an appropriated message and abort. - -@item always_prompt_user -@findex always_prompt_user/0 -@snindex always_prompt_user/0 -@cnindex always_prompt_user/0 -Force the system to prompt the user even if the @code{user_input} stream -is not a terminal. This command is useful if you want to obtain -interactive control from a pipe or a socket. - -@end table - -@node Sockets, , I/O Control, I/O -@subsection Using Sockets From YAP - -YAP includes a SICStus Prolog compatible socket interface. In YAP-6.3 -this uses the @c{clib} package to emulate the old low level interface that -provides direct access to the major socket system calls. These calls -can be used both to open a new connection in the network or connect to -a networked server. Socket connections are described as read/write -streams, and standard I/O built-ins can be used to write on or read -from sockets. The following calls are available: - -@table @code - -@item socket(+@var{DOMAIN},+@var{TYPE},+@var{PROTOCOL},-@var{SOCKET}) -@findex socket/4 -@syindex socket/4 -@cnindex socket/4 -Corresponds to the BSD system call @code{socket}. Create a socket for -domain @var{DOMAIN} of type @var{TYPE} and protocol -@var{PROTOCOL}. Both @var{DOMAIN} and @var{TYPE} should be atoms, -whereas @var{PROTOCOL} must be an integer. -The new socket object is -accessible through a descriptor bound to the variable @var{SOCKET}. - -The current implementation of YAP only accepts one socket -domain: @code{'AF_INET'}. @c and @code{'AF_UNIX'}. -Socket types depend on the -underlying operating system, but at least the following types are -supported: @code{'SOCK_STREAM'} and @code{'SOCK_DGRAM'} (untested in 6.3). - -@item socket(+@var{DOMAIN},-@var{SOCKET}) -@findex socket/2 -@syindex socket/2 -@cnindex socket/2 - -Call @code{socket/4} with @var{TYPE} bound to @code{'SOCK_STREAM'} and -@var{PROTOCOL} bound to @code{0}. - -@item socket_close(+@var{SOCKET}) -@findex socket_close/1 -@syindex socket_close/1 -@cnindex socket_close/1 - -Close socket @var{SOCKET}. Note that sockets used in -@code{socket_connect} (that is, client sockets) should not be closed with -@code{socket_close}, as they will be automatically closed when the -corresponding stream is closed with @code{close/1} or @code{close/2}. - -@item socket_bind(+@var{SOCKET}, ?@var{PORT}) -@findex socket_bind/2 -@syindex socket_bind/2 -@cnindex socket_bind/2 - -Interface to system call @code{bind}, as used for servers: bind socket -to a port. Port information depends on the domain: -@table @code -@item 'AF_UNIX'(+@var{FILENAME}) (unsupported) -@item 'AF_FILE'(+@var{FILENAME}) -use file name @var{FILENAME} for UNIX or local sockets. - -@item 'AF_INET'(?@var{HOST},?PORT) -If @var{HOST} is bound to an atom, bind to host @var{HOST}, otherwise -if unbound bind to local host (@var{HOST} remains unbound). If port -@var{PORT} is bound to an integer, try to bind to the corresponding -port. If variable @var{PORT} is unbound allow operating systems to -choose a port number, which is unified with @var{PORT}. - -@end table - -@item socket_connect(+@var{SOCKET}, +@var{PORT}, -@var{STREAM}) -@findex socket_connect/3 -@syindex socket_connect/3 -@cnindex socket_connect/3 - -Interface to system call @code{connect}, used for clients: connect -socket @var{SOCKET} to @var{PORT}. The connection results in the -read/write stream @var{STREAM}. - -Port information depends on the domain: -@table @code -@item 'AF_UNIX'(+@var{FILENAME}) -@item 'AF_FILE'(+@var{FILENAME}) -connect to socket at file @var{FILENAME}. - -@item 'AF_INET'(+@var{HOST},+@var{PORT}) -Connect to socket at host @var{HOST} and port @var{PORT}. -@end table - -@item socket_listen(+@var{SOCKET}, +@var{LENGTH}) -@findex socket_listen/2 -@syindex socket_listen/2 -@cnindex socket_listen/2 -Interface to system call @code{listen}, used for servers to indicate -willingness to wait for connections at socket @var{SOCKET}. The -integer @var{LENGTH} gives the queue limit for incoming connections, -and should be limited to @code{5} for portable applications. The socket -must be of type @code{SOCK_STREAM} or @code{SOCK_SEQPACKET}. - -@item socket_accept(+@var{SOCKET}, -@var{STREAM}) -@findex socket_accept/2 -@syindex socket_accept/2 -@cnindex socket_accept/2 - -@item socket_accept(+@var{SOCKET}, -@var{CLIENT}, -@var{STREAM}) -@findex socket_accept/3 -@syindex socket_accept/3 -@cnindex socket_accept/3 -Interface to system call @code{accept}, used for servers to wait for -connections at socket @var{SOCKET}. The stream descriptor @var{STREAM} -represents the resulting connection. If the socket belongs to the -domain @code{'AF_INET'}, @var{CLIENT} unifies with an atom containing -the IP address for the client in numbers and dots notation. - -@item socket_accept(+@var{SOCKET}, -@var{STREAM}) -@findex socket_accept/2 -@syindex socket_accept/2 -@cnindex socket_accept/2 -Accept a connection but do not return client information. - -@item socket_buffering(+@var{SOCKET}, -@var{MODE}, -@var{OLD}, +@var{NEW}) -@findex socket_buffering/4 -@syindex socket_buffering/4 -@cnindex socket_buffering/4 -Set buffering for @var{SOCKET} in @code{read} or @code{write} -@var{MODE}. @var{OLD} is unified with the previous status, and @var{NEW} -receives the new status which may be one of @code{unbuf} or -@code{fullbuf}. - -@item socket_select(+@var{SOCKETS}, -@var{NEWSTREAMS}, +@var{TIMEOUT}, -+@var{STREAMS}, -@var{READSTREAMS}) [unsupported in YAP-6.3] -@findex socket_select/5 -@syindex socket_select/5 -@cnindex socket_select/5 -Interface to system call @code{select}, used for servers to wait for -connection requests or for data at sockets. The variable -@var{SOCKETS} is a list of form @var{KEY-SOCKET}, where @var{KEY} is -an user-defined identifier and @var{SOCKET} is a socket descriptor. The -variable @var{TIMEOUT} is either @code{off}, indicating execution will -wait until something is available, or of the form @var{SEC-USEC}, where -@var{SEC} and @var{USEC} give the seconds and microseconds before -@code{socket_select/5} returns. The variable @var{SOCKETS} is a list of -form @var{KEY-STREAM}, where @var{KEY} is an user-defined identifier -and @var{STREAM} is a stream descriptor - -Execution of @code{socket_select/5} unifies @var{READSTREAMS} from -@var{STREAMS} with readable data, and @var{NEWSTREAMS} with a list of -the form @var{KEY-STREAM}, where @var{KEY} was the key for a socket -with pending data, and @var{STREAM} the stream descriptor resulting -from accepting the connection. - -@item current_host(?@var{HOSTNAME}) -Unify @var{HOSTNAME} with an atom representing the fully qualified -hostname for the current host. Also succeeds if @var{HOSTNAME} is bound -to the unqualified hostname. - -@item hostname_address(?@var{HOSTNAME},?@var{IP_ADDRESS}) -@var{HOSTNAME} is an host name and @var{IP_ADDRESS} its IP -address in number and dots notation. - - -@end table - -@node Database, Sets, I/O, Top -@section Using the Clausal Data Base - -Predicates in YAP may be dynamic or static. By default, when -consulting or reconsulting, predicates are assumed to be static: -execution is faster and the code will probably use less space. -Static predicates impose some restrictions: in general there can be no -addition or removal of clauses for a procedure if it is being used in the -current execution. - -Dynamic predicates allow programmers to change the Clausal Data Base with -the same flexibility as in C-Prolog. With dynamic predicates it is -always possible to add or remove clauses during execution and the -semantics will be the same as for C-Prolog. But the programmer should be -aware of the fact that asserting or retracting are still expensive operations, -and therefore he should try to avoid them whenever possible. - -@table @code - -@item dynamic +@var{P} -@findex dynamic/1 -@saindex dynamic/1 -@cnindex dynamic/1 -Declares predicate @var{P} or list of predicates [@var{P1},...,@var{Pn}] -as a dynamic predicate. @var{P} must be written in form: -@var{name/arity}. - -@example -:- dynamic god/1. -@end example - -@noindent -a more convenient form can be used: - -@example -:- dynamic son/3, father/2, mother/2. -@end example - -or, equivalently, - -@example -:- dynamic [son/3, father/2, mother/2]. -@end example - -@noindent -Note: - -a predicate is assumed to be dynamic when -asserted before being defined. - -@item dynamic_predicate(+@var{P},+@var{Semantics}) -@findex dynamic_predicate/2 -@snindex dynamic_predicate/2 -@cnindex dynamic_predicate/2 -Declares predicate @var{P} or list of predicates [@var{P1},...,@var{Pn}] -as a dynamic predicate following either @code{logical} or -@code{immediate} semantics. - -@item compile_predicates(:@var{ListOfNameArity}) -@findex compile_predicates/1 -@snindex compile_predicates/1 -@cnindex compile_predicates/1 - -Compile a list of specified dynamic predicates (see @code{dynamic/1} and -@code{assert/1} into normal static predicates. This call tells the -Prolog environment the definition will not change anymore and further -calls to @code{assert/1} or @code{retract/1} on the named predicates -raise a permission error. This predicate is designed to deal with parts -of the program that is generated at runtime but does not change during -the remainder of the program execution. - -@menu - -Subnodes of Database -* Modifying the Database:: Asserting and Retracting -* Looking at the Database:: Finding out what is in the Data Base -* Database References:: Using Data Base References -* Internal Database:: YAP's Internal Database -* BlackBoard:: Storing and Fetching Terms in the BlackBoard - -@end menu - -@end table - -@node Modifying the Database, Looking at the Database, , Database -@subsection Modification of the Data Base - -These predicates can be used either for static or for dynamic -predicates: - -@table @code - -@item assert(+@var{C}) -@findex assert/1 -@saindex assert/1 -@caindex assert/1 - Same as @code{assertz/1}. Adds clause @var{C} to the program. If the predicate is undefined, -declare it as dynamic. New code should use @code{assertz/1} for better portability. - - Most Prolog systems only allow asserting clauses for dynamic -predicates. This is also as specified in the ISO standard. YAP allows -asserting clauses for static predicates, as long as the predicate is not -in use and the language flag is @t{cprolog}. Note that this feature is -deprecated, if you want to assert clauses for static procedures you -should use @code{assert_static/1}. - -@item asserta(+@var{C}) [ISO] -@findex asserta/1 -@saindex asserta/1 -@caindex asserta/1 - Adds clause @var{C} to the beginning of the program. If the predicate is -undefined, declare it as dynamic. - -@item assertz(+@var{C}) [ISO] -@findex assertz/1 -@saindex assertz/1 -@caindex assertz/1 - Adds clause @var{C} to the end of the program. If the predicate is -undefined, declare it as dynamic. - - Most Prolog systems only allow asserting clauses for dynamic -predicates. This is also as specified in the ISO standard. YAP allows -asserting clauses for static predicates. The current version of YAP -supports this feature, but this feature is deprecated and support may go -away in future versions. - -@item abolish(+@var{PredSpec}) [ISO] -@findex abolish/1 -@saindex abolish/1 -@caindex abolish/1 - Deletes the predicate given by @var{PredSpec} from the database. If -@var{PredSpec} is an unbound variable, delete all predicates for the -current module. The -specification must include the name and arity, and it may include module -information. Under @t{iso} language mode this built-in will only abolish -dynamic procedures. Under other modes it will abolish any procedures. - -@item abolish(+@var{P},+@var{N}) -@findex abolish/2 -@saindex abolish/2 -@caindex abolish/2 - Deletes the predicate with name @var{P} and arity @var{N}. It will remove -both static and dynamic predicates. - -@item assert_static(:@var{C}) -@findex assert_static/1 -@snindex assert_static/1 -@cnindex assert_static/1 -Adds clause @var{C} to a static procedure. Asserting a static clause -for a predicate while choice-points for the predicate are available has -undefined results. - -@item asserta_static(:@var{C}) -@findex asserta_static/1 -@snindex asserta_static/1 -@cnindex asserta_static/1 - Adds clause @var{C} to the beginning of a static procedure. - -@item assertz_static(:@var{C}) -@findex assertz_static/1 -@snindex assertz_static/1 -@cnindex assertz_static/1 - Adds clause @var{C} to the end of a static procedure. Asserting a -static clause for a predicate while choice-points for the predicate are -available has undefined results. - -@end table - -The following predicates can be used for dynamic predicates and for -static predicates, if source mode was on when they were compiled: - -@table @code - -@item clause(+@var{H},@var{B}) [ISO] -@findex clause/2 -@saindex clause/2 -@caindex clause/2 - A clause whose head matches @var{H} is searched for in the -program. Its head and body are respectively unified with @var{H} and -@var{B}. If the clause is a unit clause, @var{B} is unified with -@var{true}. - -This predicate is applicable to static procedures compiled with -@code{source} active, and to all dynamic procedures. - -@item clause(+@var{H},@var{B},-@var{R}) -@findex clause/3 -@saindex clause/3 -@caindex clause/3 -The same as @code{clause/2}, plus @var{R} is unified with the -reference to the clause in the database. You can use @code{instance/2} -to access the reference's value. Note that you may not use -@code{erase/1} on the reference on static procedures. - -@item nth_clause(+@var{H},@var{I},-@var{R}) -@findex nth_clause/3 -@saindex nth_clause/3 -@caindex nth_clause/3 -Find the @var{I}th clause in the predicate defining @var{H}, and give -a reference to the clause. Alternatively, if the reference @var{R} is -given the head @var{H} is unified with a description of the predicate -and @var{I} is bound to its position. - -@end table - -The following predicates can only be used for dynamic predicates: - -@table @code - -@item retract(+@var{C}) [ISO] -@findex retract/1 -@saindex retract/1 -@cnindex retract/1 -Erases the first clause in the program that matches @var{C}. This -predicate may also be used for the static predicates that have been -compiled when the source mode was @code{on}. For more information on -@code{source/0} (@pxref{Setting the Compiler}). - -@item retractall(+@var{G}) [ISO] -@findex retractall/1 -@saindex retractall/1 -@cnindex retractall/1 -Retract all the clauses whose head matches the goal @var{G}. Goal -@var{G} must be a call to a dynamic predicate. - -@end table - -@node Looking at the Database, Database References, Modifying the Database, Database -@subsection Looking at the Data Base - -@table @code - -@item listing -@findex listing/0 -@saindex listing/0 -@caindex listing/0 -Lists in the current output stream all the clauses for which source code -is available (these include all clauses for dynamic predicates and -clauses for static predicates compiled when source mode was @code{on}). - -@item listing(+@var{P}) -@findex listing/1 -@syindex listing/1 -@caindex listing/1 -Lists predicate @var{P} if its source code is available. - -@item portray_clause(+@var{C}) -@findex portray_clause/1 -@syindex portray_clause/1 -@cnindex portray_clause/1 -Write clause @var{C} as if written by @code{listing/0}. - -@item portray_clause(+@var{S},+@var{C}) -@findex portray_clause/2 -@syindex portray_clause/2 -@cnindex portray_clause/2 -Write clause @var{C} on stream @var{S} as if written by @code{listing/0}. - -@item current_atom(@var{A}) -@findex current_atom/1 -@syindex current_atom/1 -@cyindex current_atom/1 -Checks whether @var{A} is a currently defined atom. It is used to find all -currently defined atoms by backtracking. - -@item current_predicate(@var{F}) [ISO] -@findex current_predicate/1 -@syindex current_predicate/1 -@cyindex current_predicate/1 -@var{F} is the predicate indicator for a currently defined user or -library predicate. @var{F} is of the form @var{Na/Ar}, where the atom -@var{Na} is the name of the predicate, and @var{Ar} its arity. - -@item current_predicate(@var{A},@var{P}) -@findex current_predicate/2 -@syindex current_predicate/2 -@cnindex current_predicate/2 -Defines the relation: @var{P} is a currently defined predicate whose -name is the atom @var{A}. - -@item system_predicate(@var{A},@var{P}) -@findex system_predicate/2 -@syindex system_predicate/2 -@cnindex system_predicate/2 -Defines the relation: @var{P} is a built-in predicate whose name -is the atom @var{A}. - -@item predicate_property(@var{P},@var{Prop}) [ISO] -@findex predicate_property/2 -@saindex predicate_property/2 -@cnindex predicate_property/2 -For the predicates obeying the specification @var{P} unify @var{Prop} -with a property of @var{P}. These properties may be: -@table @code -@item built_in -true for built-in predicates, -@item dynamic -true if the predicate is dynamic -@item static -true if the predicate is static -@item meta_predicate(@var{M}) -true if the predicate has a meta_predicate declaration @var{M}. -@item multifile -true if the predicate was declared to be multifile -@item imported_from(@var{Mod}) -true if the predicate was imported from module @var{Mod}. -@item exported -true if the predicate is exported in the current module. -@item public -true if the predicate is public; note that all dynamic predicates are -public. -@item tabled -true if the predicate is tabled; note that only static predicates can -be tabled in YAP. -@item source -true if source for the predicate is available. -@item number_of_clauses(@var{ClauseCount}) -Number of clauses in the predicate definition. Always one if external -or built-in. -@end table - -@item predicate_statistics(@var{P},@var{NCls},@var{Sz},@var{IndexSz}) -@findex predicate_statistics/4 - -Given predicate @var{P}, @var{NCls} is the number of clauses for -@var{P}, @var{Sz} is the amount of space taken to store those clauses -(in bytes), and @var{IndexSz} is the amount of space required to store -indices to those clauses (in bytes). - -@item predicate_erased_statistics(@var{P},@var{NCls},@var{Sz},@var{IndexSz}) -@findex predicate_statistics/4 - -Given predicate @var{P}, @var{NCls} is the number of erased clauses for -@var{P} that could not be discarded yet, @var{Sz} is the amount of space -taken to store those clauses (in bytes), and @var{IndexSz} is the amount -of space required to store indices to those clauses (in bytes). - -@end table - -@node Database References, Internal Database, Looking at the Database, Database -@subsection Using Data Base References - -Data Base references are a fast way of accessing terms. The predicates -@code{erase/1} and @code{instance/1} also apply to these references and may -sometimes be used instead of @code{retract/1} and @code{clause/2}. - -@table @code - -@item assert(+@var{C},-@var{R}) -@findex assert/2 -@saindex assert/2 -@caindex assert/2 - The same as @code{assert(C)} (@pxref{Modifying the Database}) but -unifies @var{R} with the database reference that identifies the new -clause, in a one-to-one way. Note that @code{asserta/2} only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - -@item asserta(+@var{C},-@var{R}) -@findex asserta/2 -@saindex asserta/2 -@caindex asserta/2 - The same as @code{asserta(C)} but unifying @var{R} with -the database reference that identifies the new clause, in a -one-to-one way. Note that @code{asserta/2} only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - -@item assertz(+@var{C},-@var{R}) -@findex assertz/2 -@saindex assertz/2 -@caindex assertz/2 - The same as @code{assertz(C)} but unifying @var{R} with -the database reference that identifies the new clause, in a -one-to-one way. Note that @code{asserta/2} only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - -@item retract(+@var{C},-@var{R}) -@findex retract/2 -@saindex retract/2 -@caindex retract/2 - Erases from the program the clause @var{C} whose -database reference is @var{R}. The predicate must be dynamic. - - -@end table - -@node Internal Database, BlackBoard, Database References, Database -@section Internal Data Base -Some programs need global information for, e.g. counting or collecting -data obtained by backtracking. As a rule, to keep this information, the -internal data base should be used instead of asserting and retracting -clauses (as most novice programmers do), . -In YAP (as in some other Prolog systems) the internal data base (i.d.b. -for short) is faster, needs less space and provides a better insulation of -program and data than using asserted/retracted clauses. -The i.d.b. is implemented as a set of terms, accessed by keys that -unlikely what happens in (non-Prolog) data bases are not part of the -term. Under each key a list of terms is kept. References are provided so that -terms can be identified: each term in the i.d.b. has a unique reference -(references are also available for clauses of dynamic predicates). - -@table @code - -@item recorda(+@var{K},@var{T},-@var{R}) -@findex recorda/3 -@saindex recorda/3 -@cyindex recorda/3 -Makes term @var{T} the first record under key @var{K} and unifies @var{R} -with its reference. - -@item recordz(+@var{K},@var{T},-@var{R}) -@findex recordz/3 -@saindex recordz/3 -@cyindex recordz/3 -Makes term @var{T} the last record under key @var{K} and unifies @var{R} -with its reference. - -@item recorda_at(+@var{R0},@var{T},-@var{R}) -@findex recorda_at/3 -@snindex recorda_at/3 -@cnindex recorda_at/3 -Makes term @var{T} the record preceding record with reference -@var{R0}, and unifies @var{R} with its reference. - -@item recordz_at(+@var{R0},@var{T},-@var{R}) -@findex recordz_at/3 -@snindex recordz_at/3 -@cnindex recordz_at/3 -Makes term @var{T} the record following record with reference -@var{R0}, and unifies @var{R} with its reference. - -@item recordaifnot(+@var{K},@var{T},-@var{R}) -@findex recordaifnot/3 -@saindex recordaifnot/3 -@cnindex recordaifnot/3 -If a term equal to @var{T} up to variable renaming is stored under key -@var{K} fail. Otherwise, make term @var{T} the first record under key -@var{K} and unify @var{R} with its reference. - -@item recordzifnot(+@var{K},@var{T},-@var{R}) -@findex recorda/3 -@snindex recorda/3 -@cnindex recorda/3 -If a term equal to @var{T} up to variable renaming is stored under key -@var{K} fail. Otherwise, make term @var{T} the first record under key -@var{K} and unify @var{R} with its reference. - -@item recorded(+@var{K},@var{T},@var{R}) -@findex recorded/3 -@saindex recorded/3 -@cyindex recorded/3 -Searches in the internal database under the key @var{K}, a term that -unifies with @var{T} and whose reference matches @var{R}. This -built-in may be used in one of two ways: -@itemize @bullet -@item @var{K} may be given, in this case the built-in will return all -elements of the internal data-base that match the key. -@item @var{R} may be given, if so returning the key and element that -match the reference. -@end itemize - -@item erase(+@var{R}) -@findex erase/1 -@saindex erase/1 -@cyindex erase/1 -The term referred to by @var{R} is erased from the internal database. If -reference @var{R} does not exist in the database, @code{erase} just fails. - -@item erased(+@var{R}) -@findex erased/1 -@saindex erased/1 -@cyindex erased/1 -Succeeds if the object whose database reference is @var{R} has been -erased. - -@item instance(+@var{R},-@var{T}) -@findex instance/2 -@saindex instance/2 -@cyindex instance/2 -If @var{R} refers to a clause or a recorded term, @var{T} is unified -with its most general instance. If @var{R} refers to an unit clause -@var{C}, then @var{T} is unified with @code{@var{C} :- true}. When -@var{R} is not a reference to an existing clause or to a recorded term, -this goal fails. - -@item eraseall(+@var{K}) -@findex eraseall/1 -@snindex eraseall/1 -@cnindex eraseall/1 -All terms belonging to the key @code{K} are erased from the internal -database. The predicate always succeeds. - -@item current_key(?@var{A},?@var{K}) -@findex current_key/2 -@syindex current_key/2 -@cnindex current_key/2 -Defines the relation: @var{K} is a currently defined database key whose -name is the atom @var{A}. It can be used to generate all the keys for -the internal data-base. - -@item nth_instance(?@var{Key},?@var{Index},?@var{R}) -@findex nth_instance/3 -@saindex nth_instance/3 -@cnindex nth_instance/3 -Fetches the @var{Index}nth entry in the internal database under the key -@var{Key}. Entries are numbered from one. If the key @var{Key} or the -@var{Index} are bound, a reference is unified with @var{R}. Otherwise, -the reference @var{R} must be given, and YAP will find -the matching key and index. - - -@item nth_instance(?@var{Key},?@var{Index},@var{T},?@var{R}) -@findex nth_instance/4 -@saindex nth_instance/4 -@cnindex nth_instance/4 -Fetches the @var{Index}nth entry in the internal database under the key -@var{Key}. Entries are numbered from one. If the key @var{Key} or the -@var{Index} are bound, a reference is unified with @var{R}. Otherwise, -the reference @var{R} must be given, and YAP will find -the matching key and index. - -@item key_statistics(+@var{K},-@var{Entries},-@var{Size},-@var{IndexSize}) -@findex key_statistics/4 -@snindex key_statistics/4 -@cnindex key_statistics/4 -Returns several statistics for a key @var{K}. Currently, it says how -many entries we have for that key, @var{Entries}, what is the -total size spent on entries, @var{Size}, and what is the amount of -space spent in indices. - -@item key_statistics(+@var{K},-@var{Entries},-@var{TotalSize}) -@findex key_statistics/3 -@snindex key_statistics/3 -@cnindex key_statistics/3 -Returns several statistics for a key @var{K}. Currently, it says how -many entries we have for that key, @var{Entries}, what is the -total size spent on this key. - -@item get_value(+@var{A},-@var{V}) -@findex get_value/2 -@snindex get_value/2 -@cnindex get_value/2 -In YAP, atoms can be associated with constants. If one such -association exists for atom @var{A}, unify the second argument with the -constant. Otherwise, unify @var{V} with @code{[]}. - -This predicate is YAP specific. - -@item set_value(+@var{A},+@var{C}) -@findex set_value/2 -@snindex set_value/2 -@cnindex set_value/2 -Associate atom @var{A} with constant @var{C}. - -The @code{set_value} and @code{get_value} built-ins give a fast alternative to -the internal data-base. This is a simple form of implementing a global -counter. -@example - read_and_increment_counter(Value) :- - get_value(counter, Value), - Value1 is Value+1, - set_value(counter, Value1). -@end example -@noindent -This predicate is YAP specific. - -@item recordzifnot(+@var{K},@var{T},-@var{R}) -@findex recordzifnot/3 -@snindex recordzifnot/3 -@cnindex recordzifnot/3 -If a variant of @var{T} is stored under key @var{K} fail. Otherwise, make -term @var{T} the last record under key @var{K} and unify @var{R} with its -reference. - -This predicate is YAP specific. - -@item recordaifnot(+@var{K},@var{T},-@var{R}) -@findex recordaifnot/3 -@snindex recordaifnot/3 -@cnindex recordaifnot/3 -If a variant of @var{T} is stored under key @var{K} fail. Otherwise, make -term @var{T} the first record under key @var{K} and unify @var{R} with its -reference. - -This predicate is YAP specific. - -@end table - -There is a strong analogy between the i.d.b. and the way dynamic -predicates are stored. In fact, the main i.d.b. predicates might be -implemented using dynamic predicates: - -@example -recorda(X,T,R) :- asserta(idb(X,T),R). -recordz(X,T,R) :- assertz(idb(X,T),R). -recorded(X,T,R) :- clause(idb(X,T),R). -@end example -@noindent - We can take advantage of this, the other way around, as it is quite -easy to write a simple Prolog interpreter, using the i.d.b.: - -@example -asserta(G) :- recorda(interpreter,G,_). -assertz(G) :- recordz(interpreter,G,_). -retract(G) :- recorded(interpreter,G,R), !, erase(R). -call(V) :- var(V), !, fail. -call((H :- B)) :- !, recorded(interpreter,(H :- B),_), call(B). -call(G) :- recorded(interpreter,G,_). -@end example -@noindent -In YAP, much attention has been given to the implementation of the -i.d.b., especially to the problem of accelerating the access to terms kept in -a large list under the same key. Besides using the key, YAP uses an internal -lookup function, transparent to the user, to find only the terms that might -unify. For instance, in a data base containing the terms - -@example -b -b(a) -c(d) -e(g) -b(X) -e(h) -@end example - -@noindent -stored under the key k/1, when executing the query - -@example -:- recorded(k(_),c(_),R). -@end example - -@noindent -@code{recorded} would proceed directly to the third term, spending almost the -time as if @code{a(X)} or @code{b(X)} was being searched. - The lookup function uses the functor of the term, and its first three -arguments (when they exist). So, @code{recorded(k(_),e(h),_)} would go -directly to the last term, while @code{recorded(k(_),e(_),_)} would find -first the fourth term, and then, after backtracking, the last one. - - This mechanism may be useful to implement a sort of hierarchy, where -the functors of the terms (and eventually the first arguments) work as -secondary keys. - - In the YAP's i.d.b. an optimized representation is used for -terms without free variables. This results in a faster retrieval of terms -and better space usage. Whenever possible, avoid variables in terms in terms stored in the i.d.b. - - -@node BlackBoard, , Internal Database, Database -@section The Blackboard - -YAP implements a blackboard in the style of the SICStus Prolog -blackboard. The blackboard uses the same underlying mechanism as the -internal data-base but has several important differences: -@itemize @bullet -@item It is module aware, in contrast to the internal data-base. -@item Keys can only be atoms or integers, and not compound terms. -@item A single term can be stored per key. -@item An atomic update operation is provided; this is useful for -parallelism. -@end itemize - - -@table @code -@item bb_put(+@var{Key},?@var{Term}) -@findex bb_put/2 -@syindex bb_put/2 -@cnindex bb_put/2 -Store term table @var{Term} in the blackboard under key @var{Key}. If a -previous term was stored under key @var{Key} it is simply forgotten. - -@item bb_get(+@var{Key},?@var{Term}) -@findex bb_get/2 -@syindex bb_get/2 -@cnindex bb_get/2 -Unify @var{Term} with a term stored in the blackboard under key -@var{Key}, or fail silently if no such term exists. - -@item bb_delete(+@var{Key},?@var{Term}) -@findex bb_delete/2 -@syindex bb_delete/2 -@cnindex bb_delete/2 -Delete any term stored in the blackboard under key @var{Key} and unify -it with @var{Term}. Fail silently if no such term exists. - -@item bb_update(+@var{Key},?@var{Term},?@var{New}) -@findex bb_update/3 -@syindex bb_update/3 -@cnindex bb_update/3 -Atomically unify a term stored in the blackboard under key @var{Key} -with @var{Term}, and if the unification succeeds replace it by -@var{New}. Fail silently if no such term exists or if unification fails. - -@end table - -@node Sets, Grammars, Database, Top -@section Collecting Solutions to a Goal - -When there are several solutions to a goal, if the user wants to collect all -the solutions he may be led to use the data base, because backtracking will -forget previous solutions. - -YAP allows the programmer to choose from several system -predicates instead of writing his own routines. @code{findall/3} gives you -the fastest, but crudest solution. The other built-in predicates -post-process the result of the query in several different ways: - -@table @code - -@item findall(@var{T},+@var{G},-@var{L}) [ISO] -@findex findall/3 -@syindex findall/3 -@cyindex findall/3 -Unifies @var{L} with a list that contains all the instantiations of the -term @var{T} satisfying the goal @var{G}. - -With the following program: -@example -a(2,1). -a(1,1). -a(2,2). -@end example -@noindent -the answer to the query -@example -findall(X,a(X,Y),L). -@end example -@noindent -would be: -@example -X = _32 -Y = _33 -L = [2,1,2]; -no -@end example - -@item findall(@var{T},+@var{G},+@var{L},-@var{L0}) -@findex findall/4 -@syindex findall/4 -@cnindex findall/4 -Similar to @code{findall/3}, but appends all answers to list @var{L0}. - -@item all(@var{T},+@var{G},-@var{L}) -@findex all/3 -@snindex all/3 -@cnindex all/3 -Similar to @code{findall(@var{T},@var{G},@var{L})} but eliminate -repeated elements. Thus, assuming the same clauses as in the above -example, the reply to the query - -@example -all(X,a(X,Y),L). -@end example -@noindent -would be: - -@example -X = _32 -Y = _33 -L = [2,1]; -no -@end example - -Note that @code{all/3} will fail if no answers are found. - -@item bagof(@var{T},+@var{G},-@var{L}) [ISO] -@findex bagof/3 -@saindex bagof/3 -@cyindex bagof/3 -For each set of possible instances of the free variables occurring in -@var{G} but not in @var{T}, generates the list @var{L} of the instances of -@var{T} satisfying @var{G}. Again, assuming the same clauses as in the -examples above, the reply to the query - -@example -bagof(X,a(X,Y),L). - -would be: -X = _32 -Y = 1 -L = [2,1]; -X = _32 -Y = 2 -L = [2]; -no -@end example - -@item setof(@var{X},+@var{P},-@var{B}) [ISO] -@findex setof/3 -@saindex setof/3 -@cyindex setof/3 -Similar to @code{bagof(@var{T},@var{G},@var{L})} but sorting list -@var{L} and keeping only one copy of each element. Again, assuming the -same clauses as in the examples above, the reply to the query -@example -setof(X,a(X,Y),L). -@end example -@noindent -would be: -@example -X = _32 -Y = 1 -L = [1,2]; -X = _32 -Y = 2 -L = [2]; -no -@end example - -@end table - -@node Grammars, OS, Sets, Top -@section Grammar Rules - -Grammar rules in Prolog are both a convenient way to express definite -clause grammars and an extension of the well known context-free grammars. - -A grammar rule is of the form: - -@example -@i{ head --> body } -@end example -@noindent -where both @i{head} and @i{body} are sequences of one or more items -linked by the standard conjunction operator ','. - -@emph{Items can be:} - -@itemize @bullet -@item -a @emph{non-terminal} symbol may be either a complex term or an atom. -@item -a @emph{terminal} symbol may be any Prolog symbol. Terminals are -written as Prolog lists. -@item -an @emph{empty body} is written as the empty list '[ ]'. -@item -@emph{extra conditions} may be inserted as Prolog procedure calls, by being -written inside curly brackets '@{' and '@}'. -@item -the left side of a rule consists of a nonterminal and an optional list -of terminals. -@item -alternatives may be stated in the right-hand side of the rule by using -the disjunction operator ';'. -@item -the @emph{cut} and @emph{conditional} symbol ('->') may be inserted in the -right hand side of a grammar rule -@end itemize - -Grammar related built-in predicates: - -@table @code - -@item expand_term(@var{T},-@var{X}) -@findex expand_term/2 -@syindex expand_term/2 -@cyindex expand_term/2 - -This predicate is used by YAP for preprocessing each top level -term read when consulting a file and before asserting or executing it. -It rewrites a term @var{T} to a term @var{X} according to the following -rules: first try @code{term_expansion/2} in the current module, and then try to use the user defined predicate -@code{user:term_expansion/2}. If this call fails then the translating process -for DCG rules is applied, together with the arithmetic optimizer -whenever the compilation of arithmetic expressions is in progress. - -@item @var{CurrentModule}:term_expansion(@var{T},-@var{X}) -@item user:term_expansion(@var{T},-@var{X}) -@findex term_expansion/2 -@syindex term_expansion/2 -@cyindex term_expansion/2 -This user-defined predicate is called by @code{expand_term/3} to -preprocess all terms read when consulting a file. If it succeeds: - -@itemize -@item -If @var{X} is of the form @code{:- G} or @code{?- G}, it is processed as -a directive. -@item -If @var{X} is of the form @code{'$source_location'(, -):} it is processed as if from @code{File} and line -@code{Line}. - -@item -If @var{X} is a list, all terms of the list are asserted or processed -as directives. -@item The term @var{X} is asserted instead of @var{T}. -@end itemize - -@item @var{CurrentModule}:goal_expansion(+@var{G},+@var{M},-@var{NG}) -@item user:goal_expansion(+@var{G},+@var{M},-@var{NG}) -@findex goal_expansion/3 -@snindex goal_expansion/3 -@cnindex goal_expansion/3 -YAP now supports @code{goal_expansion/3}. This is an user-defined -procedure that is called after term expansion when compiling or -asserting goals for each sub-goal in a clause. The first argument is -bound to the goal and the second to the module under which the goal -@var{G} will execute. If @code{goal_expansion/3} succeeds the new -sub-goal @var{NG} will replace @var{G} and will be processed in the same -way. If @code{goal_expansion/3} fails the system will use the default -rules. - -@item phrase(+@var{P},@var{L},@var{R}) -@findex phrase/3 -@syindex phrase/3 -@cnindex phrase/3 -This predicate succeeds when the difference list @code{@var{L}-@var{R}} -is a phrase of type @var{P}. - -@item phrase(+@var{P},@var{L}) -@findex phrase/2 -@syindex phrase/2 -@cnindex phrase/2 -This predicate succeeds when @var{L} is a phrase of type @var{P}. The -same as @code{phrase(P,L,[])}. - -Both this predicate and the previous are used as a convenient way to -start execution of grammar rules. - -@item 'C'(@var{S1},@var{T},@var{S2}) -@findex C/3 -@syindex C/3 -@cnindex C/3 -This predicate is used by the grammar rules compiler and is defined as -@code{'C'([H|T],H,T)}. - -@end table - -@node OS, Term Modification, Grammars, Top -@section Access to Operating System Functionality - -The following built-in predicates allow access to underlying -Operating System functionality: - -@table @code - -@item cd(+@var{D}) -@findex cd/1 -@snindex cd/1 -@cnindex cd/1 -Changes the current directory (on UNIX environments). - -@item cd -@findex cd/0 -@snindex cd/0 -@cnindex cd/0 -Changes the current directory (on UNIX environments) to the user's home directory. - -@item environ(+@var{E},-@var{S}) -@findex environ/2 -@syindex environ/2 -@cnindex environ/2 -@comment This backtrackable predicate unifies the first argument with an -@comment environment variable @var{E}, and the second with its value @var{S}. It -@comment can used to detect all environment variables. - Given an environment variable @var{E} this predicate unifies the second argument @var{S} with its value. - -@item getcwd(-@var{D}) -@findex getcwd/1 -@snindex getcwd/1 -@cnindex getcwd/1 -Unify the current directory, represented as an atom, with the argument -@var{D}. - -@item pwd -@findex pwd/0 -@snindex pwd/0 -@cnindex pwd/0 -Prints the current directory. - -@item ls -@findex ls/0 -@snindex ls/0 -@cnindex ls/0 -Prints a list of all files in the current directory. - -@item putenv(+@var{E},+@var{S}) -@findex putenv/2 -@snindex putenv/2 -@cnindex putenv/2 -Set environment variable @var{E} to the value @var{S}. If the -environment variable @var{E} does not exist, create a new one. Both the -environment variable and the value must be atoms. - -@item rename(+@var{F},+@var{G}) -@findex rename/2 -@snindex rename/2 -@cyindex rename/2 -Renames file @var{F} to @var{G}. - -@item sh -@findex sh/0 -@snindex sh/0 -@cyindex sh/0 -Creates a new shell interaction. - -@item system(+@var{S}) -@findex system/1 -@snindex system/1 -@cyindex system/1 -Passes command @var{S} to the Bourne shell (on UNIX environments) or the -current command interpreter in WIN32 environments. - -@item unix(+@var{S}) -@findex unix/1 -@snindex unix/1 -@cnindex unix/1 -Access to Unix-like functionality: -@table @code -@item argv/1 -Return a list of arguments to the program. These are the arguments that -follow a @code{--}, as in the usual Unix convention. -@item cd/0 -Change to home directory. -@item cd/1 -Change to given directory. Acceptable directory names are strings or -atoms. -@item environ/2 -If the first argument is an atom, unify the second argument with the -value of the corresponding environment variable. -@item getcwd/1 -Unify the first argument with an atom representing the current directory. -@item putenv/2 -Set environment variable @var{E} to the value @var{S}. If the -environment variable @var{E} does not exist, create a new one. Both the -environment variable and the value must be atoms. -@item shell/1 -Execute command under current shell. Acceptable commands are strings or -atoms. -@item system/1 -Execute command with @code{/bin/sh}. Acceptable commands are strings or -atoms. -@item shell/0 -Execute a new shell. -@end table - -@item working_directory(-@var{CurDir},?@var{NextDir}) -@findex working_directory/2 -@syindex working_directory/2 -@cnindex working_directory/2 @c -Fetch the current directory at @var{CurDir}. If @var{NextDir} is bound -to an atom, make its value the current working directory. - -@item alarm(+@var{Seconds},+@var{Callable},+@var{OldAlarm}) -@findex alarm/3 -@snindex alarm/3 -@cnindex alarm/3 -Arranges for YAP to be interrupted in @var{Seconds} seconds, or in -[@var{Seconds}|@var{MicroSeconds}]. When interrupted, YAP will execute -@var{Callable} and then return to the previous execution. If -@var{Seconds} is @code{0}, no new alarm is scheduled. In any event, -any previously set alarm is canceled. - -The variable @var{OldAlarm} unifies with the number of seconds remaining -until any previously scheduled alarm was due to be delivered, or with -@code{0} if there was no previously scheduled alarm. - -Note that execution of @var{Callable} will wait if YAP is -executing built-in predicates, such as Input/Output operations. - -The next example shows how @var{alarm/3} can be used to implement a -simple clock: - -@example -loop :- loop. - -ticker :- write('.'), flush_output, - get_value(tick, yes), - alarm(1,ticker,_). - -:- set_value(tick, yes), alarm(1,ticker,_), loop. -@end example - -The clock, @code{ticker}, writes a dot and then checks the flag -@code{tick} to see whether it can continue ticking. If so, it calls -itself again. Note that there is no guarantee that the each dot -corresponds a second: for instance, if the YAP is waiting for -user input, @code{ticker} will wait until the user types the entry in. - -The next example shows how @code{alarm/3} can be used to guarantee that -a certain procedure does not take longer than a certain amount of time: - -@example -loop :- loop. - -:- catch((alarm(10, throw(ball), _),loop), - ball, - format('Quota exhausted.~n',[])). -@end example -In this case after @code{10} seconds our @code{loop} is interrupted, -@code{ball} is thrown, and the handler writes @code{Quota exhausted}. -Execution then continues from the handler. - -Note that in this case @code{loop/0} always executes until the alarm is -sent. Often, the code you are executing succeeds or fails before the -alarm is actually delivered. In this case, you probably want to disable -the alarm when you leave the procedure. The next procedure does exactly so: -@example -once_with_alarm(Time,Goal,DoOnAlarm) :- - catch(execute_once_with_alarm(Time, Goal), alarm, DoOnAlarm). - -execute_once_with_alarm(Time, Goal) :- - alarm(Time, alarm, _), - ( call(Goal) -> alarm(0, alarm, _) ; alarm(0, alarm, _), fail). -@end example - -The procedure @code{once_with_alarm/3} has three arguments: -the @var{Time} to wait before the alarm is -sent; the @var{Goal} to execute; and the goal @var{DoOnAlarm} to execute -if the alarm is sent. It uses @code{catch/3} to handle the case the -@code{alarm} is sent. Then it starts the alarm, calls the goal -@var{Goal}, and disables the alarm on success or failure. - -@item on_signal(+@var{Signal},?@var{OldAction},+@var{Callable}) -@findex on_signal/3 -@snindex on_signal/3 -@cnindex on_signal/3 -Set the interrupt handler for soft interrupt @var{Signal} to be -@var{Callable}. @var{OldAction} is unified with the previous handler. - -Only a subset of the software interrupts (signals) can have their -handlers manipulated through @code{on_signal/3}. -Their POSIX names, YAP names and default behavior is given below. -The "YAP name" of the signal is the atom that is associated with -each signal, and should be used as the first argument to -@code{on_signal/3}. It is chosen so that it matches the signal's POSIX -name. - -@code{on_signal/3} succeeds, unless when called with an invalid -signal name or one that is not supported on this platform. No checks -are made on the handler provided by the user. - -@table @code -@item sig_up (Hangup) - SIGHUP in Unix/Linux; Reconsult the initialization files - ~/.yaprc, ~/.prologrc and ~/prolog.ini. -@item sig_usr1 and sig_usr2 (User signals) - SIGUSR1 and SIGUSR2 in Unix/Linux; Print a message and halt. -@end table - -A special case is made, where if @var{Callable} is bound to -@code{default}, then the default handler is restored for that signal. - -A call in the form @code{on_signal(@var{S},@var{H},@var{H})} can be used -to retrieve a signal's current handler without changing it. - -It must be noted that although a signal can be received at all times, -the handler is not executed while YAP is waiting for a query at the -prompt. The signal will be, however, registered and dealt with as soon -as the user makes a query. - -Please also note, that neither POSIX Operating Systems nor YAP guarantee -that the order of delivery and handling is going to correspond with the -order of dispatch. - -@end table - -@node Term Modification, Global Variables, OS, Top -@section Term Modification - -@cindex updating terms -It is sometimes useful to change the value of instantiated -variables. Although, this is against the spirit of logic programming, it -is sometimes useful. As in other Prolog systems, YAP has -several primitives that allow updating Prolog terms. Note that these -primitives are also backtrackable. - -The @code{setarg/3} primitive allows updating any argument of a Prolog -compound terms. The @code{mutable} family of predicates provides -@emph{mutable variables}. They should be used instead of @code{setarg/3}, -as they allow the encapsulation of accesses to updatable -variables. Their implementation can also be more efficient for long -deterministic computations. - -@table @code -@item setarg(+@var{I},+@var{S},?@var{T}) -@findex setarg/3n -@snindex setarg/3n -@cnindex setarg/3n -Set the value of the @var{I}th argument of term @var{S} to term @var{T}. - -@cindex mutable variables -@item create_mutable(+@var{D},-@var{M}) -@findex create_mutable/2 -@syindex create_mutable/2 -@cnindex create_mutable/2 -Create new mutable variable @var{M} with initial value @var{D}. - -@item get_mutable(?@var{D},+@var{M}) -@findex get_mutable/2 -@syindex get_mutable/2 -@cnindex get_mutable/2 -Unify the current value of mutable term @var{M} with term @var{D}. - -@item is_mutable(?@var{D}) -@findex is_mutable/1 -@syindex is_mutable/1 -@cnindex is_mutable/1 -Holds if @var{D} is a mutable term. - -@item get_mutable(?@var{D},+@var{M}) -@findex get_mutable/2 -@syindex get_mutable/2 -@cnindex get_mutable/2 -Unify the current value of mutable term @var{M} with term @var{D}. - -@item update_mutable(+@var{D},+@var{M}) -@findex update_mutable/2 -@syindex update_mutable/2 -@cnindex update_mutable/2 -Set the current value of mutable term @var{M} to term @var{D}. -@end table - -@node Global Variables, Profiling, Term Modification, Top -@section Global Variables - -@cindex global variables - -Global variables are associations between names (atoms) and -terms. They differ in various ways from storing information using -@code{assert/1} or @code{recorda/3}. - -@itemize @bullet -@item The value lives on the Prolog (global) stack. This implies that -lookup time is independent from the size of the term. This is -particularly interesting for large data structures such as parsed XML -documents or the CHR global constraint store. - -@item They support both global assignment using @code{nb_setval/2} and -backtrackable assignment using @code{b_setval/2}. - -@item Only one value (which can be an arbitrary complex Prolog term) -can be associated to a variable at a time. - -@item Their value cannot be shared among threads. Each thread has its own -namespace and values for global variables. -@end itemize - -Currently global variables are scoped globally. We may consider module -scoping in future versions. Both @code{b_setval/2} and -@code{nb_setval/2} implicitly create a variable if the referenced name -does not already refer to a variable. - -Global variables may be initialised from directives to make them -available during the program lifetime, but some considerations are -necessary for saved-states and threads. Saved-states to not store -global variables, which implies they have to be declared with -@code{initialization/1} to recreate them after loading the saved -state. Each thread has its own set of global variables, starting with -an empty set. Using @code{thread_initialization/1} to define a global -variable it will be defined, restored after reloading a saved state -and created in all threads that are created after the -registration. Finally, global variables can be initialised using the -exception hook called @code{exception/3}. The latter technique is used -by CHR. - -@table @code -@item b_setval(+@var{Name}, +@var{Value}) -@findex b_setval/2 -@snindex b_setval/2 -@cnindex b_setval/2 -Associate the term @var{Value} with the atom @var{Name} or replaces -the currently associated value with @var{Value}. If @var{Name} does -not refer to an existing global variable a variable with initial value -[] is created (the empty list). On backtracking the assignment is -reversed. - -@item b_getval(+@var{Name}, -@var{Value}) -@findex b_getval/2 -@snindex b_getval/2 -@cnindex b_getval/2 -Get the value associated with the global variable @var{Name} and unify -it with @var{Value}. Note that this unification may further -instantiate the value of the global variable. If this is undesirable -the normal precautions (double negation or @code{copy_term/2}) must be -taken. The @code{b_getval/2} predicate generates errors if @var{Name} is not -an atom or the requested variable does not exist. - -Notice that for compatibility with other systems @var{Name} @emph{must} be already associated with a term: otherwise the system will generate an error. - -@item nb_setval(+@var{Name}, +@var{Value}) -@findex nb_setval/2 -@snindex nb_setval/2 -@cnindex nb_setval/2 -Associates a copy of @var{Value} created with @code{duplicate_term/2} with -the atom @var{Name}. Note that this can be used to set an initial -value other than @code{[]} prior to backtrackable assignment. - -@item nb_getval(+@var{Name}, -@var{Value}) -@findex nb_getval/2 -@snindex nb_getval/2 -@cnindex nb_getval/2 -The @code{nb_getval/2} predicate is a synonym for @code{b_getval/2}, -introduced for compatibility and symmetry. As most scenarios will use -a particular global variable either using non-backtrackable or -backtrackable assignment, using @code{nb_getval/2} can be used to -document that the variable is used non-backtrackable. - -@item nb_linkval(+@var{Name}, +@var{Value}) -@findex nb_linkval/2 -@snindex nb_linkval/2 -@cnindex nb_linkval/2 -Associates the term @var{Value} with the atom @var{Name} without -copying it. This is a fast special-purpose variation of @code{nb_setval/2} -intended for expert users only because the semantics on backtracking -to a point before creating the link are poorly defined for compound -terms. The principal term is always left untouched, but backtracking -behaviour on arguments is undone if the original assignment was -trailed and left alone otherwise, which implies that the history that -created the term affects the behaviour on backtracking. Please -consider the following example: - -@example -demo_nb_linkval :- - T = nice(N), - ( N = world, - nb_linkval(myvar, T), - fail - ; nb_getval(myvar, V), - writeln(V) - ). -@end example - -@item nb_set_shared_val(+@var{Name}, +@var{Value}) -@findex nb_set_shared_val/2 -@snindex nb_set_shared_val/2 -@cnindex nb_set_shared_val/2 -Associates the term @var{Value} with the atom @var{Name}, but sharing -non-backtrackable terms. This may be useful if you want to rewrite a -global variable so that the new copy will survive backtracking, but -you want to share structure with the previous term. - -The next example shows the differences between the three built-ins: -@example -?- nb_setval(a,a(_)),nb_getval(a,A),nb_setval(b,t(C,A)),nb_getval(b,B). -A = a(_A), -B = t(_B,a(_C)) ? - -?- nb_setval(a,a(_)),nb_getval(a,A),nb_set_shared_val(b,t(C,A)),nb_getval(b,B). - -?- nb_setval(a,a(_)),nb_getval(a,A),nb_linkval(b,t(C,A)),nb_getval(b,B). -A = a(_A), -B = t(C,a(_A)) ? -@end example - -@item nb_setarg(+@{Arg], +@var{Term}, +@var{Value}) -@findex nb_setarg/3 -@snindex nb_setarg/3 -@cnindex nb_setarg/3 - -Assigns the @var{Arg}-th argument of the compound term @var{Term} with -the given @var{Value} as setarg/3, but on backtracking the assignment -is not reversed. If @var{Term} is not atomic, it is duplicated using -duplicate_term/2. This predicate uses the same technique as -@code{nb_setval/2}. We therefore refer to the description of -@code{nb_setval/2} for details on non-backtrackable assignment of -terms. This predicate is compatible to GNU-Prolog -@code{setarg(A,T,V,false)}, removing the type-restriction on -@var{Value}. See also @code{nb_linkarg/3}. Below is an example for -counting the number of solutions of a goal. Note that this -implementation is thread-safe, reentrant and capable of handling -exceptions. Realising these features with a traditional implementation -based on assert/retract or flag/3 is much more complicated. - -@example - succeeds_n_times(Goal, Times) :- - Counter = counter(0), - ( Goal, - arg(1, Counter, N0), - N is N0 + 1, - nb_setarg(1, Counter, N), - fail - ; arg(1, Counter, Times) - ). -@end example - -@item nb_set_shared_arg(+@var{Arg}, +@var{Term}, +@var{Value}) -@findex nb_set_shared_arg/3 -@snindex nb_set_shared_arg/3 -@cnindex nb_set_shared_arg/3 - -As @code{nb_setarg/3}, but like @code{nb_linkval/2} it does not -duplicate the global sub-terms in @var{Value}. Use with extreme care -and consult the documentation of @code{nb_linkval/2} before use. - -@item nb_linkarg(+@var{Arg}, +@var{Term}, +@var{Value}) -@findex nb_linkarg/3 -@snindex nb_lnkarg/3 -@cnindex nb_linkarg/3 - -As @code{nb_setarg/3}, but like @code{nb_linkval/2} it does not -duplicate @var{Value}. Use with extreme care and consult the -documentation of @code{nb_linkval/2} before use. - - -@item nb_current(?@var{Name}, ?@var{Value}) -@findex nb_current/2 -@snindex nb_current/2 -@cnindex nb_current/2 -Enumerate all defined variables with their value. The order of -enumeration is undefined. - -@item nb_delete(+@var{Name}) -@findex nb_delete/2 -@snindex nb_delete/2 -@cnindex nb_delete/2 -Delete the named global variable. -@end table - -Global variables have been introduced by various Prolog -implementations recently. We follow the implementation of them in -SWI-Prolog, itself based on hProlog by Bart Demoen. - -GNU-Prolog provides a rich set of global variables, including -arrays. Arrays can be implemented easily in YAP and SWI-Prolog using -@code{functor/3} and @code{setarg/3} due to the unrestricted arity of -compound terms. - - -@node Profiling, Call Counting, Global Variables, Top -@section Profiling Prolog Programs - -@cindex profiling - -YAP includes two profilers. The count profiler keeps information on the -number of times a predicate was called. This information can be used to -detect what are the most commonly called predicates in the program. The -count profiler can be compiled by setting YAP's flag @code{profiling} -to @code{on}. The time-profiler is a @code{gprof} profiler, and counts -how many ticks are being spent on specific predicates, or on other -system functions such as internal data-base accesses or garbage collects. - -The YAP profiling sub-system is currently under -development. Functionality for this sub-system will increase with newer -implementation. - -@subsection The Count Profiler - -@strong{Notes:} - -The count profiler works by incrementing counters at procedure entry or -backtracking. It provides exact information: - -@itemize @bullet -@item Profiling works for both static and dynamic predicates. -@item Currently only information on entries and retries to a predicate -are maintained. This may change in the future. -@item As an example, the following user-level program gives a list of -the most often called procedures in a program. The procedure -@code{list_profile} shows all procedures, irrespective of module, and -the procedure @code{list_profile/1} shows the procedures being used in -a specific module. -@example -list_profile :- - % get number of calls for each profiled procedure - setof(D-[M:P|D1],(current_module(M),profile_data(M:P,calls,D),profile_data(M:P,retries,D1)),LP), - % output so that the most often called - % predicates will come last: - write_profile_data(LP). - -list_profile(Module) :- - % get number of calls for each profiled procedure - setof(D-[Module:P|D1],(profile_data(Module:P,calls,D),profile_data(Module:P,retries,D1)),LP), - % output so that the most often called - % predicates will come last: - write_profile_data(LP). - -write_profile_data([]). -write_profile_data([D-[M:P|R]|SLP]) :- - % swap the two calls if you want the most often - % called predicates first. - format('~a:~w: ~32+~t~d~12+~t~d~12+~n', [M,P,D,R]), - write_profile_data(SLP). -@end example -@end itemize - -These are the current predicates to access and clear profiling data: - -@table @code -@item profile_data(?@var{Na/Ar}, ?@var{Parameter}, -@var{Data}) -@findex profile_data/3 -@snindex profile_data/3 -@cnindex profile_data/3 -Give current profile data on @var{Parameter} for a predicate described -by the predicate indicator @var{Na/Ar}. If any of @var{Na/Ar} or -@var{Parameter} are unbound, backtrack through all profiled predicates -or stored parameters. Current parameters are: - -@table @code -@item calls -Number of times a procedure was called. - -@item retries - Number of times a call to the procedure was backtracked to and retried. -@end table - -@item profile_reset -@findex profiled_reset/0 -@snindex profiled_reset/0 -@cnindex profiled_reset/0 -Reset all profiling information. - -@end table - -@subsection Tick Profiler -The tick profiler works by interrupting the Prolog code every so often -and checking at each point the code was. The profiler must be able to -retrace the state of the abstract machine at every moment. The major -advantage of this approach is that it gives the actual amount of time -being spent per procedure, or whether garbage collection dominates -execution time. The major drawback is that tracking down the state of -the abstract machine may take significant time, and in the worst case -may slow down the whole execution. - -The following procedures are available: - -@table @code -@item profinit -@findex profinit/0 -@snindex profinit/0 -@cnindex profinit/0 -Initialise the data-structures for the profiler. Unnecessary for -dynamic profiler. - -@item profon -@findex profon/0 -@snindex profon/0 -@cnindex profon/0 -Start profiling. - -@item profoff -@findex profoff/0 -@snindex profoff/0 -@cnindex profoff/0 -Stop profiling. - -@item showprofres -@findex showprofres/0 -@snindex showprofres/0 -@cnindex showprofres/0 -Show profiling info. - -@item showprofres(@var{N}) -@findex showprofres/1 -@snindex showprofres/1 -@cnindex showprofres/1 -Show profiling info for the top-most @var{N} predicates. - -@end table - -The @code{showprofres/0} and @code{showprofres/1} predicates call a user-defined multifile hook predicate, @code{user:prolog_predicate_name/2}, that can be used for converting a possibly explicitly-qualified callable term into an atom that will used when printing the profiling information. - -@node Call Counting, Arrays, Profiling, Top -@section Counting Calls - -@cindex Counting Calls -Predicates compiled with YAP's flag @code{call_counting} set to -@code{on} update counters on the numbers of calls and of -retries. Counters are actually decreasing counters, so that they can be -used as timers. Three counters are available: -@itemize @bullet -@item @code{calls}: number of predicate calls since execution started or since -system was reset; -@item @code{retries}: number of retries for predicates called since -execution started or since counters were reset; -@item @code{calls_and_retries}: count both on predicate calls and -retries. -@end itemize -These counters can be used to find out how many calls a certain -goal takes to execute. They can also be used as timers. - -The code for the call counters piggybacks on the profiling -code. Therefore, activating the call counters also activates the profiling -counters. - -These are the predicates that access and manipulate the call counters: - -@table @code -@item call_count_data(-@var{Calls}, -@var{Retries}, -@var{CallsAndRetries}) -@findex call_count_data/3 -@snindex call_count_data/3 -@cnindex call_count_data/3 -Give current call count data. The first argument gives the current value -for the @var{Calls} counter, next the @var{Retries} counter, and last -the @var{CallsAndRetries} counter. - -@item call_count_reset -@findex call_count_data/0 -@snindex call_count_data/0 -@cnindex call_count_data/0 -Reset call count counters. All timers are also reset. - -@item call_count(?@var{CallsMax}, ?@var{RetriesMax}, ?@var{CallsAndRetriesMax}) -@findex call_count_data/3 -@snindex call_count_data/3 -@cnindex call_count_data/3 -Set call count counter as timers. YAP will generate an exception -if one of the instantiated call counters decreases to 0. YAP will ignore -unbound arguments: -@itemize @bullet -@item @var{CallsMax}: throw the exception @code{call_counter} when the -counter @code{calls} reaches 0; -@item @var{RetriesMax}: throw the exception @code{retry_counter} when the -counter @code{retries} reaches 0; -@item @var{CallsAndRetriesMax}: throw the exception -@code{call_and_retry_counter} when the counter @code{calls_and_retries} -reaches 0. -@end itemize -@end table - -Next, we show a simple example of how to use call counters: -@example - ?- yap_flag(call_counting,on), [-user]. l :- l. end_of_file. yap_flag(call_counting,off). - -yes - -yes - ?- catch((call_count(10000,_,_),l),call_counter,format("limit_exceeded.~n",[])). - -limit_exceeded. - -yes -@end example -Notice that we first compile the looping predicate @code{l/0} with -@code{call_counting} @code{on}. Next, we @code{catch/3} to handle an -exception when @code{l/0} performs more than 10000 reductions. - - -@node Arrays, Preds, Call Counting , Top -@section Arrays - -The YAP system includes experimental support for arrays. The -support is enabled with the option @code{YAP_ARRAYS}. - -There are two very distinct forms of arrays in YAP. The -@emph{dynamic arrays} are a different way to access compound terms -created during the execution. Like any other terms, any bindings to -these terms and eventually the terms themselves will be destroyed during -backtracking. Our goal in supporting dynamic arrays is twofold. First, -they provide an alternative to the standard @code{arg/3} -built-in. Second, because dynamic arrays may have name that are globally -visible, a dynamic array can be visible from any point in the -program. In more detail, the clause -@example -g(X) :- array_element(a,2,X). -@end example -will succeed as long as the programmer has used the built-in @t{array/2} -to create an array term with at least 3 elements in the current -environment, and the array was associated with the name @code{a}. The -element @code{X} is a Prolog term, so one can bind it and any such -bindings will be undone when backtracking. Note that dynamic arrays do -not have a type: each element may be any Prolog term. - -The @emph{static arrays} are an extension of the database. They provide -a compact way for manipulating data-structures formed by characters, -integers, or floats imperatively. They can also be used to provide -two-way communication between YAP and external programs through -shared memory. - -In order to efficiently manage space elements in a static array must -have a type. Currently, elements of static arrays in YAP should -have one of the following predefined types: - -@itemize @bullet -@item @code{byte}: an 8-bit signed character. -@item @code{unsigned_byte}: an 8-bit unsigned character. -@item @code{int}: Prolog integers. Size would be the natural size for -the machine's architecture. -@item @code{float}: Prolog floating point number. Size would be equivalent -to a double in @code{C}. -@item @code{atom}: a Prolog atom. -@item @code{dbref}: an internal database reference. -@item @code{term}: a generic Prolog term. Note that this will term will -not be stored in the array itself, but instead will be stored in the -Prolog internal database. -@end itemize - -Arrays may be @emph{named} or @emph{anonymous}. Most arrays will be -@emph{named}, that is associated with an atom that will be used to find -the array. Anonymous arrays do not have a name, and they are only of -interest if the @code{TERM_EXTENSIONS} compilation flag is enabled. In -this case, the unification and parser are extended to replace -occurrences of Prolog terms of the form @code{X[I]} by run-time calls to -@code{array_element/3}, so that one can use array references instead of -extra calls to @code{arg/3}. As an example: -@example -g(X,Y,Z,I,J) :- X[I] is Y[J]+Z[I]. -@end example -should give the same results as: -@example -G(X,Y,Z,I,J) :- - array_element(X,I,E1), - array_element(Y,J,E2), - array_element(Z,I,E3), - E1 is E2+E3. -@end example - -Note that the only limitation on array size are the stack size for -dynamic arrays; and, the heap size for static (not memory mapped) -arrays. Memory mapped arrays are limited by available space in the file -system and in the virtual memory space. - -The following predicates manipulate arrays: - -@table @code - -@item array(+@var{Name}, +@var{Size}) -@findex array/2 -@snindex array/2 -@cnindex array/2 -Creates a new dynamic array. The @var{Size} must evaluate to an -integer. The @var{Name} may be either an atom (named array) or an -unbound variable (anonymous array). - -Dynamic arrays work as standard compound terms, hence space for the -array is recovered automatically on backtracking. - -@item static_array(+@var{Name}, +@var{Size}, +@var{Type}) -@findex static_array/3 -@snindex static_array/3 -@cnindex static_array/3 -Create a new static array with name @var{Name}. Note that the @var{Name} -must be an atom (named array). The @var{Size} must evaluate to an -integer. The @var{Type} must be bound to one of types mentioned -previously. - -@item reset_static_array(+@var{Name}) -@findex reset_static_array/1 -@snindex reset_static_array/1 -@cnindex reset_static_array/1 -Reset static array with name @var{Name} to its initial value. - -@item static_array_location(+@var{Name}, -@var{Ptr}) -@findex static_array_location/4 -@snindex static_array_location/4 -@cnindex static_array_location/4 -Give the location for a static array with name -@var{Name}. - -@item static_array_properties(?@var{Name}, ?@var{Size}, ?@var{Type}) -@findex static_array_properties/3 -@snindex static_array_properties/3 -@cnindex static_array_properties/3 -Show the properties size and type of a static array with name -@var{Name}. Can also be used to enumerate all current -static arrays. - -This built-in will silently fail if the there is no static array with -that name. - -@item static_array_to_term(?@var{Name}, ?@var{Term}) -@findex static_array_to_term/3 -@snindex static_array_to_term/3 -@cnindex static_array_to_term/3 -Convert a static array with name -@var{Name} to a compound term of name @var{Name}. - -This built-in will silently fail if the there is no static array with -that name. - -@item mmapped_array(+@var{Name}, +@var{Size}, +@var{Type}, +@var{File}) -@findex static_array/3 -@snindex static_array/3 -@cnindex static_array/3 -Similar to @code{static_array/3}, but the array is memory mapped to file -@var{File}. This means that the array is initialized from the file, and -that any changes to the array will also be stored in the file. - -This built-in is only available in operating systems that support the -system call @code{mmap}. Moreover, mmapped arrays do not store generic -terms (type @code{term}). - -@item close_static_array(+@var{Name}) -@findex close_static_array/1 -@snindex close_static_array/1 -@cnindex close_static_array/1 -Close an existing static array of name @var{Name}. The @var{Name} must -be an atom (named array). Space for the array will be recovered and -further accesses to the array will return an error. - -@item resize_static_array(+@var{Name}, -@var{OldSize}, +@var{NewSize}) -@findex resize_static_array/3 -@snindex resize_static_array/3 -@cnindex resize_static_array/3 -Expand or reduce a static array, The @var{Size} must evaluate to an -integer. The @var{Name} must be an atom (named array). The @var{Type} -must be bound to one of @code{int}, @code{dbref}, @code{float} or -@code{atom}. - -Note that if the array is a mmapped array the size of the mmapped file -will be actually adjusted to correspond to the size of the array. - -@item array_element(+@var{Name}, +@var{Index}, ?@var{Element}) -@findex array_element/3 -@snindex array_element/3 -@cnindex array_element/3 -Unify @var{Element} with @var{Name}[@var{Index}]. It works for both -static and dynamic arrays, but it is read-only for static arrays, while -it can be used to unify with an element of a dynamic array. - -@item update_array(+@var{Name}, +@var{Index}, ?@var{Value}) -@findex update_array/3 -@snindex update_array/3 -@cnindex update_array/3 -Attribute value @var{Value} to @var{Name}[@var{Index}]. Type -restrictions must be respected for static arrays. This operation is -available for dynamic arrays if @code{MULTI_ASSIGNMENT_VARIABLES} is -enabled (true by default). Backtracking undoes @var{update_array/3} for -dynamic arrays, but not for static arrays. - -Note that @code{update_array/3} actually uses @code{setarg/3} to update -elements of dynamic arrays, and @code{setarg/3} spends an extra cell for -every update. For intensive operations we suggest it may be less -expensive to unify each element of the array with a mutable terms and -to use the operations on mutable terms. - -@item add_to_array_element(+@var{Name}, +@var{Index}, , +@var{Number}, ?@var{NewValue}) -@findex add_to_array_element/4 -@snindex add_to_array_element/4 -@cnindex add_to_array_element/4 -Add @var{Number} @var{Name}[@var{Index}] and unify @var{NewValue} with -the incremented value. Observe that @var{Name}[@var{Index}] must be an -number. If @var{Name} is a static array the type of the array must be -@code{int} or @code{float}. If the type of the array is @code{int} you -only may add integers, if it is @code{float} you may add integers or -floats. If @var{Name} corresponds to a dynamic array the array element -must have been previously bound to a number and @code{Number} can be -any kind of number. - -The @code{add_to_array_element/3} built-in actually uses -@code{setarg/3} to update elements of dynamic arrays. For intensive -operations we suggest it may be less expensive to unify each element -of the array with a mutable terms and to use the operations on mutable -terms. - -@end table - -@node Preds, Misc, Arrays, Top -@section Predicate Information - -Built-ins that return information on the current predicates and modules: - -@table @code -@c ......... begin of 'module' documentation ......... -@item current_module(@var{M}) -@findex current_module/1 -@syindex current_module/1 -@cnindex current_module/1 -Succeeds if @var{M} are defined modules. A module is defined as soon as some -predicate defined in the module is loaded, as soon as a goal in the -module is called, or as soon as it becomes the current type-in module. - -@item current_module(@var{M},@var{F}) -@findex current_module/2 -@syindex current_module/2 -@cnindex current_module/2 -Succeeds if @var{M} are current modules associated to the file @var{F}. - -@c .......... end of 'module' documentation .......... -@end table - -@node Misc, , Preds, Top -@section Miscellaneous - -@table @code - -@item statistics/0 -@findex statistics/0 -@saindex statistics/0 -@cyindex statistics/0 -Send to the current user error stream general information on space used and time -spent by the system. -@example -?- statistics. -memory (total) 4784124 bytes - program space 3055616 bytes: 1392224 in use, 1663392 free - 2228132 max - stack space 1531904 bytes: 464 in use, 1531440 free - global stack: 96 in use, 616684 max - local stack: 368 in use, 546208 max - trail stack 196604 bytes: 8 in use, 196596 free - - 0.010 sec. for 5 code, 2 stack, and 1 trail space overflows - 0.130 sec. for 3 garbage collections which collected 421000 bytes - 0.000 sec. for 0 atom garbage collections which collected 0 bytes - 0.880 sec. runtime - 1.020 sec. cputime - 25.055 sec. elapsed time - -@end example -The example shows how much memory the system spends. Memory is divided -into Program Space, Stack Space and Trail. In the example we have 3MB -allocated for program spaces, with less than half being actually -used. YAP also shows the maximum amount of heap space having been used -which was over 2MB. - -The stack space is divided into two stacks which grow against each -other. We are in the top level so very little stack is being used. On -the other hand, the system did use a lot of global and local stack -during the previous execution (we refer the reader to a WAM tutorial in -order to understand what are the global and local stacks). - -YAP also shows information on how many memory overflows and garbage -collections the system executed, and statistics on total execution -time. Cputime includes all running time, runtime excludes garbage -collection and stack overflow time. - -@item statistics(?@var{Param},-@var{Info}) -@findex statistics/2 -@saindex statistics/2 -@cnindex statistics/2 -Gives statistical information on the system parameter given by first -argument: - -@table @code - -@item atoms -@findex atoms (statistics/2 option) -@code{[@var{NumberOfAtoms},@var{SpaceUsedBy Atoms}]} -@* -This gives the total number of atoms @code{NumberOfAtoms} and how much -space they require in bytes, @var{SpaceUsedBy Atoms}. - -@item cputime -@findex cputime (statistics/2 option) -@code{[@var{Time since Boot},@var{Time From Last Call to Cputime}]} -@* -This gives the total cputime in milliseconds spent executing Prolog code, -garbage collection and stack shifts time included. - -@item dynamic_code -@findex dynamic_code (statistics/2 option) -@code{[@var{Clause Size},@var{Index Size},@var{Tree Index -Size},@var{Choice Point Instructions -Size},@var{Expansion Nodes Size},@var{Index Switch Size}]} -@* -Size of static code in YAP in bytes: @var{Clause Size}, the number of -bytes allocated for clauses, plus -@var{Index Size}, the number of bytes spent in the indexing code. The -indexing code is divided into main tree, @var{Tree Index -Size}, tables that implement choice-point manipulation, @var{Choice Point Instructions -Size}, tables that cache clauses for future expansion of the index -tree, @var{Expansion Nodes Size}, and -tables such as hash tables that select according to value, @var{Index Switch Size}. - -@item garbage_collection -@findex garbage_collection (statistics/2 option) -@code{[@var{Number of GCs},@var{Total Global Recovered},@var{Total Time -Spent}]} -@* -Number of garbage collections, amount of space recovered in kbytes, and -total time spent doing garbage collection in milliseconds. More detailed -information is available using @code{yap_flag(gc_trace,verbose)}. - -@item global_stack -@findex global_stack (statistics/2 option) -@code{[@var{Global Stack Used},@var{Execution Stack Free}]} -@* -Space in kbytes currently used in the global stack, and space available for -expansion by the local and global stacks. - -@item local_stack -@findex local_stack (statistics/2 option) -@code{[@var{Local Stack Used},@var{Execution Stack Free}]} -@* -Space in kbytes currently used in the local stack, and space available for -expansion by the local and global stacks. - -@item heap -@findex heap (statistics/2 option) -@code{[@var{Heap Used},@var{Heap Free}]} -@* -Total space in kbytes not recoverable -in backtracking. It includes the program code, internal data base, and, -atom symbol table. - -@item program -@findex program (statistics/2 option) -@code{[@var{Program Space Used},@var{Program Space Free}]} -@* -Equivalent to @code{heap}. - -@item runtime -@findex runtime (statistics/2 option) -@code{[@var{Time since Boot},@var{Time From Last Call to Runtime}]} -@* -This gives the total cputime in milliseconds spent executing Prolog -code, not including garbage collections and stack shifts. Note that -until YAP4.1.2 the @code{runtime} statistics would return time spent on -garbage collection and stack shifting. - -@item stack_shifts -@findex stack_shifts (statistics/2 option) -@code{[@var{Number of Heap Shifts},@var{Number of Stack -Shifts},@var{Number of Trail Shifts}]} -@* -Number of times YAP had to -expand the heap, the stacks, or the trail. More detailed information is -available using @code{yap_flag(gc_trace,verbose)}. - -@item static_code -@findex static_code (statistics/2 option) -@code{[@var{Clause Size},@var{Index Size},@var{Tree Index -Size},@var{Expansion Nodes Size},@var{Index Switch Size}]} -@* -Size of static code in YAP in bytes: @var{Clause Size}, the number of -bytes allocated for clauses, plus -@var{Index Size}, the number of bytes spent in the indexing code. The -indexing code is divided into a main tree, @var{Tree Index -Size}, table that cache clauses for future expansion of the index -tree, @var{Expansion Nodes Size}, and and -tables such as hash tables that select according to value, @var{Index Switch Size}. - -@item trail -@findex trail (statistics/2 option) -@code{[@var{Trail Used},@var{Trail Free}]} -@* -Space in kbytes currently being used and still available for the trail. - -@item walltime -@findex walltime (statistics/2 option) -@code{[@var{Time since Boot},@var{Time From Last Call to Walltime}]} -@* -This gives the clock time in milliseconds since starting Prolog. - -@end table - -@item time(:@var{Goal}) -@findex time/1 -@snindex time/1 -@cnindex time/1 -Prints the CPU time and the wall time for the execution of @var{Goal}. -Possible choice-points of @var{Goal} are removed. Based on the SWI-Prolog -definition (minus reporting the number of inferences, which YAP currently -does not support). - -@item yap_flag(?@var{Param},?@var{Value}) -@findex yap_flag/2 -@snindex yap_flag/2 -@cnindex yap_flag/2 -Set or read system properties for @var{Param}: - -@table @code - -@item argv -@findex argv (yap_flag/2 option) -@* Read-only flag. It unifies with a list of atoms that gives the -arguments to YAP after @code{--}. - -@item agc_margin -@findex agc_margin (yap_flag/2 option) -An integer: if this amount of atoms has been created since the last -atom-garbage collection, perform atom garbage collection at the first -opportunity. Initial value is 10,000. May be changed. A value of 0 -(zero) disables atom garbage collection. - -@item associate -@findex associate (yap_flag/2 option) -@* -Read-write flag telling a suffix for files associated to Prolog -sources. It is @code{yap} by default. - -@item bounded [ISO] -@findex bounded (yap_flag/2 option) -@* -Read-only flag telling whether integers are bounded. The value depends -on whether YAP uses the GMP library or not. - -@item profiling -@findex call_counting (yap_flag/2 option) -@* -If @code{off} (default) do not compile call counting information for -procedures. If @code{on} compile predicates so that they calls and -retries to the predicate may be counted. Profiling data can be read through the -@code{call_count_data/3} built-in. - -@item char_conversion [ISO] -@findex char_conversion (yap_flag/2 option) -@* -Writable flag telling whether a character conversion table is used when -reading terms. The default value for this flag is @code{off} except in -@code{sicstus} and @code{iso} language modes, where it is @code{on}. - -@item character_escapes [ISO] -@findex character_escapes (yap_flag/2 option) -@* Writable flag telling whether a character escapes are enables, -@code{true}, or disabled, @code{false}. The default value for this flag is -@code{on}. - -@c You can also use @code{cprolog} mode, which corresponds to @code{off}, -@c @code{iso} mode, which corresponds to @code{on}, and @code{sicstus} -@c mode, which corresponds to the mode traditionally used in SICStus -@c Prolog. In this mode back-quoted escape sequences should not close with -@c a backquote and unrecognized escape codes do not result in error. - -@item debug [ISO] -@findex debug (yap_flag/2 option) -@* -If @var{Value} is unbound, tell whether debugging is @code{true} or -@code{false}. If @var{Value} is bound to @code{true} enable debugging, and if -it is bound to @code{false} disable debugging. - -+@item debugger_print_options -@findex debugger_print_options (yap_flag/2 option) -@* -If bound, set the argument to the @code{write_term/3} options the -debugger uses to write terms. If unbound, show the current options. - -@item dialect -@findex dialect (yap_flag/2 option) -@* -Read-only flag that always returns @code{yap}. - -@item discontiguous_warnings -@findex discontiguous_warnings (yap_flag/2 option) -@* -If @var{Value} is unbound, tell whether warnings for discontiguous -predicates are @code{on} or -@code{off}. If @var{Value} is bound to @code{on} enable these warnings, -and if it is bound to @code{off} disable them. The default for YAP is -@code{off}, unless we are in @code{sicstus} or @code{iso} mode. - -@item dollar_as_lower_case -@findex dollar_as_lower_case (yap_flag/2 option) -@* -If @code{off} (default) consider the character '$' a control character, if -@code{on} consider '$' a lower case character. - -@item double_quotes [ISO] -@findex double_quotes (yap_flag/2 option) -@* -If @var{Value} is unbound, tell whether a double quoted list of characters -token is converted to a list of atoms, @code{chars}, to a list of integers, -@code{codes}, or to a single atom, @code{atom}. If @var{Value} is bound, set to -the corresponding behavior. The default value is @code{codes}. - -@item executable -@findex executable(yap_flag/2 option) -@* Read-only flag. It unifies with an atom that gives the -original program path. - -@item fast -@findex fast (yap_flag/2 option) -@* -If @code{on} allow fast machine code, if @code{off} (default) disable it. Only -available in experimental implementations. - -@item fileerrors -@findex fileerrors (yap_flag/2 option) -@* -If @code{on} @code{fileerrors} is @code{on}, if @code{off} (default) -@code{fileerrors} is disabled. - -@item float_format -@findex float_format (yap_flag/2 option) -@* C-library @code{printf()} format specification used by @code{write/1} and -friends to determine how floating point numbers are printed. The -default is @code{%.15g}. The specified value is passed to @code{printf()} -without further checking. For example, if you want less digits -printed, @code{%g} will print all floats using 6 digits instead of the -default 15. - -@item gc -@findex gc (yap_flag/2 option) -@* -If @code{on} allow garbage collection (default), if @code{off} disable it. - -@item gc_margin -@findex gc_margin (yap_flag/2 option) -@* -Set or show the minimum free stack before starting garbage -collection. The default depends on total stack size. - -@item gc_trace -@findex gc_trace (yap_flag/2 option) -@* If @code{off} (default) do not show information on garbage collection -and stack shifts, if @code{on} inform when a garbage collection or stack -shift happened, if @code{verbose} give detailed information on garbage -collection and stack shifts. Last, if @code{very_verbose} give detailed -information on data-structures found during the garbage collection -process, namely, on choice-points. - -@item generate_debugging_info -@findex generate_debugging_info (yap_flag/2 option) -@* If @code{true} (default) generate debugging information for -procedures, including source mode. If @code{false} predicates no -information is generated, although debugging is still possible, and -source mode is disabled. - -@item host_type -@findex host_type (yap_flag/2 option) -@* Return @code{configure} system information, including the machine-id -for which YAP was compiled and Operating System information. - -@item index -@findex index (yap_flag/2 option) -@* If @code{on} allow indexing (default), if @code{off} disable it, if -@code{single} allow on first argument only. - -@item index_sub_term_search_depth -@findex index (yap_flag/2 option) -@* -Maximum bound on searching sub-terms for indexing, if @code{0} (default) no bound. - -@item informational_messages -@findex informational_messages (yap_flag/2 option) -@* -If @code{on} allow printing of informational messages, such as the ones -that are printed when consulting. If @code{off} disable printing -these messages. It is @code{on} by default except if YAP is booted with -the @code{-L} flag. - -@item integer_rounding_function [ISO] -@findex integer_rounding_function (yap_flag/2 option) -@* -Read-only flag telling the rounding function used for integers. Takes the value -@code{toward_zero} for the current version of YAP. - -@item language -@findex language (yap_flag/2 option) -@* -Choose whether YAP is closer to C-Prolog, @code{cprolog}, iso-prolog, -@code{iso} or SICStus Prolog, @code{sicstus}. The current default is -@code{cprolog}. This flag affects update semantics, leashing mode, -style checking, handling calls to undefined procedures, how directives -are interpreted, when to use dynamic, character escapes, and how files -are consulted. - -@item max_arity [ISO] -@findex max_arity (yap_flag/2 option) -@* -Read-only flag telling the maximum arity of a functor. Takes the value -@code{unbounded} for the current version of YAP. - -@item max_integer [ISO] -@findex max_integer (yap_flag/2 option) -@* -Read-only flag telling the maximum integer in the -implementation. Depends on machine and Operating System -architecture, and on whether YAP uses the @code{GMP} multi-precision -library. If @code{bounded} is false, requests for @code{max_integer} -will fail. - -@item max_tagged_integer -@findex max_tagged_integer (yap_flag/2 option) -@* -Read-only flag telling the maximum integer we can store as a single -word. Depends on machine and Operating System -architecture. It can be used to find the word size of the current machine. - -@item min_integer [ISO] -@findex min_integer (yap_flag/2 option) -@* Read-only flag telling the minimum integer in the -implementation. Depends on machine and Operating System architecture, -and on whether YAP uses the @code{GMP} multi-precision library. If -@code{bounded} is false, requests for @code{min_integer} will fail. - -@item min_tagged_integer -@findex max_tagged_integer (yap_flag/2 option) -@* -Read-only flag telling the minimum integer we can store as a single -word. Depends on machine and Operating System -architecture. - -@item n_of_integer_keys_in_bb -@findex n_of_integer_keys_in_bb (yap_flag/2 option) -@* -Read or set the size of the hash table that is used for looking up the -blackboard when the key is an integer. - -@item occurs_check -@findex occurs_check (yap_flag/2 option) -@* -Current read-only and set to @code{false}. - -@item n_of_integer_keys_in_db -@findex n_of_integer_keys_in_db (yap_flag/2 option) -@* -Read or set the size of the hash table that is used for looking up the -internal data-base when the key is an integer. - -@item open_expands_filename -@findex open_expands_filename (yap_flag/2 option) -@* -If @code{true} the @code{open/3} builtin performs filename-expansion -before opening a file (SICStus Prolog like). If @code{false} it does not -(SWI-Prolog like). - -@item open_shared_object -@findex open_shared_object (yap_flag/2 option) -@* -If true, @code{open_shared_object/2} and friends are implemented, -providing access to shared libraries (@code{.so} files) or to dynamic link -libraries (@code{.DLL} files). - -@item profiling -@findex profiling (yap_flag/2 option) -@* -If @code{off} (default) do not compile profiling information for -procedures. If @code{on} compile predicates so that they will output -profiling information. Profiling data can be read through the -@code{profile_data/3} built-in. - -@item prompt_alternatives_on(atom, changeable) -@findex prompt_alternatives_on (yap_flag/2 option) -SWI-Compatible option, determines prompting for alternatives in the Prolog toplevel. Default is @t{groundness}, YAP prompts for alternatives if and only if the query contains variables. The alternative, default in SWI-Prolog is @t{determinism} which implies the system prompts for alternatives if the goal succeeded while leaving choicepoints. - - -@item redefine_warnings -@findex discontiguous_warnings (yap_flag/2 option) -@* -If @var{Value} is unbound, tell whether warnings for procedures defined -in several different files are @code{on} or -@code{off}. If @var{Value} is bound to @code{on} enable these warnings, -and if it is bound to @code{off} disable them. The default for YAP is -@code{off}, unless we are in @code{sicstus} or @code{iso} mode. - -@item shared_object_search_path -@findex shared_object_search_path (yap_flag/2 option) -Name of the environment variable used by the system to search for shared -objects. - -@item shared_object_extension -@findex shared_object_extension (yap_flag/2 option) -Suffix associated with loadable code. - -@item single_var_warnings -@findex single_var_warnings (yap_flag/2 option) -@* -If @var{Value} is unbound, tell whether warnings for singleton variables -are @code{on} or @code{off}. If @var{Value} is bound to @code{on} enable -these warnings, and if it is bound to @code{off} disable them. The -default for YAP is @code{off}, unless we are in @code{sicstus} or -@code{iso} mode. - -@item strict_iso -@findex strict_iso (yap_flag/2 option) -@* - If @var{Value} is unbound, tell whether strict ISO compatibility mode -is @code{on} or @code{off}. If @var{Value} is bound to @code{on} set -language mode to @code{iso} and enable strict mode. If @var{Value} is -bound to @code{off} disable strict mode, and keep the current language -mode. The default for YAP is @code{off}. - -Under strict ISO Prolog mode all calls to non-ISO built-ins generate an -error. Compilation of clauses that would call non-ISO built-ins will -also generate errors. Pre-processing for grammar rules is also -disabled. Module expansion is still performed. - -Arguably, ISO Prolog does not provide all the functionality required -from a modern Prolog system. Moreover, because most Prolog -implementations do not fully implement the standard and because the -standard itself gives the implementor latitude in a few important -questions, such as the unification algorithm and maximum size for -numbers there is no guarantee that programs compliant with this mode -will work the same way in every Prolog and in every platform. We thus -believe this mode is mostly useful when investigating how a program -depends on a Prolog's platform specific features. - -@item stack_dump_on_error -@findex stack_dump_on_error (yap_flag/2 option) -@* -If @code{on} show a stack dump when YAP finds an error. The default is -@code{off}. - -@item syntax_errors -@findex syntax_errors (yap_flag/2 option) -@* -Control action to be taken after syntax errors while executing @code{read/1}, -@code{read/2}, or @code{read_term/3}: -@table @code - -@item dec10 -@* -Report the syntax error and retry reading the term. - -@item fail -@* -Report the syntax error and fail (default). - -@item error -@* -Report the syntax error and generate an error. - -@item quiet -@* -Just fail -@end table - -@item system_options -@findex system_options (yap_flag/2 option) -@* This read only flag tells which options were used to compile -YAP. Currently it informs whether the system supports @code{big_numbers}, -@code{coroutining}, @code{depth_limit}, @code{low_level_tracer}, -@code{or-parallelism}, @code{rational_trees}, @code{readline}, @code{tabling}, -@code{threads}, or the @code{wam_profiler}. - -@item tabling_mode -@* Sets or reads the tabling mode for all tabled predicates. Please -@pxref{Tabling} for the list of options. - -@item to_chars_mode -@findex to_chars_modes (yap_flag/2 option) -@* Define whether YAP should follow @code{quintus}-like -semantics for the @code{atom_chars/1} or @code{number_chars/1} built-in, -or whether it should follow the ISO standard (@code{iso} option). - -+@item toplevel_hook -@findex toplevel_hook (yap_flag/2 option) -@* -+If bound, set the argument to a goal to be executed before entering the -top-level. If unbound show the current goal or @code{true} if none is -presented. Only the first solution is considered and the goal is not -backtracked into. - -+@item toplevel_print_options -@findex toplevel_print_options (yap_flag/2 option) -@* -+If bound, set the argument to the @code{write_term/3} options used to write -terms from the top-level. If unbound, show the current options. - -@item typein_module -@findex typein_module (yap_flag/2 option) -@* -If bound, set the current working or type-in module to the argument, -which must be an atom. If unbound, unify the argument with the current -working module. - -@item unix -@findex unix (yap_flag/2 option) -@* Read-only Boolean flag that unifies with @code{true} if YAP is -running on an Unix system. Defined if the C-compiler used to compile -this version of YAP either defines @code{__unix__} or @code{unix}. - -@item unknown [ISO] -@findex unknown (yap_flag/2 option) -@* -Corresponds to calling the @code{unknown/2} built-in. Possible values -are @code{error}, @code{fail}, and @code{warning}. - -@item update_semantics -@findex update_semantics (yap_flag/2 option) -@* -Define whether YAP should follow @code{immediate} update -semantics, as in C-Prolog (default), @code{logical} update semantics, -as in Quintus Prolog, SICStus Prolog, or in the ISO standard. There is -also an intermediate mode, @code{logical_assert}, where dynamic -procedures follow logical semantics but the internal data base still -follows immediate semantics. - -@item user_error -@findex user_error (yap_flag/2 option) -@* -If the second argument is bound to a stream, set @code{user_error} to -this stream. If the second argument is unbound, unify the argument with -the current @code{user_error} stream. - -By default, the @code{user_error} stream is set to a stream -corresponding to the Unix @code{stderr} stream. - -The next example shows how to use this flag: -@example - ?- open( '/dev/null', append, Error, - [alias(mauri_tripa)] ). - -Error = '$stream'(3) ? ; - -no - ?- set_prolog_flag(user_error, mauri_tripa). - -close(mauri_tripa). - -yes - ?- -@end example -We execute three commands. First, we open a stream in write mode and -give it an alias, in this case @code{mauri_tripa}. Next, we set -@code{user_error} to the stream via the alias. Note that after we did so -prompts from the system were redirected to the stream -@code{mauri_tripa}. Last, we close the stream. At this point, YAP -automatically redirects the @code{user_error} alias to the original -@code{stderr}. - -@item user_flags -@findex user_flags (yap_flag/2 option) -@* -Define the behaviour of @code{set_prolog_flag/2} if the flag is not known. Values are @code{silent}, @code{warning} and @code{error}. The first two create the flag on-the-fly, with @code{warning} printing a message. The value @code{error} is consistent with ISO: it raises an existence error and does not create the flag. See also @code{create_prolog_flag/3}. The default is@code{error}, and developers are encouraged to use @code{create_prolog_flag/3} to create flags for their library. - -@item user_input -@findex user_input (yap_flag/2 option) -@* -If the second argument is bound to a stream, set @code{user_input} to -this stream. If the second argument is unbound, unify the argument with -the current @code{user_input} stream. - -By default, the @code{user_input} stream is set to a stream -corresponding to the Unix @code{stdin} stream. - -@item user_output -@findex user_output (yap_flag/2 option) -@* -If the second argument is bound to a stream, set @code{user_output} to -this stream. If the second argument is unbound, unify the argument with -the current @code{user_output} stream. - -By default, the @code{user_output} stream is set to a stream -corresponding to the Unix @code{stdout} stream. - -@item verbose -@findex verbose (yap_flag/2 option) -@* -If @code{normal} allow printing of informational and banner messages, -such as the ones that are printed when consulting. If @code{silent} -disable printing these messages. It is @code{normal} by default except if -YAP is booted with the @code{-q} or @code{-L} flag. - -@item verbose_load -@findex verbose_load (yap_flag/2 option) -@* If @code{true} allow printing of informational messages when -consulting files. If @code{false} disable printing these messages. It -is @code{normal} by default except if YAP is booted with the @code{-L} -flag. - -@item verbose_load -@findex verbose_load (yap_flag/2 option) -@* If @code{true} allow printing of informational messages when -consulting files. If @code{false} disable printing these messages. It -is @code{normal} by default except if YAP is booted with the @code{-L} -flag. - -@item version -@findex version (yap_flag/2 option) -@* Read-only flag that returns an atom with the current version of -YAP. - -@item version_data -@findex version_data (yap_flag/2 option) -@* Read-only flag that reads a term of the form -@code{yap}(@var{Major},@var{Minor},@var{Patch},@var{Undefined}), where -@var{Major} is the major version, @var{Minor} is the minor version, -and @var{Patch} is the patch number. - -@item windows -@findex windoes (yap_flag/2 option) -@* -Read-only boolean flag that unifies with tr @code{true} if YAP is -running on an Windows machine. - -@item write_strings -@findex write_strings (yap_flag/2 option) -@* Writable flag telling whether the system should write lists of -integers that are writable character codes using the list notation. It -is @code{on} if enables or @code{off} if disabled. The default value for -this flag is @code{off}. - -@item max_workers -@findex max_workers (yap_flag/2 option) -@* Read-only flag telling the maximum number of parallel processes. - -@item max_threads -@findex max_threads (yap_flag/2 option) -@* Read-only flag telling the maximum number of Prolog threads that can -be created. - -@end table - -@item current_prolog_flag(?@var{Flag},-@var{Value}) [ISO] -@findex current_prolog_flag/2 -@snindex current_prolog_flag/2 -@cnindex current_prolog_flag/2 - -Obtain the value for a YAP Prolog flag. Equivalent to calling -@code{yap_flag/2} with the second argument unbound, and unifying the -returned second argument with @var{Value}. - -@item prolog_flag(?@var{Flag},-@var{OldValue},+@var{NewValue}) -@findex prolog_flag/3 -@syindex prolog_flag/3 -@cnindex prolog_flag/3 - -Obtain the value for a YAP Prolog flag and then set it to a new -value. Equivalent to first calling @code{current_prolog_flag/2} with the -second argument @var{OldValue} unbound and then calling -@code{set_prolog_flag/2} with the third argument @var{NewValue}. - -@item set_prolog_flag(+@var{Flag},+@var{Value}) [ISO] -@findex set_prolog_flag/2 -@snindex set_prolog_flag/2 -@cnindex set_prolog_flag/2 - -Set the value for YAP Prolog flag @code{Flag}. Equivalent to -calling @code{yap_flag/2} with both arguments bound. - - -@item create_prolog_flag(+@var{Flag},+@var{Value},+@var{Options}) -@findex create_prolog_flag/2 -@snindex create_prolog_flag/2 -@cnindex create_prolog_flag/2 - -Create a new YAP Prolog flag. @var{Options} include @code{type(+Type)} and @code{access(+Access)} with @var{Access} -one of @code{read_only} or @code{read_write} and @var{Type} one of @code{boolean}, @code{integer}, @code{float}, @code{atom} -and @code{term} (that is, no type). - -@item op(+@var{P},+@var{T},+@var{A}) [ISO] -@findex op/3 -@syindex op/3 -@cyindex op/3 -Defines the operator @var{A} or the list of operators @var{A} with type -@var{T} (which must be one of @code{xfx}, @code{xfy},@code{yfx}, -@code{xf}, @code{yf}, @code{fx} or @code{fy}) and precedence @var{P} -(see appendix iv for a list of predefined operators). - -Note that if there is a preexisting operator with the same name and -type, this operator will be discarded. Also, @code{','} may not be defined -as an operator, and it is not allowed to have the same for an infix and -a postfix operator. - -@item current_op(@var{P},@var{T},@var{F}) [ISO] -@findex current_op/3 -@syindex current_op/3 -@cnindex current_op/3 -Defines the relation: @var{P} is a currently defined operator of type -@var{T} and precedence @var{P}. - -@item prompt(-@var{A},+@var{B}) -@findex prompt/2 -@syindex prompt/2 -@cyindex prompt/2 -Changes YAP input prompt from @var{A} to @var{B}. - -@item initialization -@findex initialization/0 -@syindex initialization/0 -@cnindex initialization/0 -Execute the goals defined by initialization/1. Only the first answer is -considered. - -@item prolog_initialization(@var{G}) -@findex prolog_initialization/1 -@saindex prolog_initialization/1 -@cnindex prolog_initialization/1 -Add a goal to be executed on system initialization. This is compatible -with SICStus Prolog's @code{initialization/1}. - -@item version -@findex version/0 -@saindex version/0 -@cnindex version/0 -Write YAP's boot message. - -@item version(-@var{Message}) -@findex version/1 -@syindex version/1 -@cnindex version/1 -Add a message to be written when yap boots or after aborting. It is not -possible to remove messages. - -@item prolog_load_context(?@var{Key}, ?@var{Value}) -@findex prolog_load_context/2 -@syindex prolog_load_context/2 -@cnindex prolog_load_context/2 -Obtain information on what is going on in the compilation process. The -following keys are available: - -@table @code - -@item directory -@findex directory (prolog_load_context/2 option) -@* -Full name for the directory where YAP is currently consulting the -file. - -@item file -@findex file (prolog_load_context/2 option) -@* -Full name for the file currently being consulted. Notice that included -filed are ignored. - -@item module -@findex module (prolog_load_context/2 option) -@* -Current source module. - -@item source -@findex file (prolog_load_context/2 option) -@* -Full name for the file currently being read in, which may be consulted, -reconsulted, or included. - -@item stream -@findex file (prolog_load_context/2 option) -@* -Stream currently being read in. - -@item term_position -@findex file (prolog_load_context/2 option) -@* -Stream position at the stream currently being read in. For SWI -compatibility, it is a term of the form -@code{'$stream_position'(0,Line,0,0,0)}. -@end table - -@item source_location(?@var{FileName}, ?@var{Line}) -@findex source_location/2 -@syindex source_location/2 -@cnindex source_location/2 -SWI-compatible predicate. If the last term has been read from a physical file (i.e., not from the file user or a string), unify File with an absolute path to the file and Line with the line-number in the file. Please use @code{prolog_load_context/2}. - -@item source_file(?@var{File}) -@findex source_file/1 -@syindex source_file/1 -@cnindex source_file/1 -SWI-compatible predicate. True if @var{File} is a loaded Prolog source file. - -@item source_file(?@var{ModuleAndPred},?@var{File}) -@findex source_file/2 -@syindex source_file/2 -@cnindex source_file/2 -SWI-compatible predicate. True if the predicate specified by @var{ModuleAndPred} was loaded from file @var{File}, where @var{File} is an absolute path name (see @code{absolute_file_name/2}). - - - -@end table +@include builtins.tex @node Library, SWI-Prolog, Built-ins, Top @@ -10485,7 +2222,7 @@ matrices are multi-dimensional and compact. In contrast to static arrays. these arrays are allocated in the stack. Matrices are available by loading the library @code{library(matrix)}. They are multimensional objects of type: -@itemize +@itemize @item @t{terms}: Prolog terms @item @t{ints}: bounded integers, represented as an opaque term. The maximum integer depends on hardware, but should be obtained from the @@ -10560,7 +2297,7 @@ matrices of integers and of floating-point numbers should have the same General matrix assignment operation. It evaluates the right-hand side and then acts different according to the left-hand side and to the matrix: -@itemize +@itemize @bullet @item if @var{LHS} is part of an integer or floating-point matrix, perform non-backtrackable assignment. @item other unify left-hand side and right-hand size. @@ -12124,8 +3861,7 @@ The file mylib.pl can be loaded as a normal Prolog file and provides the predica @code{use_foreign_library/1,2} are intended for use in directives. -@item [det]use_foreign_library(+@var{FileSpec}) -@item [det]use_foreign_library(+@var{FileSpec}, +@var{Entry}:atom) +@item [det] use_foreign_library(+@var{FileSpec}), use_foreign_library(+@var{FileSpec}, +@var{Entry}:atom) @findex use_foreign_library/1 @snindex use_foreign_library/1 @cnindex use_foreign_library/1 @@ -14124,6 +5860,7 @@ negation @end table @item bdd_from_list(?@var{List}, -@var{BddHandle}) +@findex bdd_from_list/2 Convert a @var{List} of logical expressions of the form above into a BDD accessible through @var{BddHandle}. @@ -15234,8 +6971,6 @@ efficient SQL translation. @snindex db_close/1 @cnindex db_close/1 -@item db_close. - @end table Assuming the MySQL server is running and we have an account, we can @@ -16861,6 +8596,7 @@ The possible forms for @var{P} are the same as in @code{spy P}. Removes all existing spy-points. @item notrace +@findex notrace/0 Switches off the debugger and stops tracing. @item leash(+@var{M})