This is info/sicstus.info, produced by makeinfo version 4.13 from sicstus.texi. INFO-DIR-SECTION SICStus Prolog START-INFO-DIR-ENTRY * SICStus Prolog Manual: (sicstus). SICStus Prolog User's Manual. END-INFO-DIR-ENTRY Generated 1 February 2012.  File: sicstus.info, Node: Top, Next: Intro, Prev: (dir), Up: (dir) SICStus Prolog ************** This manual documents SICStus Prolog 4.2.1, February 2012. Prolog is a simple but powerful programming language developed at the University of Marseille, as a practical tool for programming in logic. From a user's point of view the major attraction of the language is ease of programming. Clear, readable, concise programs can be written quickly with few errors. * Menu: * Intro:: An Introduction to This Manual * Acknowledgments:: Acknowledgments * Notation:: Notational Conventions * Glossary:: Glossary of Concepts Used * Run Intro:: How to Run Prolog * Prolog Intro:: The Prolog Language * Debug Intro:: Debugging * Mixing C and Prolog:: C-interface * Interfacing .NET and Java:: Using the interfaces for .NET and Java * Multiple SICStus Runtimes:: Multiple SICStus Runtimes in a Process * Writing Efficient Programs:: Writing Efficient Programs * The Prolog Library:: The Prolog Library * Prolog Reference Pages:: Prolog Reference Pages * C Reference Pages:: C Reference Pages * Command Reference Pages:: Command Reference Pages * References:: References * Predicate Index:: An item for each predicate, function, etc * Keystroke Index:: An item for each keystroke * Book Index:: An item for each concept, predicate, method, other  File: sicstus.info, Node: Intro, Next: Acknowledgments, Prev: Top, Up: Top Introduction ************ Prolog is a simple but powerful programming language developed at the University of Marseille [Roussel 75], as a practical tool for programming in logic [Kowalski 74]. From a user's point of view the major attraction of the language is ease of programming. Clear, readable, concise programs can be written quickly with few errors. For an introduction to programming in Prolog, readers are recommended to consult [Sterling & Shapiro 86]. However, for the benefit of those who do not have access to a copy of this book, and for those who have some prior knowledge of logic programming, we include a summary of the language. For a more general introduction to the field of Logic Programming see [Kowalski 79]. *Note Prolog Intro::. This manual describes a Prolog system developed at the Swedish Institute of Computer Science. Parts of the system were developed by the project "Industrialization of SICStus Prolog" in collaboration with Ericsson Telecom AB, NobelTech Systems AB, Infologics AB and Televerket. The system consists of a _WAM_ emulator written in C, a library and runtime system written in C and Prolog and an interpreter and a compiler written in Prolog. The Prolog engine is a Warren Abstract Machine (WAM) emulator [Warren 83]. Two modes of compilation are available: in-core i.e. incremental, and file-to-file. When compiled, a predicate will run about 8 times faster and use memory more economically. Implementation details can be found in [Carlsson 90] and in several technical reports available from SICS. SICStus Prolog follows the mainstream Prolog tradition in terms of syntax and built-in predicates. As of release 4, SICStus Prolog is fully compliant with the International Standard ISO/IEC 13211-1 (PROLOG: Part 1--General Core) (`http://webstore.ansi.org/ansidocstore/product.asp?sku=INCITS%2FISO%2FIEC+13211%2D1%2D1995').  File: sicstus.info, Node: Acknowledgments, Next: Notation, Prev: Intro, Up: Top Acknowledgments *************** The following people have contributed to the development of SICStus Prolog: Jonas Almgren, Johan Andersson, Stefan Andersson, Nicolas Beldiceanu, Tama's Benko'', Kent Boortz, Dave Bowen, Per Brand, Go"ran Baage, Vicki Carleson, Mats Carlsson, Per Danielsson, Joakim Eriksson, Jesper Eskilson, Niklas Finne, Lena Flood, Gyo"rgy Gyaraki, Da'vid Hana'k, Seif Haridi, Ralph Haygood, Christian Holzbaur, Tom Howland, Key Hyckenberg, Pe'ter La'szlo', Per Mildner, Richard O'Keefe, Greger Ottosson, Dan Sahlin, Peter Schachte, Rob Scott, Thomas Sjo"land, Pe'ter Szeredi, Tama's Szeredi, Peter Van Roy, David Warren, Johan Wide'n, Magnus AAgren, and Emil AAstro"m. The Industrialization of SICStus Prolog (1988-1991) was funded by Ericsson Telecom AB, NobelTech Systems AB, Infologics AB, and Televerket, under the National Swedish Information Technology Program IT4. The development of release 3 (1991-1995) was funded in part by Ellemtel Utvecklings AB This manual is based on DECsystem-10 Prolog User's Manual by D.L. Bowen, L. Byrd, F.C.N. Pereira, L.M. Pereira, D.H.D. Warren *Note lib-chr:: for acknowledgments relevant to the CHR constraint solver. *Note lib-clpqr:: for acknowledgments relevant to the clp(Q,R) constraint solver. UNIX is a trademark of Bell Laboratories. MSDOS and Windows are trademarks of Microsoft Corp. OS/2 is a trademark of IBM Corp.  File: sicstus.info, Node: Notation, Next: Glossary, Prev: Acknowledgments, Up: Top 1 Notational Conventions ************************ * Menu: * Keyboard Characters:: Keyboard Characters * Mode Spec:: Mode Spec * Development and Runtime Systems:: Development and Runtime Systems * Function Prototypes:: Function Prototypes * ISO Compliance:: ISO Compliance  File: sicstus.info, Node: Keyboard Characters, Next: Mode Spec, Up: Notation 1.1 Keyboard Characters ======================= When referring to keyboard characters, printing characters are written thus: `a', while control characters are written like this: `^A'. Thus `^C' is the character you get by holding down the key while you type `c'. Finally, the special control characters carriage-return, line-feed and space are often abbreviated to , and respectively. Throughout, we will assume that `^D' is the EOF character (it's usually `^Z' under Windows) and that `^C' is the interrupt character. In most contexts, the term `end_of_file' terminated by a full stop (`.') can be typed instead of the EOF character.  File: sicstus.info, Node: Mode Spec, Next: Development and Runtime Systems, Prev: Keyboard Characters, Up: Notation 1.2 Mode Spec ============= When describing a predicate, we present its usage with a "mode spec", which has the form NAME(ARG, ..., ARG), where each ARG denotes how that argument is used by the predicate, and has one of the following forms: :ARGNAME The argument is used as a term denoting a goal or a clause or a predicate name, or that otherwise needs special handling of module prefixes. It is is subject to "module name expansion" (*note ref-mod-mne::). +ARGNAME The argument is an input argument. Usually, but not always, this implies that the argument should be instantiated. -ARGNAME The argument is an output argument. Usually, but not always, this implies that the argument should be uninstantiated. ?ARGNAME The argument may be used for both input and output. *Please note:* The reference pages for built-in predicate use slightly different mode specs.  File: sicstus.info, Node: Development and Runtime Systems, Next: Function Prototypes, Prev: Mode Spec, Up: Notation 1.3 Development and Runtime Systems =================================== The full Prolog system with top-level, compiler, debugger etc. is known as the "development system". It is possible to link user-written C code with a subset of SICStus Prolog to create "runtime systems". When introducing a built-in predicate, any limitations on its use in runtime systems will be mentioned.  File: sicstus.info, Node: Function Prototypes, Next: ISO Compliance, Prev: Development and Runtime Systems, Up: Notation 1.4 Function Prototypes ======================= Whenever this manual documents a C function as part of SICStus Prolog's foreign language interface, the function prototype will be displayed in ANSI C syntax.  File: sicstus.info, Node: ISO Compliance, Prev: Function Prototypes, Up: Notation 1.5 ISO Compliance ================== SICStus Prolog is fully compliant with the International Standard ISO/IEC 13211-1 (PROLOG: Part 1--General Core) (`http://webstore.ansi.org/ansidocstore/product.asp?sku=INCITS%2FISO%2FIEC+13211%2D1%2D1995'). To aid programmers who wish to write standard compliant programs, built-in predicates and arithmetic functors that are part of the ISO Prolog Standard are annotated with _[ISO]_ in this manual.  File: sicstus.info, Node: Glossary, Next: Run Intro, Prev: Notation, Up: Top 2 Glossary ********** "abolish" To abolish a predicate is to retract all the predicate's clauses and to remove all information about it from the Prolog system, to make it as if that predicate had never existed. "advice-point" A special case of breakpoint, the advice breakpoint. It is distinguished from spypoints in that it is intended for non-interactive debugging, such as checking of program invariants, collecting information, profiling, etc. "alphanumeric" An alphanumeric character is any of the lowercase characters from `a' to `z', the uppercase characters from `A' to `Z', the numerals from `0' to `9', or underscore (`_'). "ancestors" An ancestor of a goal is any goal that the system is trying to solve when it calls that goal. The most distant ancestor is the goal that was typed at the top-level prompt. "anonymous variable" An anonymous variable is one that has no unique name, and whose value is therefore inaccessible. An anonymous variable is denoted by an underscore (`_'). "argument" See predicate, structure, and arity. "arity" The arity of a structure is its number of arguments. For example, the structure `customer(jones,85)' has an arity of 2. "atom" A character sequence used to uniquely denote some entity in the problem domain. A number is _not_ an atom. Examples of legal atoms are: hello * := '#$%' 'New York' 'don\'t' *Note ref-syn-trm-ato::. Atoms are recognized by the built-in predicate `atom/1'. Each Prolog atom is represented internally by a unique integer, represented in C as an `SP_atom'. "atomic term" Synonym for constant. "backtrace" A collection of information on the control flow of the program, gathered by the debugger. Also the display of this information produced by the debugger. The backtrace includes data on goals that were called but not exited and also on goals that exited nondeterminately. "backtracking" The process of reviewing the goals that have been satisfied and attempting to resatisfy these goals by finding alternative solutions. "binding" The process of assigning a value to a variable; used in unification. "blocked goal" A goal that is suspended because it is not instantiated enough. "body" The body of a clause consists of the part of a Prolog clause following the `:-' symbol. "breakpoint" A description of certain invocations in the program where the user wants the debugger to stop, or to perform some other actions. A breakpoint is specific if it applies to the calls of a specific predicate, possibly under some conditions; otherwise, it is generic. Depending on the intended usage, breakpoints can be classified as debugger breakpoints, also known as spypoints, or advice breakpoints, also called advice-points; *note Advanced Debugging::. "breakpoint spec" A term describing a breakpoint. Composed of a test part, specifying the conditions under which the breakpoint should be applied, and an action part, specifying the effects of the breakpoint on the execution. "byte-list" A byte-list is a list of bytes, i.e. integers in [0,...,255]. "buffer" A temporary workspace in Emacs that contains a file being edited. "built-in predicate" A predicate that comes with the system and that does not have to be explicitly loaded before it is used. "callable term" A callable term is either a compound term or an atom. Callable terms are recognized by the built-in predicate `callable/1'. "character code" An integer that is the numeric representation of a character in the character code set. "character code set" A subset of the set {0, ..., 2^31-1} that can be handled in input/output. SICStus Prolog fixes the character code set to a superset of Unicode, which includes the ASCII code set, i.e. codes 0..127, and these codes are interpreted as ASCII characters "character-conversion mapping" SICStus Prolog maintains a character-conversion mapping, which is used while reading terms and programs. Initially, the mapping prescribes no character conversions. It can be modified by the built-in predicate `char_conversion(IN, OUT)', following which IN will be converted to OUT. Character coversion can be switched off by the `char_conversion' Prolog flag. "character-type mapping" A function mapping each element of the character code set to one of the character categories (whitespace, letter, symbol-char, etc.), required for parsing tokens. "choicepoints" A memory block representing outstanding choices for some goals or disjunctions. "clause" A fact or a rule. A rule comprises a "head" and a body. A fact consists of a head only, and is equivalent to a rule with the body `true'. "code-list" A code-list is a list of character codes. "conditional compilation" Conditinally including or excluding parts of a file at compile time. "compactcode" Virtual code representation of compiled code. A reasonable compromise between performance and space requirement. A valid value for the `compiling' Prolog flag. "compile" To load a program (or a portion thereof) into Prolog through the compiler. Compiled code runs more quickly than interpreted code, and provides better precision for execution profiling and coverage analysis. On the other hand, you cannot debug compiled code in as much detail as interpreted code. "compound term" A compound term is a term that is an atom together with one or more arguments. For example, in the term `father(X)', `father' is the name, and `X' is the first and only argument. The argument to a compound term can be another compound term, as in `father(father(X))'. Compound terms are recognized by the built-in predicate `compound/1'. "conjunction" A series of goals connected by the connective "and" (that is, a series of goals whose principal operator is `,'). "console-based executable" An executable that inherits the standard streams from the process that invoked it, e.g. a UNIX shell or a DOS-prompt. "constant" An integer (for example: 1, 20, -10), a floating-point number (for example: 12.35), or an atom. Constants are recognized by the built-in predicate `atomic/1'. "consult" To load a program (or a portion thereof) into Prolog through the interpreter. Interpreted code runs more slowly than compiled code, and does not provide as good precision for execution profiling and coverage analysis. On the other hand, you can debug interpreted code in more detail than compiled code. "control structure" A built-in predicate that is "part of the language" in the sense that it is treated specially in certain language features. The set of such control structures and language features is enuemrated in *note ref-sem-ctr::. "creep" What the debugger does in trace mode, also known as single-stepping. It goes to the next port of a procedure box and prints the goal, then prompts you for input. *Note Basic Debug::. "cursor" The point on the screen at which typed characters appear. This is usually highlighted by a line or rectangle the size of one space, which may or may not blink. "cut" Written as `!'. A built-in predicate that succeeds when encountered; if backtracking should later return to the cut, the goal that matched the head of the clause containing the cut fails immediately. "database" The Prolog database comprises all of the clauses that have been loaded or asserted into the Prolog system or that have been asserted, except those clauses that have been retracted or abolished. "db_reference" A compound term denoting a unique reference to a dynamic clause. Recognized by the built-in predicate `db_reference/1'. "debug" A mode of program execution in which the debugger stops to print the current goal only at predicates that have spypoints set on them (see leap). "debugcode" Interpreted representation of compiled code. A valid value for the `compiling' Prolog flag. "declaration" A declaration looks like a directive, but is not executed but rather conveys information about predicates about to be loaded. "deinit function" A function in a foreign resource that is called prior to unloading the resource. "determinate" A predicate is determinate if it can supply only one answer. "development system" A stand-alone executable with the full programming environment, including top-level, compiler, debugger etc. The default `sicstus' executable is a development system; new development systems containing pre-linked foreign resources can also be created. "directive" A directive is a goal preceded by the prefix operator `:-', whose intuitive meaning is "execute this as a query, but do not print out any variable bindings." "disjunction" A series of goals connected by the connective "or" (that is, a series of goals whose principal operator is `;'). "do-loop" A control structure of the form `(ITERATORS do BODY)'. It expresses a simple iteration. *Note ref-sem-ctr-dol::. "dynamic predicate" A predicate that can be modified while a program is running. The semantics of such updates is described in *note ref-mdb-bas::. A predicate must explicitly be declared to be dynamic or it must be added to the database via one of the assertion predicates. "encoded string" A sequence of bytes representing a sequence of possibly wide character codes, using the UTF-8 encoding. "escape sequence" A sequence of characters beginning with `\' inside certain syntactic tokens (*note ref-syn-syn-esc::). "export" A module exports a predicate so that other modules can import it. "extended runtime system" A stand-alone executable. In addition to the normal set of built-in runtime system predicates, extended runtime systems include the compiler. Extended runtime systems require the extended runtime library, available from SICS as an add-on product. "fact" A clause with no conditions--that is, with an empty body. A fact is a statement that a relationship exists between its arguments. Some examples, with possible interpretations, are: king(louis, france). % Louis was king of France. have_beaks(birds). % Birds have beaks. employee(nancy, data_processing, 55000). % Nancy is an employee in the % data processing department. "file specification" An atom or a compound term denoting the name of a file. The rules for mapping such terms to absolute file names are described in *note ref-fdi::. "floundered query" A query where all unsolved goals are blocked. "foreign predicate" A predicate that is defined in a language other than Prolog, and explicitly bound to Prolog predicates by the Foreign Language Interface. "foreign resource" A named set of foreign predicates. "functor" The functor of a compound term is its name and arity. For example, the compound term `foo(a,b)' is said to have "the functor `foo' of arity two", which is generally written `foo/2'. The functor of a constant is the term itself paired with zero. For example, the constant `nl' is said to have "the functor `nl' of arity zero", which is generally written `nl/0'. "garbage collection" The freeing up of space for computation by making the space occupied by terms that are no longer available for use by the Prolog system. "generalized predicate spec" A generalized predicate spec corresponds to the argument type "pred_spec_tree" (*note mpg-ref-aty-ety::) and is a term of one of the following forms. It is always interpreted wrt. a given module context: NAME all predicates called NAME no matter what arity, where NAME is an atom for a specific name or a variable for all names, or NAME/ARITY the predicate of that name and arity, or MODULE:SPEC specifying a particular module MODULE instead of the default module, where MODULE is an atom for a specific module or a variable for all modules, or [Spec,...,Spec] the set of all predicates covered by the SPECS. "glue code" Interface code between the Prolog engine and foreign predicates. Automatically generated by the foreign language interface as part of building a linked foreign resource. "goal" A simple goal is a predicate call. When called, it will either succeed or fail. A compound goal is a formula consisting of simple goals connected by connectives such as "and" (`,') or "or" (`;'). A goal typed at the top-level is called a query. "ground" A term is ground when it is free of (unbound) variables. Ground terms are recognized by the built-in predicate `ground/1'. "guarded clause" A clause of the form HEAD :- GOALS, !, GOALS. "head" The head of a clause is the single goal, which will be satisfied if the conditions in the body (if any) are true; the part of a rule before the `:-' symbol. The head of a list is the first element of the list. "extendible predicate" An extendible predicate is a multifile predicate, to which new clauses can be added by the user. "hook predicate" A hook predicate is a predicate that somehow alters or customizes the behavior of a hookable predicate. "hookable predicate" A hookable predicate is a built-in predicate whose behavior is somehow altered or customized by a hook predicate. "interactive stream" A stream with the `interactive' stream property. Certain behavior of interactive streams are optimized for the case where a human is at the other end of the stream. "import" Exported predicates in a module can be imported by other modules. Once a predicate has been imported by a module, it can be called, or exported, as if it were defined in that module. There are two kinds of importation: predicate-importation, in which only specified predicates are imported from a module; and module-importation, in which all the predicates exported by a module are imported. "indexing" The process of filtering a set of potentially matching clauses of a predicate given a goal. For interpreted and compiled code, indexing is done on the principal functor of the first argument. Indexing is coarse wrt. large integers and floats. "init function" A function in a foreign resource that is called upon loading the resource. "initialization" An initialization is a goal that is executed when the file in which the initialization is declared is loaded. An initialization is declared as a directive `:- initialization GOAL'. "instantiation" A variable is instantiated if it is bound to a non-variable term; that is, to an atomic term or a compound term. "interpret" Load a program or set of clauses into Prolog through the interpreter (also known as consulting). Interpreted code runs more slowly than compiled code, does not provide as good precision for execution profiling and coverage analysis. On the other hand, more extensive facilities are available for debugging interpreted code. "invocation box" Same as procedure box. "iterator" A compound term expressing how a do-loop should be iterated. *Note ref-sem-ctr-dol::. "large integer" An integer that is not a small integer. "layout term" In the context of handling line number information for source code, a source term SOURCE gets associated to a layout term LAYOUT, which is one of the following: * `[]', if no line number information is available for SOURCE. * If SOURCE is a simple term, LAYOUT is the number of the line where SOURCE occurs. * If SOURCE is a compound term, LAYOUT is a list whose head is the number of the line where the first token of SOURCE occurs, and whose remaining elements are the layouts of the arguments of SOURCE. "leap" What the debugger does in debug mode. The debugger shows only the ports of predicates that have spypoints on them. It then normally prompts you for input, at which time you may leap again to the next spypoint (see trace). "leashing" Determines how frequently the debugger will stop and prompt you for input when you are tracing. A port at which the debugger stops is called a "leashed port". "linked foreign resource" A foreign resource that is ready to be installed in an atomic operation, normally represented as a shared object or DLL. "list" A list is written as a set of zero or more terms between square brackets. If there are no terms in a list, it is said to be empty, and is written as `[]'. In this first set of examples, all members of each list are explicitly stated: [aa, bb,cc] [X, Y] [Name] [[x, y], z] In the second set of examples, only the first several members of each list are explicitly stated, while the rest of the list is represented by a variable on the right-hand side of the "rest of" operator, `|': [X | Y] [a, b, c | Y] [[x, y] | Rest] `|' is also known as the "list constructor." The first element of the list to the left of `|' is called the head of the list. The rest of the list, including the variable following `|' (which represents a list of any length), is called the "tail" of the list. "load" To load a Prolog clause or set of clauses, in source or binary form, from a file or set of files. "meta-call" The process of interpreting a callable term as a goal. This is done e.g. by the built-in predicate `call/1'. "meta-logical predicate" A predicate that performs operations that require reasoning about the current instantiation of terms or decomposing terms into their constituents. Such operations cannot be expressed using predicate definitions with a finite number of clauses. "meta-predicate" A meta-predicate is one that calls one or more of its arguments; more generally, any predicate that needs to assume some module in order to operate is called a meta-predicate. Some arguments of a meta-predicate are subject to module name expansion. "module" A module is a set of predicates in a module-file. The name of a module is an atom. Some predicates in a module are exported. The default module is `user'. "module name expansion" The process by which certain arguments of meta-predicates get prefixed by the source module. *Note ref-mod-mne::. "module-file" A module-file is a file that is headed with a module declaration of the form: :- module(MODULENAME, EXPORTEDPREDLIST). which must appear as the first term in the file. "multifile predicate" A predicate whose definition is to be spread over more than one file. Such a predicate must be preceded by an explicit multifile declaration in all files containing clauses for it. "mutable term" A special form of compound term subject to destructive assignment. *Note ref-lte-mut::. Mutable terms are recognized by the built-in predicate `mutable/1'. "name clash" A name clash occurs when a module attempts to define or import a predicate that it has already defined or imported. "occurs-check" A test to ensure that binding a variable does not bind it to a term where that variable occurs. "one-char atom" An atom that consists of a single character. "operator" A notational convenience that allows you to express any compound term in a different format. For example, if `likes' in | ?- likes(sue, cider). is declared an infix operator, the query above could be written: | ?- sue likes cider. An operator does not have to be associated with a predicate. However, certain built-in predicates are declared as operators. For example, | ?- =..(X, Y). can be written as | ?- X =.. Y. because `=..' has been declared an infix operator. Those predicates that correspond to built-in operators are written using infix notation in the list of built-in predicates at the beginning of the part that contains the reference pages. Some built-in operators do _not_ correspond to built-in predicates; for example, arithmetic operators. See *note ref-syn-ops-bop:: for a list of built-in operators. "pair" A compound term `K-V'. Pairs are used by the built-in predicate `keysort/2' and by many library modules. "parent" The parent of the current goal is a goal that, in its attempt to obtain a successful solution to itself, is calling the current goal. "port" One of the seven key points of interest in the execution of a Prolog predicate. See *note Procedure Box:: for a definition. "pre-linked foreign resource" A linked foreign resource that is linked into a stand-alone executable as part of building the executable. "precedence" A number associated with each Prolog operator, which is used to disambiguate the structure of the term represented by an expression containing a number of operators. Operators of lower precedence are applied before those of higher precedence; the operator with the highest precedence is considered the principal functor of the expression. To disambiguate operators of the same precedence, the associativity type is also necessary. *Note ref-syn-ops::. "predicate" A functor that specifies some relationship existing in the problem domain. For example, `< /2' is a built-in predicate specifying the relationship of one number being less than another. In contrast, the functor `+ /2' is not (normally used as) a predicate. A predicate is either built-in or is implemented by a procedure. "predicate spec" A compound term `NAME/ARITY' or `MODULE:NAME/ARITY' denoting a predicate. "procedure" A set of clauses in which the head of each clause has the same predicate. For instance, a group of clauses of the following form: connects(san_francisco, oakland, bart_train). connects(san_francisco, fremont, bart_train). connects(concord, daly_city, bart_train). is identified as belonging to the predicate `connects/3'. "procedure box" A way of visualizing the execution of a Prolog procedure, A procedure box is entered and exited via ports. "profiling" The process of gathering execution statistics of the program, essentially counting the number of times selected program points have been reached. "program" A set of procedures designed to perform a given task. "PO file" A PO (Prolog object) file contains a binary representation of a set of modules, predicates, clauses and directives. They are portable between different platforms, except between 32-bit and 64-bit platforms. They are created by `save_files/2', `save_modules/2', and `save_predicates/2'. "query" A query is a question put by the user to the Prolog system. A query is written as a goal followed by a full-stop in response to the top-level prompt. For example, | ?- father(edward, ralph). refers to the predicate `father/2'. If a query has no variables in it, the system will respond either `yes' or `no'. If a query contains variables, the system will try to find values of those variables for which the query is true. For example, | ?- father(edward, X). X = ralph After the system has found one answer, the user can direct the system to look for additional answers to the query by typing `;'. "recursion" The process in which a running predicate calls itself, presumably with different arguments and for the purpose of solving some subset of the original problem. "region" The text between the cursor and a previously set mark in an Emacs buffer. "rule" A clause with one or more conditions. For a rule to be true, all of its conditions must also be true. For example, has_stiff_neck(ralph) :- hacker(ralph). This rule states that if the individual `ralph' is a hacker, he must also have a stiff neck. The constant `ralph' is replaced in has_stiff_neck(X) :- hacker(X). by the variable `X'. `X' unifies with anything, so this rule can be used to prove that any hacker has a stiff neck. "runtime kernel" A shared object or DLL containing the SICStus virtual machine and other runtime support for stand-alone executables. "runtime system" A stand-alone executable with a restricted set of built-in predicates and no top-level. Stand-alone applications containing debugged Prolog code and destined for end-users are typically packaged as runtime systems. "saved-state" A snapshot of the state of Prolog saved in a file by `save_program/[1,2]'. "semantics" The relation between the set of Prolog symbols and their combinations (as Prolog terms and clauses), and their meanings. Compare syntax. "sentence" A clause or directive. "side-effect" A predicate that produces a side-effect is one that has any effect on the "outside world" (the user's terminal, a file, etc.), or that changes the Prolog database. "simple term" A simple term is a constant or a variable. Simple terms are recognized by the built-in predicate `simple/1'. "skeletal goal" A compound term `NAME(ARG, ..., ARG)' or `MODULE:NAME(ARG, ..., ARG)' denoting a predicate. "small integer" An integer in the range `[-2^28,2^28-1]' on 32-bit platforms, or `[-2^60,2^60-1]' on 64-bit platforms. The start and end of this range is available as the value of the Prolog flags `min_tagged_integer' and `max_tagged_integer', respectively. "source code" The human-readable, as opposed to the machine-executable, representation of a program. "source module" The module that is the context of a file being loaded. For module-files, the source module is named in the file's module declaration. For other files, the source module is inherited from the context. "SP_term_ref" A "handle" object providing an interface from C to Prolog terms. "spypoint" A special case of breakpoint, the "debugger breakpoint", intended for interactive debugging. Its simplest form, the "plain spypoint" instructs the debugger to stop at all ports of all invocations of a specified predicate. "Conditional spypoints" apply to a single predicate, but are more selective: the user can supply applicability "tests" and prescribe the "actions" to be carried out by the debugger. A "generic spypoint" is like a conditional spypoint, but not restricted to a single predicate. *Note Advanced Debugging::. "stand-alone executable" A binary program that can be invoked from the operating system, containing the SICStus runtime kernel. A stand-alone executable is a development system (e.g. the default `sicstus' executable), or a runtime system. Both kinds are created by the application builder. A stand-alone executable does not itself contain any Prolog code; all Prolog code must be loaded upon startup. "static predicate" A predicate that can be modified only by being reloaded or by being abolished. See dynamic predicate. "steadfast" A predicate is steadfast if it refuses to give the wrong answer even when the query has an unexpected form, typically with values supplied for arguments intended as output. "stream" An input/output channel. *Note ref-iou::. "stream alias" A name assigned to a stream at the time of opening, which can be referred to in I/O predicates. Must be an atom. There are also three predefined aliases for the standard streams: `user_input', `user_output' and `user_error'. Although not a stream alias proper, the atom `user' also stands for the standard input or output stream, depending on context. "stream object" A term denoting an open Prolog stream. *Note ref-iou::. "stream position" A term representing the current position of a stream. This position is determined by the current byte, character and line counts and line position. Standard term comparison on stream position terms works as expected. When `SP1' and `SP2' refer to positions in the same stream, `SP1@) at the end of the query. If the goal(s) specified in a query can be satisfied, and if there are no variables as in this example, the system answers yes and execution of the query terminates. If variables are included in the query, the final value of each variable is displayed (except for variables whose names begin with `_'). Thus the query | ?- memb(X, [a,b,c]). would be answered by X = a ? At this point, the development system accepts one-letter commands corresponding to certain actions. To execute an action simply type the corresponding character (lower or upper case) followed by . The available commands in development systems are: `' `y' "accepts" the solution; the query is terminated and the development system responds with `yes'. `;' `n' "rejects" the solution; the development system backtracks (*note ref-sem::) looking for alternative solutions. If no further solutions can be found it outputs `no'. `b' invokes a recursive top-level. `<' In the top-level, a global "printdepth" is in effect for limiting the subterm nesting level when printing bindings. The limit is initially 10. This command, without arguments, resets the printdepth to 10. With an argument of N, the printdepth is set to N, treating 0 as infinity. This command works by changing the value of the `toplevel_print_options' Prolog flag. `^' A local "subterm selector", initially `[]', is maintained. The subterm selector provides a way of zooming in to some subterm of each binding. For example, the subterm selector `[2,3]' causes the 3rd subterm of the 2nd subterm of each binding to be selected. This command, without arguments, resets the subterm selector to `[]'. With an argument of 0, the last element of the subterm selector is removed. With an argument of N (> 0), N is added to the end of the subterm selector. With multiple arguments separated by whitespace, the arguments are applied from left to right. `h' `?' lists available commands. While the variable bindings are displayed, all variables occurring in the values are replaced by terms of the form `'$VAR'(N)' to yield friendlier variable names. Such names come out as a sequence of letters and digits preceded by `_'. The outcome of some queries is shown below. | ?- memb(X, [tom,dick,harry]). X = tom ; X = dick ; X = harry ; no | ?- memb(X, [a,b,f(Y,c)]), memb(X, [f(b,Z),d]). X = f(b,c), Y = b, Z = c | ?- memb(X, [f(_),g]). X = f(_A) Directives are like queries except that: 1. Variable bindings are not displayed if and when the directive succeeds. 2. You are not given the chance to backtrack through other solutions.  File: sicstus.info, Node: Directives, Prev: Queries, Up: Queries and Directives 3.4.2 Directives ---------------- Directives start with the symbol `:-'. Any required output must be programmed explicitly; e.g. the directive: :- memb(3, [1,2,3]), write(ok). asks the system to check whether `3' belongs to the list `[1,2,3]'. Execution of a directive terminates when all the goals in the directive have been successfully executed. Other alternative solutions are not sought. If no solution can be found, the system prints: * GOAL - goal failed as a warning. The principal use for directives (as opposed to queries) is to allow files to contain directives that call various predicates, but for which you do not want to have the answers printed out. In such cases you only want to call the predicates for their effect, i.e. you don't want terminal interaction in the middle of consulting the file. A useful example would be the use of a directive in a file that consults a whole list of other files, e.g.: :- consult([ bits, bobs, main, tests, data, junk ]). If a directive like this were contained in the file `myprog', typing the following at top-level would be a quick way of reading in your entire program: | ?- [myprog]. When simply interacting with the top-level, this distinction between queries and directives is not normally very important. At top-level you should just type queries normally. In a file, queries are in fact treated as directives, i.e. if you wish to execute some goals, the directive in the file must be preceded by `:-' or `?-'; otherwise, it would be treated as a clause.  File: sicstus.info, Node: Syntax Errors, Next: Undefined Predicates, Prev: Queries and Directives, Up: Run Intro 3.5 Syntax Errors ================= Syntax errors are detected during reading. Each clause, directive or, in general, any term read in by the built-in predicate `read/1' that fails to comply with syntax requirements is displayed on the standard error stream as soon as it is read, along with its position in the input stream and a mark indicating the point in the string of symbols where the parser has failed to continue analysis, e.g.: | memb(X, X$L). ! Syntax error ! , or ) expected in arguments ! in line 5 ! memb ( X , X ! <> ! $ L ) . if `$' has not been declared as an infix operator. Note that any comments in the faulty line are not displayed with the error message. If you are in doubt about which clause was wrong you can use the `listing/1' predicate to list all the clauses that were successfully read in, e.g.: | ?- listing(memb/2). *Please note*: The built-in predicates `read/[1,2]' normally raise an exception on syntax errors (*note ref-ere::). The behavior is controlled by the Prolog flag `syntax_errors'.  File: sicstus.info, Node: Undefined Predicates, Next: Execution, Prev: Syntax Errors, Up: Run Intro 3.6 Undefined Predicates ======================== There is a difference between predicates that have no definition and predicates that have no clauses. The latter case is meaningful e.g. for dynamic predicates (*note ref-lod-dcl::) that clauses are being added to or removed from. There are good reasons for treating calls to undefined predicates as errors, as such calls easily arise from typing errors. The system can optionally catch calls to predicates that have no definition. First, the user defined predicate `user:unknown_predicate_handler/3' (*note ref-ere::) is called. If undefined or if the call fails, the action is governed by the state of the `unknown' Prolog flag; *note ref-lps-flg::. Calls to predicates that have no clauses are not caught. Two development system predicates are handy in this context: | ?- unknown(X,error). % Undefined predicates will raise an exception (error) X = error This sets the flag and prints a message about the new value. | ?- debugging. The debugger is switched off Using leashing stopping at [call,exit,redo,fail,exception] ports Undefined predicates will raise an exception (error) There are no breakpoints This prints a message about the current value, as well as information about the state of the debugger.  File: sicstus.info, Node: Execution, Next: Exiting, Prev: Undefined Predicates, Up: Run Intro 3.7 Program Execution And Interruption ====================================== Execution of a program is started by giving the system a query that contains a call to one of the program's predicates. Only when execution of one query is complete does the system become ready for another query. However, one may interrupt the normal execution of a query by typing `^C'. This `^C' interruption has the effect of suspending the execution, and the following message is displayed: Prolog interruption (h or ? for help) ? At this point, the development system accepts one-letter commands corresponding to certain actions. To execute an action simply type the corresponding character (lower or upper case) followed by . The available commands in development systems are: `a' aborts the current computation. `c' continues the execution. `e' exits from SICStus Prolog, closing all files. `h' `?' lists available commands. `b' invokes a recursive top-level. `d' `z' `t' switch on the debugger. *Note Debug Intro::. If the standard input stream is not connected to the terminal, e.g. by redirecting standard input to a file or a pipe, the above `^C' interrupt options are not available. Instead, typing `^C' causes SICStus Prolog to exit, and no terminal prompts are printed.  File: sicstus.info, Node: Exiting, Next: Nested, Prev: Execution, Up: Run Intro 3.8 Exiting From The Top-Level ============================== To exit from the top-level and return to the shell, either type `^D' at the top-level, or call the built-in predicate `halt/0', or use the `e' (exit) command following a `^C' interruption.  File: sicstus.info, Node: Nested, Next: Saving, Prev: Exiting, Up: Run Intro 3.9 Nested Executions--Break ============================ The Prolog system provides a way to suspend the execution of your program and to enter a new incarnation of the top-level where you can issue queries to solve goals etc. This is achieved by issuing the query (*note Execution::): | ?- break. This invokes a recursive top-level, indicated by the message: % Break level 1 You can now type queries just as if you were at top-level. If another call of `break/0' is encountered, it moves up to level 2, and so on. To close the break and resume the execution that was suspended, type `^D'. The debugger state and current input and output streams will be restored, and execution will be resumed at the predicate call where it had been suspended after printing the message: % End break  File: sicstus.info, Node: Saving, Next: SPIDER, Prev: Nested, Up: Run Intro 3.10 Saving and Restoring Program States ======================================== Once a program has been read, the system will have available all the information necessary for its execution. This information is called a "program state". The saved-state of a program may be saved on disk for future execution. To save a program into a file FILE, type the following query. On UNIX platforms, the file becomes executable: | ?- save_program(FILE). You can also specify a goal to be run when a saved program is restored. This is done by: | ?- save_program(FILE, start). where `start/0' is the predicate to be called. Once a program has been saved into a file FILE, the following query will restore the system to the saved-state: | ?- restore(FILE). If a saved-state has been moved or copied to another machine, or if it is a symbolic link, the path names of foreign resources and other files needed upon restore are typically different at restore time from their save time values. To solve this problem, certain atoms will be renamed during restore as follows: * Atoms that had `$SP_PATH/library' (the name of the directory containing the Prolog Library) as prefix at save time will have that prefix replaced by the corresponding restore time value. * Atoms that had the name of the directory containing FILE as prefix at save time will have that prefix replaced by the corresponding restore time value. The purpose of this procedure is to be able to build and deploy an application consisting of a saved-state and other files as a directory tree with the saved-state at the root: as long as the other files maintain their relative position in the deployed copy, they can still be found upon restore. *Note Building for a Target Machine:: for an example. *Please note*: When creating a saved-state with `save_program/[1,2]', the names and paths of foreign resources, are included in the saved-state. After restoring a saved-state, this information is used to reload the foreign resources again. The state of the foreign resource in terms of global C variables and allocated memory is thus not preserved. Foreign resources may define init and deinit functions to take special action upon loading and unloading; *note Init and Deinit Functions::. As of release 3.8, partial saved-states corresponding to a set of source files, modules, and predicates can be created by the built-in predicates `save_files/2', `save_modules/2', and `save_predicates/2' respectively. These predicates create files in a binary format, by default with the prefix `.po' (for Prolog object), which can be loaded by `load_files/[1,2]'. In fact, PO files use exactly the same binary format as saved-states, and are subject to the same above-mentioned atom renaming rules. For example, to compile a program split into several source files into a single PO file, type: | ?- compile(FILES), save_files(FILES, OBJECT). For each filename given, the first goal will try to locate a source file and compile it into memory. The second goal will save the program just compiled into a PO file whose default suffix is `.po'. Thus the PO file will contain a partial memory image. *Please note*: PO files can be created with any suffix, but cannot be loaded unless the suffix is `.po'!  File: sicstus.info, Node: SPIDER, Next: Emacs Interface, Prev: Saving, Up: Run Intro 3.11 SICStus Prolog IDE ======================= SICStus Prolog IDE, also known as SPIDER, is an Eclipse-based development environment for SICStus with many powerful features. SPIDER was added in release 4.1 and is described on its own site, `http://www.sics.se/sicstus/spider/'. Some of the features of SPIDER are: _Semantic Highligting_ Code is highlighted based on semantic properties such as singleton variables, .... _On-the-fly warnings_ The editor flags things like calls to undefined predicates, incorrect use of directives, missing declarations, ... _Pop-up documentation_ Predicate documentation is parsed on-the-fly and shown when the mouse is hovering over a call. This works for both built-in and user-defined predicates. _Open Definition_ Clicking on a called predicate can bring up its source code. _Call Hierarchy_ Show callers and other references to a predicate or file. _Profiling_ Show profiling data _Source Code Coverage_ Show source code coverage, both as margin annotations and in various tabular forms. _Call Hierarchy_ Show callers and other references to a predicate or file. _File outline_ The predicates in a file are shown in an outline. They can be alphabetically sorted and non-exported predicates can be hidden from the outline. _Variable Bindings in Debugger_ The debugger shows the names and values of variables. _Debugger Backtrace_ Backtrace is shown and there are buttons for common debugger actions (Step Over, Step Out, Redo, ...). _Source Code Debugging_ Source-linked debugging. Works also for code that has no recorded source info, like the SICStus library. _Prolog Toplevel_ The ordinary toplevel is still available, including the traditional debugger interface. _Attach to embedded code_ SPIDER can attach to a SICStus runtime embedded in some other program. _Works With Existing Code_ No need to reorganize your code, SPIDER can work with your existing folder structure. _Powered by Eclipse_ Eclipse provides many features for free, like support for other programming languages, revision control, and much more. Some of these features can be seen in the following screen shot. [image src="images/spider_screenshot1.png"] Some Features of SPIDER  File: sicstus.info, Node: Emacs Interface, Prev: SPIDER, Up: Run Intro 3.12 Emacs Interface ==================== This section explains how to use the GNU Emacs interface for SICStus Prolog, and how to customize your GNU Emacs environment for it. Emacs is a powerful programmable editor especially suitable for program development. It is available for free for many platforms, including various UNIX dialects, Windows and Mac OS X. For information specific to GNU Emacs or XEmacs, see `http://www.gnu.org' and `http://www.xemacs.org' respectively. For information on running Emacs under Windows, see the `GNU Emacs FAQ For MS Windows' at `http://www.gnu.org/software/emacs/windows/ntemacs.html', much of which applies to both GNU Emacs and XEmacs. The advantages of using SICStus in the Emacs environment are source-linked debugging, auto indentation, syntax highlighting, help on predefined predicates (requires the SICStus info files to be installed), loading code from inside Emacs, auto-fill mode, and more. The Emacs interface is not part of SICStus Prolog proper, but is included in the distribution for convenience. It was written by Emil Åström and Milan Zamazal, based on an earlier version of the mode written by Masanobu Umeda. Contributions has also been made by Johan Andersson, Peter Olin, Mats Carlsson, Johan Bevemyr, Stefan Andersson, Per Danielsson, Per Mildner, Henrik Båkman, and Tamás Rozmán. Some ideas and also a few lines of code have been borrowed (with permission) from `Oz.el' by Ralf Scheidhauer and Michael Mehl, the Emacs major mode for the Oz programming language. * Menu: * Installation:: Installation * Basic Configuration:: Basic Configuration * Usage:: Usage * Mode Line:: Mode Line * Configuration:: Configuration * Tips:: Tips  File: sicstus.info, Node: Installation, Next: Basic Configuration, Up: Emacs Interface 3.12.1 Installation ------------------- *Note The Emacs Interface: (relnotes)The Emacs Interface for more information about installing the Emacs interface. There are some differences between GNU Emacs and XEmacs. This will be indicated with Emacs-Lisp comments in the examples. * Menu: * Quick-Start:: Quick-Start * Customizing Emacs:: Customizing Emacs * Enabling Emacs Support for SICStus:: Enabling Emacs Support for SICStus * Enabling Emacs Support for SICStus Documentation:: Enabling Emacs Support for SICStus Documentation  File: sicstus.info, Node: Quick-Start, Next: Customizing Emacs, Up: Installation 3.12.1.1 Quick-Start .................... Assuming the Emacs interface for SICStus Prolog has been installed in the default location, inserting a single line in your `~/.emacs' will make Emacs use the SICStus Prolog mode automatically when editing files with a `.pro' or `.pl' extension. It will also ensure Emacs can find the SICStus executables and on-line documentation, etc. Note to Windows users: `~/.emacs' denotes a file `.emacs' in whatever Emacs considers to be your _home_ directory. See `GNU Emacs FAQ For MS Windows' at `http://www.gnu.org/software/emacs/windows/ntemacs.html' for details. Under UNIX, assuming SICStus 4.2.1 was installed in `/usr/local/', add the following line: (load "/usr/local/lib/sicstus-4.2.1/emacs/sicstus_emacs_init") Under Windows, assuming SICStus 4.2.1 was installer in `C:\Program Files\SICStus Prolog 4.2.1\', add the following line: (load "C:/Program Files/SICStus Prolog 4.2.1/emacs/sicstus_emacs_init") No other configuration should be needed to get started. If you want to customize things, look in the `sictus_emacs_init.el' file and the rest of this section.  File: sicstus.info, Node: Customizing Emacs, Next: Enabling Emacs Support for SICStus, Prev: Quick-Start, Up: Installation 3.12.1.2 Customizing Emacs .......................... Version 20 of GNU Emacs and XEmacs introduced a new method for editing and storing user settings. This feature is available from the menu bar as `Customize' and particular Emacs variables can be customized with `M-x customize-variable'. Using `Customize' is the preferred way to modify the settings for Emacs and the appropriate customize commands will be indicated below, sometimes together with the old method of directly setting Emacs variables.  File: sicstus.info, Node: Enabling Emacs Support for SICStus, Next: Enabling Emacs Support for SICStus Documentation, Prev: Customizing Emacs, Up: Installation 3.12.1.3 Enabling Emacs Support for SICStus ........................................... This section is for reference only, *it can safely be skipped*; it will let you understand the setup that is performed by the `sictus_emacs_init.el' file. Assuming the Emacs interface for SICStus Prolog has been installed in the default location, inserting the following lines in your `~/.emacs' will make Emacs use this mode automatically when editing files with a `.pro' or `.pl' extension: (setq load-path (cons (expand-file-name "/usr/local/lib/sicstus-4.2.1/emacs") load-path)) (autoload 'run-prolog "prolog" "Start a Prolog sub-process." t) (autoload 'prolog-mode "prolog" "Major mode for editing Prolog programs." t) (setq prolog-use-sicstus-sd t) (setq auto-mode-alist (append '(("\\.pro$" . prolog-mode) ("\\.pl$" . prolog-mode)) auto-mode-alist)) where the path in the first line is the file system path to `prolog.el' (the generic Prolog mode) and `sicstus-support.el' (SICStus specific code). For example, `~/emacs' means that the file is in the user's home directory, in directory emacs. Windows paths can be written like `C:/Program Files/SICStus Prolog 4.2.1/emacs'. The last line above makes sure that files ending with `.pro' or `.pl' are assumed to be Prolog files and not Perl, which is the default Emacs setting for `.pl'. If this is undesirable, remove that line. It is then necessary for the user to manually switch to Prolog mode by typing `M-x prolog-mode' after opening a Prolog file; for an alternative approach, see *note Mode Line::. If the shell command `sicstus' is not available in the default path, it is necessary to set the value of the environment variable `EPROLOG' to a shell command to invoke SICStus Prolog. This is an example for C Shell: % setenv EPROLOG /usr/local/bin/sicstus  File: sicstus.info, Node: Enabling Emacs Support for SICStus Documentation, Prev: Enabling Emacs Support for SICStus, Up: Installation 3.12.1.4 Enabling Emacs Support for SICStus Documentation ......................................................... If you follow the steps in Section Quick Start, above, you can skip this section. It is possible to look up the documentation for any built-in or library predicate from within Emacs (using `C-c ?' or the menu). For this to work Emacs must be told about the location of the `info'-files that make up the documentation. The default location for the `info'-files are `/lib/sicstus-4.2.1/doc/info/' on UNIX platforms and `C:/Program Files/SICStus Prolog 4.2.1/doc/info/' under Windows. Add the following to your `~/.emacs' file, assuming INFO is the path to the info files, e.g. `C:/Program Files/SICStus Prolog 4.2.1/doc/info/' (setq Info-default-directory-list (append Info-default-directory-list '("INFO"))) for GNU Emacs, or (setq Info-directory-list (append Info-directory-list '("INFO"))) for XEmacs. You can also use `M-x customize-group info ' if your Emacs is new enough. You may have to quit and restart Emacs for these changes to take effect.  File: sicstus.info, Node: Basic Configuration, Next: Usage, Prev: Installation, Up: Emacs Interface 3.12.2 Basic Configuration -------------------------- If the following lines are not present in `~/.emacs', we suggest they are added, so that the font-lock mode (syntax coloring support) is enabled for all major modes in Emacs that support it. (global-font-lock-mode t) ; GNU Emacs (setq font-lock-auto-fontify t) ; XEmacs (setq font-lock-maximum-decoration t) These settings and more are also available through `M-x customize-group' `font-lock'. If one wants to add font-locking only to the Prolog mode, the two lines above could be replaced by: (add-hook 'prolog-mode-hook 'turn-on-font-lock) Similarly, to turn it off only for Prolog mode use: (add-hook 'prolog-mode-hook 'turn-off-font-lock)  File: sicstus.info, Node: Usage, Next: Mode Line, Prev: Basic Configuration, Up: Emacs Interface 3.12.3 Usage ------------ A Prolog process can be started by choosing `Run Prolog' from the `Prolog' menu, by typing `C-c ', or by typing `M-x run-prolog'. It is however not strictly necessary to start a Prolog process manually since it is automatically done when consulting or compiling, if needed. The process can be restarted (i.e. the old one is killed and a new one is created) by typing `C-u C-c ', in this case Emacs will also prompt for a Lisp list of extra parameters to pass on the command line. Programs are run and debugged in the normal way, with terminal I/O via the `*prolog*' buffer. The most common debugging predicates are available from the menu or via key-bindings. A particularly useful feature under the Emacs interface is source-linked debugging. This is enabled or disabled using the `Prolog/Source-linked debugging' menu entry. It can also be enabled by setting the Emacs variable `prolog-use-sicstus-sd' to `t' in `~/.emacs'. Both these methods set the Prolog flag `source_info' to `emacs'. Its value should be `emacs' while loading the code to be debugged and while debugging. If so, the debugger will display the source code location of the current goal when it prompts for a debugger command, by highlighting the the current line. If `source_info' was `off' when the code was loaded, or if it was asserted or loaded from `user', the current goal will still be shown but out of context. Note that if the code has been modified since it was last loaded, Prolog's line number information may be invalid. If this happens, just reload the relevant buffer. Another useful feature which is available for code loaded with `source_info' switched on is that the debugger can show the variable bindings for the current goal, its ancestors, and the clauses they occur in. The bindings are shown in a separate `*Prolog Bindings*' buffer. This is enabled by the `C-c C-g' command and disabled by the `C-u C-c C-g' command. Yet another feature which is available for compiled code loaded with `source_info' switched on is code coverage highlighting (*note Coverage Analysis::). Highlighting of the current buffer is refreshed by the `C-c C-o' command and cleared by the `C-u C-c C-o' command. Consultation and compilation is either done via the menu or with the following key-bindings: `C-c C-f' Consult file. `C-c C-b' Consult buffer. `C-c C-r' Consult region. `C-c C-p' Consult predicate. `C-c C-c f' Compile file. `C-c C-c b' Compile buffer. `C-c C-c r' Compile region. `C-c C-c p' Compile predicate. The boundaries used when consulting and compiling predicates are the first and last clauses of the predicate the cursor is currently in. Other useful key-bindings are: `M-a' Go to beginning of clause. Go to the previous clause if already at the beginning. `M-e' Go to end of clause. Go to the next clause if already at the end. `C-M-c' Mark clause. `C-M-a' Go to beginning of predicate. `C-M-e' Go to end of predicate. `C-M-h' Mark predicate. `M-{' Go to the previous paragraph (i.e. empty line). `M-}' Go to the next paragraph (i.e. empty line). `M-h' Mark paragraph. `C-M-n' Go to matching right parenthesis. `C-M-p' Go to matching left parenthesis. `M-;' Creates a comment at `comment-column'. This comment will always stay at this position when the line is indented, regardless of changes in the text earlier on the line, provided that `prolog-align-comments-flag' is set to `t'. `C-c C-t' `C-u C-c C-t' Enable and disable creeping, respectively. `C-c C-d' `C-u C-c C-d' Enable and disable leaping, respectively. `C-c C-z' `C-u C-c C-z' Enable and disable zipping, respectively. `C-c C-g' `C-u C-c C-g' Enable and disable bindings window, respectively. When enabled, SICStus will endeavor to show the variable bindings of the clause containing the current goal. `C-c C-g' splits the `*prolog*' window vertically and inserts the `*Prolog Bindings*' window, which shows the bindings and is updated upon every debugger command. `C-u C-c C-g' deletes the `*Prolog Bindings*' window. `C-c C-o' `C-u C-c C-o' Refresh and clear coverage highlighting for the current buffer, respectively. Lines containing coverage sites (*note Coverage Analysis::) will be highlighted in face `pltrace-face-reached-det' (defaults to green) if they were hit at least once and made no nondet calls with the execution profiler switched on; in face `pltrace-face-reached-nondet' (defaults to yellow) if they were hit at least once and made one or more nondet calls with the execution profiler switched on; otherwise, they will be highlighted in face `pltrace-face-reached-not' (defaults to red). Lines not containing coverage sites are not highlighted. `C-x SPC' `C-u C-x SPC' Set and remove a line breakpoint. This uses the advanced debugger features introduced in release 3.8; see *note Advanced Debugging::. `C-c C-s' Insert the PREDSPEC of the current predicate into the code. `C-c C-n' Insert the template of the current predicate (name, parentheses, commas) into the code. `M-RET' Insert a line break followed by the template of the current predicate into the code. This can be useful when writing recursive predicates or predicates with several clauses. See also the `prolog-electric-dot-flag' variable below. `C-c C-v a' Convert all variables in a region to anonymous variables. See also the `prolog-electric-underscore-flag' Emacs variable. `C-c ?' Help on predicate. This requires the SICStus info files to be installed. If the SICStus info files are installed in a nonstandard way, you may have to change the Emacs variable `prolog-info-predicate-index'. `C-c RET' `C-u C-c RET' Run Prolog. With the second variant, Emacs will prompt for a Lisp list of extra parameters to pass on the command line. `C-c C-c' Interrupt Prolog. The same as typing `^C' in a shell. `C-c C-\' Kill Prolog. Immediately kills the process.  File: sicstus.info, Node: Mode Line, Next: Configuration, Prev: Usage, Up: Emacs Interface 3.12.4 Mode Line ---------------- If working with an application split into several modules, it is often useful to let files begin with a "mode line": %%% -*- Mode: Prolog; Module: ModuleName; -*- The Emacs interface will look for the mode line and notify the SICStus Prolog module system that code fragments being incrementally reconsulted or recompiled should be imported into the module MODULENAME. If the mode line is missing, the code fragment will be imported into the type-in module. An additional benefit of the mode line is that it tells Emacs that the file contains Prolog code, regardless of the setting of the Emacs variable `auto-mode-alist'. A mode line can be inserted by choosing `Insert/Module modeline' in the `Prolog' menu.  File: sicstus.info, Node: Configuration, Next: Tips, Prev: Mode Line, Up: Emacs Interface 3.12.5 Configuration -------------------- The behavior of the Emacs interface can be controlled by a set of user-configurable settings. Some of these can be changed on the fly, while some require Emacs to be restarted. To set a variable on the fly, type `M-x set-variable VariableName Value '. Note that variable names can be completed by typing a few characters and then pressing . To set a variable so that the setting is used every time Emacs is started, add lines of the following format to `~/.emacs': (setq VariableName Value) Note that the Emacs interface is presently not using the `Customize' functionality to edit the settings. The available settings are: `prolog-system' The Prolog system to use. Defaults to `'sicstus', which will be assumed for the rest of this chapter. See the on-line documentation for the meaning of other settings. For other settings of `prolog-system' the variables below named `sicstus-SOMETHING' will not be used, in some cases corresponding functionality is available through variables named `prolog-SOMETHING'. `sicstus-version' The version of SICStus that is used. Defaults to `'(4 . 2)'. Note that the spaces are significant! `prolog-use-sicstus-sd' Set to `t' (the default) to enable the source-linked debugging extensions by default. The debugging can be enabled via the `Prolog' menu even if this variable is `nil'. Note that the source-linked debugging only works if `sicstus-version' is set correctly. `prolog-indent-width' How many positions to indent the body of a clause. Defaults to `tab-width', normally 8. `prolog-paren-indent' The number of positions to indent code inside grouping parentheses. Defaults to 4, which gives the following indentation. p :- ( q1 ; q2, q3 ). Note that the spaces between the parentheses and the code are automatically inserted when is pressed at those positions. `prolog-align-comments-flag' Set to `nil' to prevent single `%'-comments from being automatically aligned. Defaults to `t'. Note that comments with one `%' are indented to comment-column, comments with two `%' to the code level, and that comments with three `%' are never changed when indenting. `prolog-indent-mline-comments-flag' Set to `nil' to prevent indentation of text inside `/* ... */' comments. Defaults `t'. `sicstus-keywords' This is a list with keywords that are highlighted in a special color when used as directives (i.e. as `:- KEYWORD'). Defaults to '("block" "discontiguous" "dynamic" "initialization" "meta_predicate" "mode" "module" "multifile" "public" "volatile" "det" "nondet" ; for spdet ) `prolog-electric-newline-flag' Set to `nil' to prevent Emacs from automatically indenting the next line when pressing . Defaults to `t'. `prolog-hungry-delete-key-flag' Set to `t' to enable deletion of all whitespace before the cursor when pressing (unless inside a comment, string, or quoted atom). Defaults to `nil'. `prolog-electric-dot-flag' Set to `t' to enable the electric dot function. If enabled, pressing `.' at the end of a non-empty line inserts a dot and a newline. When pressed at the beginning of a line, a new head of the last predicate is inserted. When pressed at the end of a line with only whitespace, a recursive call to the current predicate is inserted. The function respects the arity of the predicate and inserts parentheses and the correct number of commas for separation of the arguments. Defaults to `nil'. `prolog-electric-underscore-flag' Set to `t' to enable the electric underscore function. When enabled, pressing underscore (`_') when the cursor is on a variable, replaces the variable with the anynomous variable. Defaults to `nil'. `prolog-use-prolog-tokenizer-flag' Set to `nil' to use built-in functions of Emacs for parsing the source code when indenting. This is faster than the default but does not handle some of the syntax peculiarities of Prolog. Defaults to `t'. `prolog-parse-mode' What position the parsing is done from when indenting code. Two possible settings: `'beg-of-line' and `'beg-of-clause'. The first is faster but may result in erroneous indentation in `/* ... */' comments. The default is `'beg-of-line'. `prolog-imenu-flag' Set to `t' to enable a new `Predicate' menu that contains all predicates of the current file. Choosing an entry in the menu moves the cursor to the start of that predicate. Defaults to `nil'. `prolog-info-predicate-index' The info node for the SICStus predicate index. This is important if the online help function is to be used (by pressing `C-c ?', or choosing the `Prolog/Help on predicate' menu entry). The default setting is `"(sicstus)Predicate Index"'. `prolog-underscore-wordchar-flag' Set to `nil' to not make underscore (`_') a word-constituent character. Defaults to `t'. Font-locking uses a number of "faces", which can be customized with regular Emacs commands, for instance `M-x describe-face FaceName '. The following faces are relevant: `highlight' Source code highlight at debug ports. `pltrace-face-reached-det' Highlight for a line of code reached by coverage analysis with no nondet calls made from that line of code. `pltrace-face-reached-nondet' Highlight for a line of code reached by coverage analysis with one or more nondet calls made from that line of code. `pltrace-face-reached-not' Highlight for a line of code not reached by coverage analysis. `prolog-warning-face' Face used in warning messages. `prolog-informational-face' Face used in informational messages. `prolog-exception-face' Face used in the first line of an error exception message, as well as to highlight Exception port displays. `prolog-error-face' Face used in other lines of exception messages. `prolog-call-face' Face used to highlight Call port displays. `prolog-exit-face' Face used to highlight Exit port displays. `prolog-redo-face' Face used to highlight Redo port displays. `prolog-fail-face' Face used to highlight Fail port displays. `prolog-builtin-face' Face used to highlight keywords used in directives (see `sicstus-keywords').  File: sicstus.info, Node: Tips, Prev: Configuration, Up: Emacs Interface 3.12.6 Tips ----------- Some general tips and tricks for using the SICStus mode and Emacs in general are given here. Some of the methods may not work in all versions of Emacs. * Menu: * Font-locking:: Font-locking * Auto-fill Mode:: Auto-fill Mode * Speed:: Speed * Changing Colors:: Changing Colors  File: sicstus.info, Node: Font-locking, Next: Auto-fill Mode, Up: Tips 3.12.6.1 Font-locking ..................... When editing large files, it might happen that font-locking is not done because the file is too large. Typing `M-x lazy-lock-mode', which is much faster, results in only the visible parts of the buffer being highlighted; see its Emacs on-line documentation for details. If the font-locking seems to be incorrect, choose `Fontify Buffer' from the `Prolog' menu.  File: sicstus.info, Node: Auto-fill Mode, Next: Speed, Prev: Font-locking, Up: Tips 3.12.6.2 Auto-fill Mode ....................... Auto-fill mode is enabled by typing `M-x auto-fill-mode'. This enables automatic line breaking with some features. For example, the following multiline comment was created by typing `M-;' followed by the text. The second line was indented and a `%' was added automatically. dynamics([]). % A list of pit furnace % dynamic instances  File: sicstus.info, Node: Speed, Next: Changing Colors, Prev: Auto-fill Mode, Up: Tips 3.12.6.3 Speed .............. There are several things to do if the speed of the Emacs environment is a problem: * First of all, make sure that `prolog.el' and `sicstus-support.el' are compiled, i.e. that there is a `prolog.elc' and a `sicstus-support.elc' file at the same location as the original files. To do the compilation, start Emacs and type `M-x byte-compile-file PATH ', where PATH is the path to the `*.el' file. Do not be alarmed if there are a few warning messages as this is normal. If all went well, there should now be a compiled file, which is used the next time Emacs is started. * The next thing to try is changing the setting of `prolog-use-prolog-tokenizer-flag' to `nil'. This means that Emacs uses built-in functions for some of the source code parsing, thus speeding up indentation. The problem is that it does not handle all peculiarities of the Prolog syntax, so this is a trade-off between correctness and speed. * The setting of the `prolog-parse-mode' variable also affects the speed, `'beg-of-line' being faster than `'beg-of-clause'. * Font locking may be slow. You can turn it off using customization, available through `M-x customize-group' `font-lock' . An alternative is to enable one of the lazy font locking modes. You can also turn it off completely; see *note Basic Configuration::.  File: sicstus.info, Node: Changing Colors, Prev: Speed, Up: Tips 3.12.6.4 Changing Colors ........................ The Prolog mode uses the default Emacs colors for font-locking as far as possible. The only custom settings are in the Prolog process buffer. The default settings of the colors may not agree with your preferences, so here is how to change them. If your Emacs supports it, use `Customize'. `M-x customize-group' `font-lock' will show the `Customize' settings for font locking and also contains pointers to the `Customize' group for the font lock (type)faces. The rest of this section outlines the more involved methods needed in older versions of Emacs. First of all, list all available faces (a face is a combined setting of foreground and background colors, font, boldness, etc.) by typing `M-x list-faces-display'. There are several functions that change the appearance of a face, the ones you will most likely need are: * `set-face-foreground' * `set-face-background' * `set-face-underline-p' * `make-face-bold' * `make-face-bold-italic' * `make-face-italic' * `make-face-unbold' * `make-face-unitalic' These can be tested interactively by typing `M-x FUNCTION-NAME'. You will then be asked for the name of the face to change and a value. If the buffers are not updated according to the new settings, refontify the buffer using the `Fontify Buffer' menu entry in the `Prolog' menu. Colors are specified by a name or by RGB values. Available color names can be listed with `M-x list-colors-display'. To store the settings of the faces, a few lines must be added to `~/.emacs'. For example: ;; Customize font-lock faces (add-hook 'font-lock-mode-hook '(lambda () (set-face-foreground font-lock-variable-name-face "#00a000") (make-face-bold font-lock-keyword-face) (set-face-foreground font-lock-reference-face "Blue") ))  File: sicstus.info, Node: Prolog Intro, Next: Debug Intro, Prev: Run Intro, Up: Top 4 The Prolog Language ********************* This chapter describes the syntax and semantics of the Prolog language, and introduces the central built-in predicates and other important language constructs. In many cases, an entry in a list of built-in predicates, will be annotated with keywords. These annotations are defined in *note mpg-ref-cat::. * Menu: * ref-syn:: Syntax * ref-sem:: Semantics * ref-lod:: Loading Programs * ref-sls:: Saving and Loading the Prolog Database * ref-fdi:: Files and Directories * ref-iou:: Input and Output * ref-ari:: Arithmetic * ref-lte:: Looking at Terms * ref-lps:: Looking at the Program State * ref-mgc:: Memory Use and Garbage Collection * ref-mod:: Modules * ref-mdb:: Modification of the Database * ref-all:: Sets and Bags: Collecting Solutions to a Goal * ref-gru:: Grammar Rules * ref-ere:: Errors and Exceptions * ref-msg:: Messages and Queries * ref-oth:: Other Topics  File: sicstus.info, Node: ref-syn, Next: ref-sem, Up: Prolog Intro 4.1 Syntax ========== * Menu: * ref-syn-ove:: Overview * ref-syn-trm:: Terms * ref-syn-cpt:: Compound Terms * ref-syn-ces:: Character Escaping * ref-syn-ops:: Operators and their Built-in Predicates * ref-syn-com:: Commenting * ref-syn-syn:: Formal Syntax * ref-syn-sum:: Summary of Predicates  File: sicstus.info, Node: ref-syn-ove, Next: ref-syn-trm, Up: ref-syn 4.1.1 Overview -------------- This section describes the syntax of SICStus Prolog.  File: sicstus.info, Node: ref-syn-trm, Next: ref-syn-cpt, Prev: ref-syn-ove, Up: ref-syn 4.1.2 Terms ----------- * Menu: * ref-syn-trm-ove:: Overview * ref-syn-trm-int:: Integers * ref-syn-trm-flo:: Floating-point Numbers * ref-syn-trm-ato:: Atoms * ref-syn-trm-var:: Variables * ref-syn-trm-fte:: Foreign Terms  File: sicstus.info, Node: ref-syn-trm-ove, Next: ref-syn-trm-int, Up: ref-syn-trm 4.1.2.1 Overview ................ The data objects of the language are called "term"s. A term is either a "constant", a "variable", or a "compound term". A constant is either a "number" (integer or floating-point) or an "atom". Constants are definite elementary objects, and correspond to proper nouns in natural language. Variables and compound terms are described in *note ref-syn-trm-var::, and *note ref-syn-cpt::, respectively. Foreign data types are discussed in the context of `library(structs)'; *note lib-structs::.  File: sicstus.info, Node: ref-syn-trm-int, Next: ref-syn-trm-flo, Prev: ref-syn-trm-ove, Up: ref-syn-trm 4.1.2.2 Integers ................ The printed form of an integer consists of a sequence of digits optionally preceded by a minus sign (`-'). These are normally interpreted as base 10 integers. It is also possible to enter integers in base 2 (binary), 8 (octal), and 16 (hexadecimal); this is done by preceding the digit string by the string `0b', `0o', or `0x' respectively. The characters A-F or a-f stand for digits greater than 9. For example, the following tokens all represent the integer fifteen: 15 0b1111 0o17 0xf Note that +525 is not a valid integer. There is also a special notation for character constants. E.g.: 0'A 0'\x41\ 0'\101\ are all equivalent to `65' (the character code for `A'). `0'' followed by any character except `\' (backslash) is thus read as an integer. If `0'' is followed by `\', the `\' denotes the start of an escape sequence with special meaning (*note ref-syn-syn-esc::).  File: sicstus.info, Node: ref-syn-trm-flo, Next: ref-syn-trm-ato, Prev: ref-syn-trm-int, Up: ref-syn-trm 4.1.2.3 Floating-point Numbers .............................. A floating-point number (float) consists of a sequence of digits with an embedded decimal point, optionally preceded by a minus sign (-), and optionally followed by an exponent consisting of upper- or lowercase `E' and a signed base 10 integer. Examples of floats are: 1.0 -23.45 187.6E12 -0.0234e15 12.0E-2 Note that there must be at least one digit before, and one digit after, the decimal point.  File: sicstus.info, Node: ref-syn-trm-ato, Next: ref-syn-trm-var, Prev: ref-syn-trm-flo, Up: ref-syn-trm 4.1.2.4 Atoms ............. An atom is identified by its name, which is a sequence characters, and can be written in any of the following forms: * Any sequence of alphanumeric characters (including `_'), starting with a lowercase letter. Note that an atom may not begin with an underscore. The characters that are allowed to occur in such an unquoted atom are restricted to a subset of Unicode; see *note ref-syn-syn-tok::. * Any sequence from the following set of characters (except `/*', which begins a comment): + - * / \ ^ < > = ~ : . ? @ # $ & * Any sequence of characters delimited by single quotes. Backslashes in the sequence denote escape sequences (*note ref-syn-syn-esc::), and if the single quote character is included in the sequence it must be escaped, e.g. `'can\'t''. The characters that are allowed to occur in such a quoted atom are restricted to a subset of Unicode; see *note ref-syn-syn-tok::. Backquotes are allowed as an alternative to quotes. * Any of: ! ; [] {} Note that the bracket pairs are special: `[]' and `{}' are atoms but `[', `]', `{', and `}' are not. The form `[X]' is a special notation for lists (see *note ref-syn-cpt-lis::) as an alternative to `.(X,[])', and the form `{X}' is allowed as an alternative to `{}(X)'. Examples of atoms are: a void = := 'Anything in quotes' [] *Please note:* It is recommended that you do not invent atoms beginning with the character `$', since it is possible that such names may conflict with the names of atoms having special significance for certain built-in predicates.  File: sicstus.info, Node: ref-syn-trm-var, Next: ref-syn-trm-fte, Prev: ref-syn-trm-ato, Up: ref-syn-trm 4.1.2.5 Variables ................. Variables may be written as any sequence of alphanumeric characters (including `_') beginning with either a capital letter or `_'. For example: X Value A A1 _3 _RESULT If a variable is referred to only once in a clause, it does not need to be named and may be written as an "anonymous" variable, represented by the underline character `_' by itself. Any number of anonymous variables may appear in a clause; they are read as distinct variables. Anonymous variables are not special at runtime.  File: sicstus.info, Node: ref-syn-trm-fte, Prev: ref-syn-trm-var, Up: ref-syn-trm 4.1.2.6 Foreign Terms ..................... Pointers to C data structures can be handled using the Structs package.  File: sicstus.info, Node: ref-syn-cpt, Next: ref-syn-ces, Prev: ref-syn-trm, Up: ref-syn 4.1.3 Compound Terms -------------------- * Menu: * ref-syn-cpt-lis:: Lists * ref-syn-cpt-sli:: Strings As Lists The structured data objects of Prolog are compound terms. A compound term comprises a "functor" (called the "principal functor" of the term) and a sequence of one or more terms called "arguments". A functor is characterized by its "name", which is an atom, and its "arity" or number of arguments. For example, the compound term whose principal functor is `point' of arity 3, and which has arguments X, Y, and Z, is written point(X, Y, Z) When we need to refer explicitly to a functor we will normally denote it by the form NAME/ARITY. Thus, the functor `point' of arity 3 is denoted point/3 Note that a functor of arity 0 is represented as an atom. Functors are generally analogous to common nouns in natural language. One may think of a functor as a record type and the arguments of a compound term as the fields of a record. Compound terms are usefully pictured as trees. For example, the (compound) term s(np(john), vp(v(likes), np(mary))) would be pictured as the following tree: s / \ np vp | / \ john v np | | likes mary The principal functor of this term is `s/2'. Its arguments are also compound terms. In illustration, the principal functor of the first argument is `np/1'. Sometimes it is convenient to write certain functors as "operators"; binary functors (that is, functors of two arguments) may be declared as "infix" operators, and unary functors (that is, functors of one argument) may be declared as either "prefix" or "postfix" operators. Thus it is possible to write X+Y P;Q X. All other whitespace characters must be expressed with escape sequences (*note ref-syn-syn-esc::).  File: sicstus.info, Node: ref-syn-ops, Next: ref-syn-com, Prev: ref-syn-ces, Up: ref-syn 4.1.5 Operators and their Built-in Predicates --------------------------------------------- * Menu: * ref-syn-ops-ove:: Overview * ref-syn-ops-ops:: Manipulating and Inspecting Operators * ref-syn-ops-res:: Syntax Restrictions * ref-syn-ops-bop:: Built-in Operators  File: sicstus.info, Node: ref-syn-ops-ove, Next: ref-syn-ops-ops, Up: ref-syn-ops 4.1.5.1 Overview ................ Operators in Prolog are simply a notational convenience. For example, `+' is an infix operator, so 2 + 1 is an alternative way of writing the term `+(2, 1)'. That is, `2 + 1' represents the data structure + / \ 2 1 and _not_ the number 3. (The addition would only be performed if the structure were passed as an argument to an appropriate procedure, such as `is/2'; see *note ref-ari-eae::.) Prolog syntax allows operators of three kinds: "infix", "prefix", and "postfix". An infix operator appears between its two arguments, while a prefix operator precedes its single argument and a postfix operator follows its single argument. Each operator has a "precedence", which is a number from 1 to 1200. The precedence is used to disambiguate expressions in which the structure of the term denoted is not made explicit through the use of parentheses. The general rule is that the operator with the _highest_ precedence is the principal functor. Thus if `+' has a higher precedence than `/', then a+b/c a+(b/c) are equivalent, and denote the term `+(a,/(b,c))'. Note that the infix form of the term `/(+(a,b),c)' must be written with explicit parentheses: (a+b)/c If there are two operators in the expression having the same highest precedence, the ambiguity must be resolved from the "types" of the operators. The possible types for an infix operator are * `xfx' * `xfy' * `yfx' Operators of type `xfx' are not associative: it is required that both of the arguments of the operator be subexpressions of _lower_ precedence than the operator itself; that is, the principal functor of each subexpression must be of lower precedence, unless the subexpression is written in parentheses (which gives it zero precedence). Operators of type `xfy' are right-associative: only the first (left-hand) subexpression must be of lower precedence; the right-hand subexpression can be of the _same_ precedence as the main operator. Left-associative operators (type `yfx') are the other way around. An atom named NAME is declared as an operator of type TYPE and precedence PRECEDENCE by the command :-op(PRECEDENCE, TYPE, NAME). An operator declaration can be cancelled by redeclaring the NAME with the same TYPE, but PRECEDENCE 0. The argument NAME can also be a list of names of operators of the same type and precedence. It is possible to have more than one operator of the same name, so long as they are of different kinds: infix, prefix, or postfix. Note that the ISO Prolog standard contains the restriction that there should be no infix and postfix operators with the same name, however, SICStus Prolog lifts this restriction. An operator of any kind may be redefined by a new declaration of the same kind. This applies equally to operators that are provided as standard, except for the `','' operator. Declarations for all these "built-in operators" can be found in *note ref-syn-ops-bop::. For example, the built-in operators `+' and `-' are as if they had been declared by (A) so that (B) is valid syntax, and means (C) or pictorially (D). :-op(500, yfx, [+,-]). (A) a-b+c (B) (a-b)+c (C) + / \ - c / \ a b (D) The list functor `./2' is not a standard operator, but we could declare it to be (E) and then (F) would represent the structure (G). :-op(600, xfy, .). (E) a.b.c (F) . / \ a . / \ b c (G) Contrasting this with the diagram above for a-b+c shows the difference between `yfx' operators where the tree grows to the left, and `xfy' operators where it grows to the right. The tree cannot grow at all for `xfx' operators; it is simply illegal to combine `xfx' operators having equal precedences in this way. The possible types for a prefix operator are: * `fx' * `fy' and for a postfix operator they are: * `xf' * `yf' The meaning of the types should be clear by analogy with those for infix operators. As an example, if `not' were declared as a prefix operator of type `fy', then not not P would be a permissible way to write `not(not(P))'. If the type were `fx', the preceding expression would not be legal, although not P would still be a permissible form for `not(P)'. If these precedence and associativity rules seem rather complex, remember that you can always use parentheses when in any doubt.  File: sicstus.info, Node: ref-syn-ops-ops, Next: ref-syn-ops-res, Prev: ref-syn-ops-ove, Up: ref-syn-ops 4.1.5.2 Manipulating and Inspecting Operators ............................................. To add or remove an operator, use `op(PRECEDENCE, TYPE, NAME)'. `op/3' declares the atom NAME to be an operator of the stated TYPE and PRECEDENCE. If PRECEDENCE is 0, the operator properties of NAME (if any) are cancelled. To examine the set of operators currently in force, use `current_op(PRECEDENCE, TYPE, NAME)'.  File: sicstus.info, Node: ref-syn-ops-res, Next: ref-syn-ops-bop, Prev: ref-syn-ops-ops, Up: ref-syn-ops 4.1.5.3 Syntax Restrictions ........................... Note carefully the following syntax restrictions, which serve to remove potential ambiguities associated with prefix operators. 1. The arguments of a compound term written in standard syntax must be expressions of precedence _less than_ 1000. Thus it is necessary to write the expression `P:-Q' in parentheses assert((P:-Q)) because the precedence of the infix operator `:-', and hence of the expression `P:-Q', is 1200. Enclosing the expression in parentheses reduces its precedence to 0. 2. Similarly, the elements of a list written in standard syntax must be expressions of precedence _less than_ 1000. Thus it is necessary to write the expression `P->Q' in parentheses [(P->Q)] because the precedence of the infix operator `->', and hence of the expression `P->Q', is 1050. Enclosing the expression in parentheses reduces its precedence to 0. 3. In a term written in standard syntax, the principal functor and its following `(' must _not_ be separated by any intervening spaces, newlines, or other characters. Thus point (X,Y,Z) is invalid syntax. 4. If the argument of a prefix operator starts with a `(', this `(' must be separated from the operator by at least one space or other whitespace character. Thus :-(p;q),r. (where `:-' is the prefix operator) is invalid syntax. The system would try to interpret it as the structure: , / \ :- r | ; / \ p q That is, it would take `:-' to be a functor of arity 1. However, since the arguments of a functor are required to be expressions of precedence less than 1000, this interpretation would fail as soon as the `;' (precedence 1100) were encountered. In contrast, the term: :- (p;q),r. is valid syntax and represents the following structure: :- | , / \ ; r / \ p q  File: sicstus.info, Node: ref-syn-ops-bop, Prev: ref-syn-ops-res, Up: ref-syn-ops 4.1.5.4 Built-in Operators .......................... :- op( 1200, xfx, [ :-, --> ]). :- op( 1200, fx, [ :-, ?- ]). :- op( 1150, fx, [ mode, public, dynamic, volatile, discontiguous, multifile, block, meta_predicate, initialization ]). :- op( 1100, xfy, [ ;, do ]). :- op( 1050, xfy, [ -> ]). :- op( 1000, xfy, [ ',' ]). :- op( 900, fy, [ \+, spy, nospy ]). :- op( 700, xfx, [ =, \=, is, =.., ==, \==, @<, @>, @=<, @>=, =:=, =\=, <, >, =<, >= ]). :- op( 550, xfy, [ : ]). :- op( 500, yfx, [ +, -, \, /\, \/ ]). :- op( 400, yfx, [ *, /, //, mod, rem, <<, >> ]). :- op( 200, xfx, [ ** ]). :- op( 200, xfy, [ ^ ]). :- op( 200, fy, [ +, -, \ ]). The above operators are as in the ISO Prolog standard, except the following, which are not present in ISO Prolog at all: :- op( 1150, fx, [ mode, public, dynamic, volatile, discontiguous, multifile, block, meta_predicate, initialization ]). :- op( 1100, xfy, [ do ]). :- op( 900, fy, [ spy, nospy ]). :- op( 550, xfy, [ : ]). :- op( 500, yfx, [ \ ]). :- op( 200, fy, [ + ]).  File: sicstus.info, Node: ref-syn-com, Next: ref-syn-syn, Prev: ref-syn-ops, Up: ref-syn 4.1.6 Commenting ---------------- Comments have no effect on the execution of a program, but they are very useful for making programs more comprehensible. Two forms of comments are allowed: 1. The character `%' followed by any sequence of characters up to the end of the line. 2. The symbol `/*' followed by any sequence of characters (including newlines) up to the symbol `*/'.  File: sicstus.info, Node: ref-syn-syn, Next: ref-syn-sum, Prev: ref-syn-com, Up: ref-syn 4.1.7 Formal Syntax ------------------- * Menu: * ref-syn-syn-ove:: Overview * ref-syn-syn-not:: Notation * ref-syn-syn-sen:: Syntax of Sentences as Terms * ref-syn-syn-trm:: Syntax of Terms as Tokens * ref-syn-syn-tok:: Syntax of Tokens as Character Strings * ref-syn-syn-esc:: Escape Sequences * ref-syn-syn-nte:: Notes  File: sicstus.info, Node: ref-syn-syn-ove, Next: ref-syn-syn-not, Up: ref-syn-syn 4.1.7.1 Overview ................ A Prolog program consists of a sequence of "sentences". Each sentence is a Prolog "term". How sentences are interpreted as terms is defined in *note ref-syn-syn-sen::, below. Note that a term representing a sentence may be written in any of its equivalent syntactic forms. For example, the functor `:-/2' could be written in standard prefix notation instead of as the usual infix operator. Terms are written as sequences of "tokens". Tokens are sequences of characters, which are treated as separate symbols. Tokens include the symbols for variables, constants, and functors, as well as punctuation characters such as parentheses and commas. The interpretation of sequences of tokens as terms is defined in *note ref-syn-syn-trm::. Each list of tokens that is read in (for interpretation as a term or sentence) must be terminated by a "full-stop" (a period followed by a whitespace character such as newline or space) token. Two tokens must be separated by a "space" if they could otherwise be interpreted as a single token. Both spaces and "comment"s are ignored when interpreting the token list as a term. A comment may appear at any point in a token list (separated from other tokens by spaces where necessary). The interpretation of sequences of characters as tokens is defined in *note ref-syn-syn-tok::. The next section describes the notation used in the formal definition of Prolog syntax.  File: sicstus.info, Node: ref-syn-syn-not, Next: ref-syn-syn-sen, Prev: ref-syn-syn-ove, Up: ref-syn-syn 4.1.7.2 Notation ................ * Syntactic categories (or NONTERMINALS) are printed in italics, for example QUERY. Depending on the section, a category may represent a class of either terms, token lists, or character strings. * A syntactic rule takes the general form C ::= F1 | F2 | F3 . . . which states that an entity of category C may take any of the alternative forms F1, F2, or F3. * Certain definitions and restrictions are given in ordinary English, enclosed in braces (`{}'). * A category written as `C...' denotes a sequence of one or more Cs. * A category written as `?C' denotes an optional C. Therefore `?C...' denotes a sequence of zero or more Cs. * A few syntactic categories have names with arguments, and rules in which they appear may contain meta-variables in the form of italicized capital letters. The meaning of such rules should be clear from analogy with the definite clause grammars described in *note ref-gru::. * In *note ref-syn-syn-trm::, particular tokens of the category NAME (a name beginning with a capital letter) are written as quoted atoms, while tokens that are individual punctuation characters are written literally.  File: sicstus.info, Node: ref-syn-syn-sen, Next: ref-syn-syn-trm, Prev: ref-syn-syn-not, Up: ref-syn-syn 4.1.7.3 Syntax of Sentences as Terms .................................... SENTENCE ::= MODULE `:' SENTENCE | LIST { where LIST is a list of SENTENCE } | CLAUSE | DIRECTIVE | QUERY | GRAMMAR-RULE CLAUSE ::= RULE | UNIT-CLAUSE RULE ::= HEAD `:-' BODY UNIT-CLAUSE ::= HEAD { where HEAD is not otherwise a SENTENCE } DIRECTIVE ::= `:-' BODY QUERY ::= `?-' BODY HEAD ::= MODULE `:' HEAD | GOAL { where GOAL is not a VARIABLE } BODY ::= MODULE `:' BODY | BODY `->' BODY DISJ BODY | BODY `->' BODY | `\+' BODY | BODY DISJ BODY | BODY `,' BODY | `once(BODY)' | `do(ITER,BODY)' | `if(BODY,BODY,BODY)' | TERM `^' BODY | GOAL GOAL ::= TERM { where TERM is not otherwise a BODY } GRAMMAR-RULE ::= GR-HEAD `-->' GR-BODY GR-HEAD ::= MODULE `:' GR-HEAD | GR-HEAD `,' TERMINALS | NON-TERMINAL { where NON-TERMINAL is not a VARIABLE } GR-BODY ::= MODULE `:' GR-BODY | GR-BODY `->' GR-BODY DISJ GR-BODY | GR-BODY `->' GR-BODY | `\+' GR-BODY | GR-BODY DISJ GR-BODY | GR-BODY `,' GR-BODY | `once(GR-BODY)' | `do(ITER,GR-BODY)' | `if(GR-BODY,GR-BODY,GR-BODY)' | TERM `^' GR-BODY | NON-TERMINAL | TERMINALS | GR-CONDITION NON-TERMINAL ::= TERM { where TERM is not otherwise a GR-BODY } TERMINALS ::= LIST | STRING GR-CONDITION ::= `!' | `{BODY}' MODULE ::= ATOM DISJ ::= `;' | `|' { read as `;' } ITER ::= ITER `,' ITER ::= `fromto(TERM,TERM,TERM,TERM)' | `foreach(TERM,TERM)' | `foreacharg(TERM,TERM)' | `foreacharg(TERM,TERM,TERM)' | `count(TERM,TERM,TERM)' | `for(TERM,TERM,TERM)' | `param(TERM)'  File: sicstus.info, Node: ref-syn-syn-trm, Next: ref-syn-syn-tok, Prev: ref-syn-syn-sen, Up: ref-syn-syn 4.1.7.4 Syntax of Terms as Tokens ................................. TERM-READ-IN ::= SUBTERM(1200) FULL-STOP SUBTERM(N) ::= TERM(M) { where M is less than or equal to N } TERM(N) ::= OP(N,FX) SUBTERM(N-1) { except in the case of a NUMBER if SUBTERM starts with a `(', OP must be followed by WHITESPACE-TEXT } | OP(N,FY) SUBTERM(N) { if SUBTERM starts with a `(', OP must be followed by WHITESPACE-TEXT } | 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(1100) ::= SUBTERM(1099) `|' { term with functor `;/2' } SUBTERM(1100) TERM(1000) ::= SUBTERM(999) `,' { term with functor `','/2' } SUBTERM(1000) TERM(0) ::= FUNCTOR `(' ARGUMENTS { provided there is no `)' WHITESPACE-TEXT between the FUNCTOR and the `(' } | `(' SUBTERM(1200) `)' | `{' SUBTERM(1200) `}' | LIST | STRING | CONSTANT | VARIABLE OP(N,T) ::= NAME { where NAME has been declared as an operator of type T and precedence N } ARGUMENTS ::= SUBTERM(999) | SUBTERM(999) `,' ARGUMENTS LIST ::= `[]' | `[' LISTEXPR `]' LISTEXPR ::= SUBTERM(999) | SUBTERM(999) `,' LISTEXPR | SUBTERM(999) `|' SUBTERM(999) CONSTANT ::= ATOM | NUMBER NUMBER ::= UNSIGNED-NUMBER | SIGN UNSIGNED-NUMBER | SIGN `inf' | SIGN `nan' UNSIGNED-NUMBER::= NATURAL-NUMBER | UNSIGNED-FLOAT ATOM ::= NAME FUNCTOR ::= NAME  File: sicstus.info, Node: ref-syn-syn-tok, Next: ref-syn-syn-esc, Prev: ref-syn-syn-trm, Up: ref-syn-syn 4.1.7.5 Syntax of Tokens as Character Strings ............................................. SICStus Prolog supports wide characters (up to 31 bits wide), interpreted as a superset of Unicode. Each character in the code set has to be classified as belonging to one of the character categories, such as SMALL-LETTER, DIGIT, etc. This classification is called the character-type mapping, and it is used for defining the syntax of tokens. Only character codes 0..255, i.e. the ISO-8859-1 (Latin 1) subset of Unicode, can be part of unquoted tokens(1), unless the Prolog flag `legacy_char_classification' is set; see *note ref-lps-flg::. This restriction may be lifted in the future. For quoted tokens, i.e. quoted atoms and strings, almost any sequence of code points assigned to non-private abstract characters in Unicode 5.0 is allowed. The disallowed characters are those in the whitespace-char category except that space (character code 32) is allowed despite it being a whitespace-char. An additional restriction is that the sequence of characters that makes up a quoted token must be in Normal Form C (NFC) `http://www.unicode.org/reports/tr15/'. This is currently not enforced. A future release may enforce this restriction or perform this normalization automatically. NFC is the normalization form used on the web (`http://www.w3.org/TR/charmod/') and what most software can be expected to produce by default. Any sequence consisting of only characters from Latin 1 is already in NFC. When the Prolog flag `legacy_char_classification' is set, characters in the whitespace-char category are still treated as whitespace but other character codes outside the range 0..255, assigned to non-private abstract characters in Unicode 5.0, is treated as lower case. Such characters can therefore appear as themself, without using escape sequences, both in quoted and unquoted tokens. Note: Any output produced by `write_term/2' with the option `quoted(true)' will be in NFC. This includes output from `writeq/[1,2]' and `write_canonical/[1,2]'. WHITESPACE-CHAR These are character codes 0..32, 127..160, 8206..8207, and 8232..8233. This includes ASCII characters such as , , and , as well as all characters with Unicode property "Pattern_Whitespace" including the Unicode-specific (8232). SMALL-LETTER These are character codes 97..122, i.e. the letters `a' through `z', as well as the non-ASCII character codes 170, 186, 223..246, and 248..255. If the Prolog flag `legacy_char_classification' (*note ref-lps-flg::) is set then the SMALL-LETTER set will also include almost every code point above 255 assigned to non-private abstract characters in Unicode 5.0. CAPITAL-LETTER These are character codes 65..90, i.e. the letters `A' through `Z', as well as the non-ASCII character codes 192..214, and 216..222. DIGIT These are character codes 48..57, i.e. the digits `0' through `9'. SYMBOL-CHAR These are character codes 35, 36, 38, 42, 43, 45..47, 58, 60..64, 92, 94, and 126, i.e. the characters: + - * / \ ^ < > = ~ : . ? @ # $ & In addition, the non-ASCII character codes 161..169, 171..185, 187..191, 215, and 247 belong to this character type(2). SOLO-CHAR These are character codes 33 and 59 i.e. the characters `!' and `;'. PUNCTUATION-CHAR These are character codes 37, 40, 41, 44, 91, 93, and 123..125, i.e. the characters: % ( ) , [ ] { | } QUOTE-CHAR These are character codes 34, 39, and 96 i.e. the characters `"', `'', and ``'. UNDERLINE This is character code 95 i.e. the character `_'. Other characters are unclassified and may only appear in comments and to some extent, as discussed above, in quoted atoms and strings. TOKEN ::= NAME | NATURAL-NUMBER | UNSIGNED-FLOAT | VARIABLE | STRING | PUNCTUATION-CHAR | WHITESPACE-TEXT | FULL-STOP NAME ::= QUOTED-NAME | WORD | SYMBOL | SOLO-CHAR | `[' ?WHITESPACE-TEXT `]' | `{' ?WHITESPACE-TEXT `}' WORD ::= SMALL-LETTER ?ALPHA... SYMBOL ::= SYMBOL-CHAR... { except in the case of a FULL-STOP or where the first 2 chars are `/*' } NATURAL-NUMBER ::= DIGIT... | BASE-PREFIX ALPHA... { where each ALPHA must be digits of the base indicated by BASE-PREFIX, treating a,b,... and A,B,... as 10,11,... } | `0' `'' CHAR-ITEM { yielding the character code for CHAR } UNSIGNED-FLOAT ::= SIMPLE-FLOAT | SIMPLE-FLOAT EXP EXPONENT SIMPLE-FLOAT ::= DIGIT... `.' DIGIT... EXP ::= `e' | `E' EXPONENT ::= DIGIT... | SIGN DIGIT... SIGN ::= `-' | `+' VARIABLE ::= UNDERLINE ?ALPHA... | CAPITAL-LETTER ?ALPHA... STRING ::= `"' ?STRING-ITEM... `"' STRING-ITEM ::= QUOTED-CHAR { other than `"' or `\' } | `""' | `\' ESCAPE-SEQUENCE QUOTED-ATOM ::= `'' ?QUOTED-ITEM... `'' QUOTED-ITEM ::= QUOTED-CHAR { other than `'' or `\' } | `''' | `\' ESCAPE-SEQUENCE BACKQUOTED-ATOM::= ``' ?BACKQUOTED-ITEM... ``' BACKQUOTED-ITEM::= QUOTED-CHAR { other than ``' or `\' } | ```' | `\' ESCAPE-SEQUENCE WHITESPACE-TEXT::= WHITESPACE-TEXT-ITEM... WHITESPACE-TEXT-ITEM::= WHITESPACE-CHAR | COMMENT COMMENT ::= `/*' ?CHAR... `*/' { where ?CHAR... must not contain `*/' } | `%' ?CHAR... { where ?CHAR... must not contain } FULL-STOP ::= `.' { the following token, if any, must be WHITESPACE-TEXT} CHAR ::= WHITESPACE-CHAR | PRINTING-CHAR PRINTING-CHAR ::= ALPHA | SYMBOL-CHAR | SOLO-CHAR | PUNCTUATION-CHAR | QUOTE-CHAR ALPHA ::= CAPITAL-LETTER | SMALL-LETTER | DIGIT | UNDERLINE ESCAPE-SEQUENCE::= `b' { backspace, character code 8 } | `t' { horizontal tab, character code 9 } | `n' { newline, character code 10 } | `v' { vertical tab, character code 11 } | `f' { form feed, character code 12 } | `r' { carriage return, character code 13 } | `e' { escape, character code 27 } | `d' { delete, character code 127 } | `a' { alarm, character code 7 } | OTHER-ESCAPE-SEQUENCE QUOTED-NAME ::= QUOTED-ATOM | BACKQUOTED-ATOM BASE-PREFIX ::= `0b' { indicates base 2 } | `0o' { indicates base 8 } | `0x' { indicates base 16 } CHAR-ITEM ::= QUOTED-ITEM OTHER-ESCAPE-SEQUENCE::= `x' ALPHA... `\' {treating a,b,... and A,B,... as 10,11,... } in the range [0..15], hex character code } | DIGIT... `\' { in the range [0..7], octal character code } | { ignored } | `\' { stands for itself } | `'' { stands for itself } | `"' { stands for itself } | ``' { stands for itself } QUOTED-CHAR ::= | PRINTING-CHAR ---------- Footnotes ---------- (1) Characters outside this range can still be included in quoted atoms and strings by using escape sequences (*note ref-syn-syn-esc::). (2) In release 3 and 4.0.0 the lower case characters 170 and 186 were incorrectly classified as symbol-char. This was corrected in release 4.0.1.  File: sicstus.info, Node: ref-syn-syn-esc, Next: ref-syn-syn-nte, Prev: ref-syn-syn-tok, Up: ref-syn-syn 4.1.7.6 Escape Sequences ........................ A backslash occurring inside integers in `0'' notation or inside quoted atoms or strings has special meaning, and indicates the start of an escape sequence. The following escape sequences exist: `\b' backspace (character code 8) `\t' horizontal tab (character code 9) `\n' newline (character code 10) `\v' vertical tab (character code 11) `\f' form feed (character code 12) `\r' carriage return (character code 13) `\e' escape (character code 27) `\d' delete (character code 127) `\a' alarm (character code 7) `\xHEX-DIGIT...\' the character code represented by the hexadecimal digits `\OCTAL-DIGIT...\' the character code represented by the octal digits. `\' A backslash followed by a single newline character is ignored. The purpose of this is to allow a STRING or QUOTED-NAME to be spread over multiple lines. `\\, \', \", \`' Stand for the character following the `\'.  File: sicstus.info, Node: ref-syn-syn-nte, Prev: ref-syn-syn-esc, Up: ref-syn-syn 4.1.7.7 Notes ............. 1. The expression of precedence 1000 (i.e. belonging to syntactic category TERM(1000)), which is written X,Y denotes the term `','(X,Y)' in standard syntax. 2. The parenthesized expression (belonging to syntactic category TERM(0)) (X) denotes simply the term `X'. 3. The curly-bracketed expression (belonging to syntactic category TERM(0)) {X} denotes the term `{}(X)' in standard syntax. 4. Note that, for example, `-3' denotes a number whereas `-(3)' denotes a compound term that has `- /1' as its principal functor. 5. The character `"' within a string must be written duplicated: `""'. Similarly for the character `'' within a quoted atom and for the character ``' in a backquoted atom. 6. Backslashes in strings, quoted atoms, and integers written in `0'' notation denote escape sequences. 7. A name token declared to be a prefix operator will be treated as an atom only if no TERM-READ-IN can be read by treating it as a prefix operator. 8. A name token declared to be both an infix and a postfix operator will be treated as a postfix operator only if no TERM-READ-IN can be read by treating it as an infix operator. 9. The whitespace following the full stop is not considered part of the full stop, and so it remains in the input stream.  File: sicstus.info, Node: ref-syn-sum, Prev: ref-syn-syn, Up: ref-syn 4.1.8 Summary of Predicates --------------------------- Detailed information is found in the reference pages for the following: `current_op(P,T,A) "ISO"' atom A is an operator of type T with precedence P `op(P,T,A) "ISO"' make atom A an operator of type T with precedence P  File: sicstus.info, Node: ref-sem, Next: ref-lod, Prev: ref-syn, Up: Prolog Intro 4.2 Semantics ============= * Menu: * ref-sem-pro:: Programs * ref-sem-typ:: Types of Predicates Supplied with SICStus Prolog * ref-sem-ctr:: Control Structures * ref-sem-sec:: Declarative and Procedural Semantics * ref-sem-cal:: Meta-Calls * ref-sem-exc:: Exceptions Related to Procedure Calls * ref-sem-occ:: Occurs-Check * ref-sem-con:: Summary of Control Predicates This section gives an informal description of the semantics of SICStus Prolog.  File: sicstus.info, Node: ref-sem-pro, Next: ref-sem-typ, Up: ref-sem 4.2.1 Programs -------------- A fundamental unit of a logic program is the "goal" or "procedure call" for example: gives(tom, apple, teacher) reverse([1,2,3], L) X < Y A goal is merely a special kind of term, distinguished only by the context in which it appears in the program. The principal functor of a goal is called a "predicate". It corresponds roughly to a verb in natural language, or to a procedure name in a conventional programming language. A logic "program" consists simply of a sequence of statements called "sentences", which are analogous to sentences in natural language. A sentence comprises a "head" and a "body". The head either consists of a single goal or is empty. The body consists of a sequence of zero or more goals (it may be empty). If the head is not empty, the sentence is called a "clause". If the body of a clause is empty, the clause is called a "unit clause", and is written in the form (A) where P is the head goal. We interpret this _declaratively_ as (B) and _procedurally_ as (C). P. (A) "P is true." (B) "Goal P is satisfied." (C) If the body of a clause is non-empty, the clause is called a "non-unit clause", and is written in the form (D) where P is the head goal and Q, R, and S are the goals that make up the body. We can read such a clause either declaratively as (E) or procedurally as (F). P :- Q, R, S. (D) "P is true if Q and R and S are true." (E) "To satisfy goal P, satisfy goals Q, R, and S." (F) A sentence with an empty head is called a "directive", of which the most important kind is called a "query" and is written in the form (G). Such a query is read declaratively as (H), and procedurally as (I). ?- P, Q. (G) "Are P and Q true?" (H) "Satisfy goals P and Q." (I) Sentences generally contain variables. A variable should be thought of as standing for some definite but unidentified object. This is analogous to the use of a pronoun in natural language. Note that a variable is not simply a writable storage location as in most programming languages; rather it is a local name for some data object, like the variable of pure Lisp. Note that variables in different sentences are completely independent, even if they have the same name--the _lexical scope_ of a variable is limited to a single sentence. To illustrate this, here are some examples of sentences containing variables, with possible declarative and procedural readings: `employed(X) :- employs(Y, X).' "Any X is employed if any Y employs X." "To find whether a person X is employed, find whether any Y employs X." `derivative(X, X, 1).' "For any X, the derivative of X with respect to X is 1." "The goal of finding a derivative for the expression X with respect to X itself is satisfied by the result 1." `?- ungulate(X), aquatic(X).' "Is it true, for any X, that X is an ungulate and X is aquatic?" "Find an X that is both an ungulate and aquatic." In any program, the "procedure" for a particular predicate is the sequence of clauses in the program whose head goals have that predicate as principal functor. For example, the procedure for a predicate `concatenate' of three arguments might well consist of the two clauses shown in (J) where `concatenate(L1, L2, L3)' means "the list L1 concatenated with the list L2 is the list L3". concatenate([], L, L). (J) concatenate([X|L1], L2, [X|L3]) :- concatenate(L1, L2, L3). (K) In Prolog, several predicates may have the same name but different arities. Therefore, when it is important to specify a predicate unambiguously, the form NAME/ARITY is used, for example `concatenate/3'.  File: sicstus.info, Node: ref-sem-typ, Next: ref-sem-ctr, Prev: ref-sem-pro, Up: ref-sem 4.2.2 Types of Predicates Supplied with SICStus Prolog ------------------------------------------------------ * Menu: * ref-sem-typ-hok:: Hook Predicates * ref-sem-typ-rpr:: Extendible Predicates Certain predicates are predefined by the Prolog system. Most of these cannot be changed or retracted. Such predicates are called "built-in predicates". Certain ones, however, can be modified or totally redefined. These are the hook predicates and the extendible predicates used in message and query handling.  File: sicstus.info, Node: ref-sem-typ-hok, Next: ref-sem-typ-rpr, Up: ref-sem-typ 4.2.2.1 Hook Predicates ....................... "Hook predicates" are called by the system. They enable you to modify SICStus Prolog's behavior. They are undefined by default. The idea of a hook predicate is that its clauses are independent of each other, and it makes sense to spread their definitions over several files (which may be written by different people). In other words, a hook predicate is typically declared to be multifile (*note Multifile Declarations::). Often, an application needs to combine the functionality of several software modules, among which some define clauses for such hook predicates. By simply declaring every hook predicate as multifile, the functionality of the clauses for the hook predicate is automatically combined. If this is not done, the last software module to define clauses for a particular hook predicate will effectively supersede any clauses defined for the same hook predicate in a previous module. Most hook predicates must be defined in the `user' module, and only their first solution is relevant.  File: sicstus.info, Node: ref-sem-typ-rpr, Prev: ref-sem-typ-hok, Up: ref-sem-typ 4.2.2.2 Extendible Predicates ............................. "Extendible predicates" exist to enable you to extend or modify SICStus Prolog's message and query handling. These predicates are all defined in the file `library('SU_messages')'.  File: sicstus.info, Node: ref-sem-ctr, Next: ref-sem-sec, Prev: ref-sem-typ, Up: ref-sem 4.2.3 Control Structures ------------------------ As we have seen, the goals in the body of a sentence are linked by the operator `,', which can be interpreted as conjunction (and). The Prolog language provides a number of other operators, known as "control structures", for building complex goals. Apart from being built-in predicates, these control structures play a special role in certain language features, namely Grammar Rules (*note ref-gru::), and when code is loaded or asserted in the context of modules (*note ref-mod::). The set of control structures is described in this section, and consists of: `:P,:Q "ISO"' prove P and Q `:P;:Q "ISO"' prove P or Q `+M::P "ISO"' call P in module M `:P->:Q;:R "ISO"' if P succeeds, prove Q; if not, prove R `:P->:Q "ISO"' if P succeeds, prove Q; if not, fail `! "ISO"' cut any choices taken in the current procedure `\+ :P "ISO"' goal P is not provable `?X ^ :P' there exists an X such that P is provable (used in `setof/3' and `bagof/3') `+ITERATORS do :BODY' executes BODY iteratively according to ITERATORS `if(:P,:Q,:R)' for each solution of P succeeds, prove Q; if none, prove R `once(:P) "ISO"' Find the first solution, if any, of goal P. * Menu: * ref-sem-ctr-cut:: The Cut * ref-sem-ctr-dis:: Disjunctions * ref-sem-ctr-ite:: If-Then-Else * ref-sem-ctr-naf:: Negation as Failure * ref-sem-ctr-dol:: Do-Loops * ref-sem-ctr-oth:: Other Control Structures  File: sicstus.info, Node: ref-sem-ctr-cut, Next: ref-sem-ctr-dis, Up: ref-sem-ctr 4.2.3.1 The Cut ............... Besides the sequencing of goals and clauses, Prolog provides one other very important facility for specifying control information. This is the "cut", written `!'. It is inserted in the program just like a goal, but is not to be regarded as part of the logic of the program and should be ignored as far as the declarative semantics is concerned. The effect of the cut is as follows. When first encountered as a goal, cut succeeds immediately. If backtracking should later return to the cut, the effect is to fail the _parent goal_, i.e. the goal that matched the head of the clause containing the cut, and caused the clause to be activated. In other words, the cut operation _commits_ the system to all choices made since the parent goal was invoked, and causes other alternatives to be discarded. The goals thus rendered _determinate_ are the parent goal itself, any goals occurring before the cut in the clause containing the cut, and any subgoals that were executed during the execution of those preceding goals. For example, the procedure member(X, [X|L]). member(X, [Y|L]) :- member(X, L). can be used to test whether a given term is in a list: | ?- member(b, [a,b,c]). returns the answer `yes'. The procedure can also be used to extract elements from a list, as in | ?- member(X, [d,e,f]). With backtracking this will successively return each element of the list. Now suppose that the first clause had been written instead: member(X, [X|L]) :- !. In this case, the second call above would extract only the first element of the list (`d'). On backtracking, the cut would immediately fail the entire procedure. Another example: x :- p, !, q. x :- r. This is analogous to "if p then q else r" in an Algol-like language. Note that a cut discards all the alternatives subsequent to the parent goal, even when the cut appears within a disjunction. This means that the normal method for eliminating a disjunction--by defining an extra predicate--cannot be applied to a disjunction containing a cut. A proper use of the cut is usually a major difficulty for new Prolog programmers. The usual mistakes are to over-use cut, and to let cuts destroy the logic. A cut that doesn't destroy the logic is called a "green cut"; a cut that does is called a "red cut". We would like to advise all users to follow these general rules. Also *note Writing Efficient Programs::. * Write each clause as a self-contained logic rule, which just defines the truth of goals that match its head. Then add cuts to remove any fruitless alternative computation paths that may tie up memory. * Cuts are hardly ever needed in the last clause of a predicate. * Use cuts sparingly, and _only_ at proper places. A cut should be placed at the exact point that it is known that the current choice is the correct one; no sooner, no later, usually placed right after the head, sometimes preceded by simple tests. * Make cuts as local in their effect as possible. If a predicate is intended to be determinate, define _it_ as such; do not rely on its callers to prevent unintended backtracking. * Binding output arguments before a cut is a common source of programming errors. If a predicate is not steadfast, it is usually for this reason. To illustrate the last issue, suppose that you want to write a predicate `max/3' that finds the greater of two numbers. The pure version is: max(X, Y, X) :- X >= Y. max(X, Y, Y) :- X < Y. Now since the two conditions are mutually exclusive, we can add a green cut to the first clause: max(X, Y, X) :- X >= Y, !. max(X, Y, Y) :- X < Y. Furthermore, if the `X >= Y' test fails we know that `X < Y' must be true, and therefore it is tempting to turn the green cut into a red one and drop the `X < Y' test: max(X, Y, X) :- X >= Y, !. max(X, Y, Y). Unfortunately, this version of `max/3' can give wrong answers, for example: | ?- max(10, 0, 0). yes The reason is that the query doesn't match the head of the first clause, and so we never executed the `X >= Y' test. When we dropped the `X < Y' test, we made the mistake of assuming that the head of the first clause would match any query. This is an example of a predicate that is "not steadfast". A steadfast version is: max(X, Y, Z) :- X >= Y, !, Z = X. max(X, Y, Y).  File: sicstus.info, Node: ref-sem-ctr-dis, Next: ref-sem-ctr-ite, Prev: ref-sem-ctr-cut, Up: ref-sem-ctr 4.2.3.2 Disjunction ................... It is sometimes convenient to use an additional operator `|', standing for disjunction (or). (The precedence of `|' is such that it dominates `,' but is dominated by `:-'.) An example is the clause (A), which can be read as (B). grandfather(X, Z) :- ( mother(X, Y) | father(X, Y) ), father(Y, Z). (A) "For any X, Y, and Z, X has Z as a grandfather if either the mother of X is Y or the father of X is Y, and the father of Y is Z." (B) Such uses of disjunction can usually be eliminated by defining an extra predicate. For instance, (A) is equivalent to (C) grandfather(X, Z) :- parent(X, Y), father(Y, Z). parent(X, Y) :- mother(X, Y). parent(X, Y) :- father(X, Y). (C) For historical reasons, the token `|', when used outside a list, is actually an alias for `;'. The aliasing is performed when terms are read in, so that (D) is read as if it were (E) thus you can use `;' instead of `|' for disjunction if you like. a :- b | c. (D) a :- b ; c. (E)  File: sicstus.info, Node: ref-sem-ctr-ite, Next: ref-sem-ctr-naf, Prev: ref-sem-ctr-dis, Up: ref-sem-ctr 4.2.3.3 If-Then-Else .................... As an alternative to the use of cuts, and as an etension to the disjunction syntax, Prolog provides the construct: (IF -> THEN ; ELSE) This is the same as the if-then-else construct in other programming languages. Procedurally, it calls the IF goal, committing to it if it succeeds, then calling the THEN goal, otherwise calling the ELSE goal. THEN and ELSE, but not IF, can produce more solutions on backtracking. Cuts inside of IF do not make much sense and are not recommended. If you do use them, their scope is limited to IF itself. The if-then-else construct is often used in a multiple-branch version: ( IF_1 -> THEN_1 ; IF_2 -> THEN_2 ... ; /* otherwise -> */ WHENALLELSEFAILS ) In contexts other than as the first argument of `;/2', the following two goals are equivalent: (IF -> THEN) (IF -> THEN ; fail) That is, the `->' operator has nothing to do with, and should not be confused with, logical implication. `once/1' is a control construct that provides a "local cut". That is, the following three goals are equivalent: once(IF) (IF -> true) (IF -> true ; fail) Finally, there is another version of if-then-else of the form: if(IF,THEN,ELSE) which differs from `(IF -> THEN ; ELSE)' in that `if/3' explores _all_ solutions to IF. This feature is also known as a "soft cut". There is a small time penalty for this--if IF is known to have only one solution of interest, the form `(IF -> THEN ; ELSE)' should be preferred.  File: sicstus.info, Node: ref-sem-ctr-naf, Next: ref-sem-ctr-dol, Prev: ref-sem-ctr-ite, Up: ref-sem-ctr 4.2.3.4 Negation as Failure ........................... The following construct provides a kind of pseudo-negation meaning "P is not provable". This is not real negation ("P is false"). The following two goals are equivalent: \+ P (P -> fail ; true)  File: sicstus.info, Node: ref-sem-ctr-dol, Next: ref-sem-ctr-oth, Prev: ref-sem-ctr-naf, Up: ref-sem-ctr 4.2.3.5 Do-Loops ................ Proposed in [Schimpf 2002], the control structure `(ITERATORS do BODY)' often eliminates the need to write an auxiliary predicate to perform some simple iteration. A do-loop is substituted by a goal: `PRECALLGOALS, AUX(CALLARGS).' where AUX is a new, unique predicate symbol, CALLARGS is its initial arguments, and PRECALLGOALS is a sequence of goals to be executed before calling AUX. In addition, a definition for AUX is defined, and is always of the form: `AUX(BASEARGS) :- !.' `AUX(HEADARGS) :- PREBODYGOALS, BODY, AUX(RECARGS).' where BASEARGS, HEADARGS and RECARGS are sequence of arguments and PREBODYGOALS a sequence of goals. The `do' operator is an infix operator of the same priority as `;'. It is recommended to always enclose a do-loop in parentheses. ITERATORS is a comma-separated sequence of iterators. Before giving the full list of available iterators, we first show some simple examples. The iterator `foreach(VAR,LIST)' provides iteration over a list: | ?- (foreach(X,[1,2,3]) do write(X), nl). 1 2 3 yes The same iterator can be used to construct a list: | ?- (foreach(X,[1,2,3]), foreach(Y,List) do Y is X+3). List = [4, 5, 6] The iterator `fromto(FIRST,IN,OUT,LAST)' can be used to express an accumulator with initial value FIRST, final value LAST, with IN and OUT being local variables in BODY: | ?- (foreach(X,[1,2,3]), fromto(0,In,Out,Sum) do Out is In+X). Sum = 6 The iterator `for(VAR,MIN,MAX)' will iterate BODY with VAR ranging over integers MIN thru MAX, which can be expressions: | ?- (for(I,1,5), foreach(I,List) do true). List = [1,2,3,4,5] The iterator `count(VAR,MIN,MAX)' will iterate BODY with VAR ranging over ascending integers from MIN, unifying MAX with the final value. Its main use is to count the number of iterations: | ?- (foreach(X,[a,b,c,d,e]), count(I,1,N), foreach(I-X,Pairs) do true). N = 5, Pairs = [1-a,2-b,3-c,4-d,5-e] The iterator `foreacharg(VAR,STRUCT)' provides iteration over the arguments of a structure. The variant `foreacharg(VAR,STRUCT,I)' also exists, with I ranging over the argument number, 1-based: | ?- (foreacharg(A,f(1,2,3)), foreach(A,List) do true). List = [1,2,3] | ?- (foreacharg(A,f(a,b,c,d,e),I), foreach(I-A,List) do true). List = [1-a,2-b,3-c,4-d,5-e] Do-loops have special variable scoping rules, which sometimes contradict the default rule that the scope of a variable is the clause in which it occurs: the scope of variables occurring in BODY as well as variables quantified by iterators is one loop iteration. The exact scope of variables is given in the table below. To override the scoping rule, i.e. to enable a variable to be passed to all loop iterations, use the `param(VAR)' declaration: | ?- (for(I,1,5), foreach(X,List), param(X) do true). List = [X,X,X,X,X] An omitted `param(VAR)' iterator is often spotted by the compiler, which issues a warning. Suppose that we want to define a predicate that removes all occurrences of the element `Kill' from the list LIST giving RESIDUE. A do-loop formulation is given below, along with a buggy version where `param(Kill)' is missing: _% do.pl_ delete1(List, Kill, Residue) :- % correct ( foreach(X,List), fromto(Residue,S0,S,[]), param(Kill) do (X = Kill -> S0 = S ; S0 = [X|S]) ). delete2(List, Kill, Residue) :- % wrong ( foreach(X,List), fromto(Residue,S0,S,[]) do (X = Kill -> S0 = S ; S0 = [X|S]) ). The compiler warns about the missing `param(Kill)', and for a good reason: the first version works as indended, but the second does not: | ?- [do]. % compiling /home/matsc/sicstus4/do.pl... * [Kill] treated as local in do-loop but also used outside * suggest renaming or adding param([Kill]) * Approximate lines: 8-15, file: '/home/matsc/sicstus4/do.pl' % compiled /home/matsc/sicstus4/do.pl in module user, 10 msec 192 bytes | ?- delete1([1,2,3,4,5], 3, R). R = [1,2,4,5] | ?- delete2([1,2,3,4,5], 3, R). R = [] Finally, do-loops can be used as a control structure in grammar rules as well. A do-loop in a grammar rule context will generate (or parse) the concatenation of the lists of symbols generated (or parsed) by each loop iteration. For example, suppose that you are representing three-dimensional points as lists `[X,Y,Z]'. Suppose that you need to generate a list of all such points for X between 1 and LENGTH, Y between 1 and WIDTH, and Z between 1 and HEIGHT. A generator of such lists can be written as a grammar rule with nested do-loops as follows. | ?- compile(user). | points3d(Length, Width, Height) --> | ( for(X,1,Length), | param(Width,Height) | do ( for(Y,1,Width), | param(X,Height) | do ( for(Z,1,Height), | param(X,Y) | do [[X,Y,Z]] | ) | ) | ). | ?- ^D % compiled user in module user, 0 msec 1024 bytes | ?- phrase(points3d(3,2,4), S). S = [[1,1,1],[1,1,2],[1,1,3],[1,1,4], [1,2,1],[1,2,2],[1,2,3],[1,2,4], [2,1,1],[2,1,2],[2,1,3],[2,1,4], [2,2,1],[2,2,2],[2,2,3],[2,2,4], [3,1,1],[3,1,2],[3,1,3],[3,1,4], [3,2,1],[3,2,2],[3,2,3],[3,2,4]] We now summarize the available iterators. In this table, the phrase "VAR is a local variable" means that VAR is a brand new variable in each iteration. All other variables have _global_ scope, i.e. the scope is the clause containing the do-loop. `fromto(FIRST,IN,OUT,LAST)' Iterate BODY starting with IN=FIRST until OUT=LAST. IN and OUT are local variables. For all but the first iteration, the value of IN is the same as the value of OUT in the previous iteration. `foreach(X,LIST)' Iterate BODY with X ranging over all elements of LIST. X is a local variable. Can also be used for constructing a list. `foreacharg(X,STRUCT)' Iterate BODY with X ranging over all arguments of STRUCT. X is a local variable. Cannot be used for constructing a term. `foreacharg(X,STRUCT,IDX)' Same as before, but IDX is set to the argument position of X in STRUCT, i.e. `arg(IDX, STRUCT, X)' is true. X and IDX are local variables. `for(I,MINEXPR,MAXEXPR)' Iterate BODY with I ranging over integers from MINEXPR to MAXEXPR. I is a local variable. MINEXPR and MAXEXPR can be arithmetic expressions. Can be used only for controlling iteration, i.e. MAXEXPR cannot be uninstantiated. `count(I,MIN,MAX)' Iterate BODY with I ranging over integers from MIN up to MAX. I is a local variable. Can be used for controlling iteration as well as counting, i.e. MAX can be a uninstantiated. `param(VAR)' For declaring variables global, i.e. shared with the context, even if they are quantified by some other iterator of this table. VAR can be a single variable or a list of variables. *Please note*: By default, variables in BODY have local scope. `IterSpec1, IterSpec2' The specifiers are iterated synchronously; that is, they all take their first value for the first execution of BODY, their second value for the second execution of BODY, etc. The order in which they are written does not matter, and the set of local variables in BODY is the union of those of ITERSPEC1 and ITERSPEC2. When multiple iteration specifiers are given in this way, typically not all of them will impose a termination condition on the loop (e.g. `foreach' with an uninstantiated list and `count' with an uninstantiated maximum do not impose a termination condition), but at least one of them should do so. If several specifiers impose termination conditions, then these conditions must coincide, i.e. specify the same number of iterations. Finally, we present a translation scheme for the iterators in terms of PRECALLGOALS, CALLARGS, BASEARGS, HEADARGS, PREBODYGOALS and RECARGS, as previously introduced: ITERATOR PRECALLGOALS CALLARGSBASEARGSHEADARGSPREBODYGOALS RECARGS `fromto(F,I0,I1,T)'`true' F,T `L0,L0' `I0,L1' `true' `I1,L1' `foreach(X,L)' `true' L `[]' `[X|T]' `true' `T' `foreacharg(A,S)'`functor(S,_,N),'`S,1,N1'`_,I0,I0'`S,I0,I2'`I1 is I0+1,' `S,I1,I2' `N1 is N+1' `arg(I0,S,A)' `foreacharg(A,S,I1)'`functor(S,_,N),'`S,1,N1'`_,I0,I0'`S,I0,I2'`I1 is I0+1,' `S,I1,I2' `N1 is N+1' `arg(I0,S,A)' `count(I,FE,T)'`F is FE-1' `F,T' `L0,L0' `I0,L1' `I is I0+1' `I,L1' `for(I,FE,TE)' `F is FE' `F,S' `L0,L0' `I,L1' `I1 is I+1' `I1,L1' `S is max(F,TE+1)' `param(P)' `true' P P P `true' P  File: sicstus.info, Node: ref-sem-ctr-oth, Prev: ref-sem-ctr-dol, Up: ref-sem-ctr 4.2.3.6 Other Control Structures ................................ The "all solution" predicates recognize the following construct as meaning "there exists an X such that P is true", and treats it as equivalent to P. The use of this explicit existential quantifier outside the `setof/3' and `bagof/3' constructs is superfluous and discouraged. Thus, the following two goals are equivalent: X^P P The following construct is meaningful in the context of modules (*note ref-mod::), meaning "P is true in the context of the M module": M:P  File: sicstus.info, Node: ref-sem-sec, Next: ref-sem-cal, Prev: ref-sem-ctr, Up: ref-sem 4.2.4 Declarative and Procedural Semantics ------------------------------------------ The semantics of definite clauses should be fairly clear from the informal interpretations already given. However, it is useful to have a precise definition. The "declarative semantics" of definite clauses tells us which goals can be considered true according to a given program, and is defined recursively as follows: A goal is "true" if it is the head of some clause instance and each of the goals (if any) in the body of that clause instance is true, where an "instance" of a clause (or term) is obtained by substituting, for each of zero or more of its variables, a new term for all occurrences of the variable. For example, if a program contains the procedure for `concatenate/3', declared in *note ref-sem-pro::, the declarative semantics tells us that (A) is true, because this goal is the head of a certain instance of the second clause (K) for `concatenate/3', namely (B), and we know that the only goal in the body of this clause instance is true, because it is an instance of the unit clause that is the first clause for `concatenate/3'. concatenate([a], [b], [a,b]) concatenate([a], [b], [a,b]):- concatenate([], [b], [b]). Note that the declarative semantics makes no reference to the sequencing of goals within the body of a clause, nor to the sequencing of clauses within a program. This sequencing information is, however, very relevant for the "procedural semantics" that Prolog gives to definite clauses. The procedural semantics defines exactly how the Prolog system will execute a goal, and the sequencing information is the means by which the Prolog programmer directs the system to execute his program in a sensible way. The effect of executing a goal is to enumerate, one by one, its true instances. Here is an informal definition of the procedural semantics. To "execute" a goal, the system searches forwards from the beginning of the program for the first clause whose head "matches" or "unifies" with the goal. The "unification" process [Robinson 65] finds the most general common instance of the two terms, which is unique if it exists. If a match is found, the matching clause instance is then "activated" by executing in turn, from left to right, each of the goals (if any) in its body. If at any time the system fails to find a match for a goal, it "backtracks"; that is, it rejects the most recently activated clause, undoing any substitutions made by the match with the head of the clause. Next it reconsiders the original goal that activated the rejected clause, and tries to find a subsequent clause that also matches the goal. For example, if we execute the goal expressed by the query (A) we find that it matches the head of the second clause for `concatenate/3', with `X' instantiated to `[a|X1]'. The new variable `X1' is constrained by the new goal produced, which is the recursive procedure call (B) and this goal matches the second clause, instantiating `X1' to `[b|X2]', and yielding the new goal (C). | ?- concatenate(X, Y, [a,b]). (A) concatenate(X1, Y, [b]) (B) concatenate(X2, Y, []) (C) Now this goal will only match the first clause, instantiating both `X2' and `Y' to `[]'. Since there are no further goals to be executed, we have a solution X = [a,b] Y = [] That is, the following is a true instance of the original goal: concatenate([a,b], [], [a,b]) If this solution is rejected, backtracking will generate the further solutions X = [a] Y = [b] X = [] Y = [a,b] in that order, by re-matching goals already solved once using the first clause of `concatenate/3', against the second clause. Thus, in the procedural semantics, the set of clauses H :- B1, ..., BM. H' :- B1', ..., BM'. ... are regarded as a "procedure definition" for some predicate H, and in a query ?- G1, ..., GN. each GI is regarded as a "procedure call". To execute a query, the system selects by its "computation rule" a goal, GJ say, and searches by its "search rule" a clause whose head matches GJ. Matching is done by the "unification" algorithm (see [Robinson 65]), which computes the most general unifier, "mgu", of GJ and H). The MGU is unique if it exists. If a match is found, the current query is "reduced" to a new query ?- (G1, ..., GJ-1, B1, ..., BM, GJ+1, ..., GN)MGU. and a new cycle is started. The execution terminates when the empty query has been produced. If there is no matching head for a goal, the execution backtracks to the most recent successful match in an attempt to find an alternative match. If such a match is found, an alternative new query is produced, and a new cycle is started. In SICStus Prolog, as in other Prolog systems, the search rule is simple: "search forward from the beginning of the program". The computation rule in traditional Prolog systems is also simple: "pick the leftmost goal of the current query". However, SICStus Prolog and other modern implementations have a somewhat more complex computation rule "pick the leftmost unblocked goal of the current query". A goal can be blocked on one ore more uninstantiated variables, and a variable may block several goals. Thus binding a variable can cause blocked goals to become unblocked, and backtracking can cause currently unblocked goals to become blocked again. Moreover, if the current query is ?- G1, ..., GJ-1, GJ, GJ+1, ..., GN. where GJ is the first unblocked goal, and matching GJ against a clause head causes several blocked goals in G1, ..., GJ-1 to become unblocked, these goals may become reordered. The internal order of any two goals that were blocked on the _same_ variable is retained, however. Another consequence is that a query may be derived consisting entirely of blocked goals. Such a query is said to have "floundered". The top-level checks for this condition. If detected, the outstanding blocked subgoals are printed on the standard error stream along with the answer substitution, to notify the user that the answer (s)he has got is really a speculative one, since it is only valid if the blocked goals can be satisfied. A goal is blocked if certain arguments are uninstantiated and its predicate definition is annotated with a matching block declaration (*note Block Declarations::). Goals of certain built-in predicates may also be blocked if their arguments are not sufficiently instantiated. When this mechanism is used, the control structure resembles that of coroutines, suspending and resuming different threads of control. When a computation has left blocked goals behind, the situation is analogous to spawning a new suspended thread. When a blocked goal becomes unblocked, the situation is analogous to temporarily suspending the current thread and resuming the thread to which the blocked goal belongs.  File: sicstus.info, Node: ref-sem-cal, Next: ref-sem-exc, Prev: ref-sem-sec, Up: ref-sem 4.2.5 Meta-Calls ---------------- If X is instantiated to a term that would be acceptable as the body of a clause, the goal `call(X)' is executed exactly as if that term appeared textually in place of the `call(X)', except the scope of any cut occurring in X is limited to the execution of X. That is, the cut does not "propagate" into the clause in which `call(X)' occurs. If X is not properly instantiated, an error exception is raised as described in *note ref-sem-exc::. In release 4, `call/1' has been generalized to `call/N' of any arity N between 1 and 255: the first argument is treated as template, which should be augmented by the remaining arguments, giving the goal to call. For example, the goal `call(p(X),Y,Z)' is equivalent to the goal `p(X,Y,Z)'. Note in particular that the first argument does not need to be an atom.  File: sicstus.info, Node: ref-sem-exc, Next: ref-sem-occ, Prev: ref-sem-cal, Up: ref-sem 4.2.6 Exceptions Related to Procedure Calls ------------------------------------------- All predicates that take a call argument will raise the following exceptions: `instantiation_error' Module prefix or goal uninstantiated. `type_error' Goal not a callable. `existence_error' Procedure does not exist. `context_error' Declaration or clause construct called as procedure. The reference page for such predicates will simply refer to these as "Call errors" and will go on to detail other exceptions that may be raised for a particular predicate.  File: sicstus.info, Node: ref-sem-occ, Next: ref-sem-con, Prev: ref-sem-exc, Up: ref-sem 4.2.7 Occurs-Check ------------------ Prolog's unification does not have an "occurs-check"; that is, when unifying a variable against a term, the system does not check to see if the variable occurs in the term. When the variable occurs in the term, unification should fail, but the absence of the check means that the unification succeeds, producing a "cyclic" term. Operations such as trying to print a cyclic term will cause a loop. The absence of the occurs-check is not a bug or a design oversight, but a conscious design decision. The reason for this decision is that unification with the occurs-check is at best linear on the sum of the sizes of the terms being unified, whereas unification without the occurs-check is linear on the size of the smallest of the terms being unified. For any programming language to be practical, basic operations should take constant time. Unification against a variable may be thought of as the basic operation of Prolog, and this can take constant time only if the occurs-check is omitted. Thus the absence of an occurs-check is essential to Prolog's practicality as a programming language. The inconvenience caused by this restriction is, in practice, very slight. SICStus Prolog unifies, compares (*note ref-lte-cte::), asserts, and copies cyclic terms without looping. The `write_term/[2,3]' built-in predicate can optionally handle cyclic terms. Unification with occurs-check is available as a built-in predicate; *note ref-lte-met-usu::. Predicates for subsumption and testing (a)cyclicity are available in a library package; *note lib-terms::. Other predicates usually do not handle cyclic terms well.  File: sicstus.info, Node: ref-sem-con, Prev: ref-sem-occ, Up: ref-sem 4.2.8 Summary of Control Predicates ----------------------------------- `:P,:Q "ISO"' prove P and Q `:P;:Q "ISO"' prove P or Q `+M::P "ISO"' call P in module M `:P->:Q;:R "ISO"' if P succeeds, prove Q; if not, prove R `:P->:Q "ISO"' if P succeeds, prove Q; if not, fail `! "ISO"' cut any choices taken in the current procedure `\+ :P "ISO"' goal P is not provable `?X ^ :P' there exists an X such that P is provable (used in `setof/3' and `bagof/3') `block :P "declaration"' declaration that predicates specified by P should block until sufficiently instantiated `call(:P) "ISO"' `call(:P,...)' execute P or `P(...)' `call_cleanup(:GOAL,:CLEANUP)' Executes the procedure call GOAL. When GOAL succeeds determinately, is cut, fails, or raises an exception, CLEANUP is executed. `call_residue_vars(:GOAL,?VARS)' Executes the procedure call GOAL. VARS is unified with the list of new variables created during the call that remain unbound and have blocked goals or attributes attached to them. `+ITERATORS do :BODY' executes BODY iteratively according to ITERATORS `fail "ISO"' fail (start backtracking) `false' same as `fail' `freeze(+VAR,:GOAL)' Blocks GOAL until `nonvar(VAR)' holds. `if(:P,:Q,:R)' for each solution of P that succeeds, prove Q; if none, prove R `once(:P) "ISO"' Find the first solution, if any, of goal P. `otherwise' same as true `repeat "ISO"' succeed repeatedly on backtracking `true "ISO"' succeed `when(+COND,:GOAL)' block GOAL until COND holds  File: sicstus.info, Node: ref-lod, Next: ref-sls, Prev: ref-sem, Up: Prolog Intro 4.3 Loading Programs ==================== * Menu: * ref-lod-ove:: Overview * ref-lod-lod:: The Load Predicates * ref-lod-rpx:: Redefining Procedures during Program Execution * ref-lod-dcl:: Declarations and Initializations * ref-lod-exp:: Term and Goal Expansion * ref-lod-cnd:: Conditional Compilation * ref-lod-lis:: Predicate List  File: sicstus.info, Node: ref-lod-ove, Next: ref-lod-lod, Up: ref-lod 4.3.1 Overview -------------- There are two ways of loading programs into Prolog--loading source files and loading pre-compiled PO files. Source files can be "compiled" into virtual machine code, as well as "consulted" for interpretation. Dynamic predicates are always stored in interpreted form, however. Virtual machine code runs about 8 times faster than interpreted code, and requires less runtime storage. Compiled code is fully debuggable, except certain constructs compile inline and cannot be traced. Compiled code also provides better precision for execution profiling and coverage analysis. The compiler operates in two different modes, controlled by the `compiling' Prolog flag. The possible values of the flag are: `compactcode' Compilation produces byte-coded abstract instructions. The default. `debugcode' Compilation produces _interpreted_ code, i.e. compiling is replaced by consulting. This section contains references to the use of the module system. These can be ignored if the module system is not being used (see *note ref-mod:: for information on the module system).  File: sicstus.info, Node: ref-lod-lod, Next: ref-lod-rpx, Prev: ref-lod-ove, Up: ref-lod 4.3.2 The Load Predicates ------------------------- Loading a program is accomplished by one of these predicates `[]' `[:FILE|+FILES]' `load_files(:FILES)' `load_files(:FILES, +OPTIONS)' loads source or PO file(s), whichever is the more recent, according to OPTIONS. `compile(:FILE)' loads source file into virtual machine code. `consult(:FILE)' `reconsult(:FILE)' loads source file into interpreted representation. `ensure_loaded(:FILE)' loads a source and PO file, whichever is more recent, unless the file has already been loaded and it has not been modified since it was loaded. The following notes apply to all the Load Predicates: 1. The FILE argument must be one of the following: * an atom that is the name of a file containing Prolog code; a `.pro', `.pl' or a `.po' suffix to a filename may be omitted (see *note ref-fdi-fsp::) * a list of any atom listed above; * the atom `user' 2. These predicates resolve relative file names in the same way as `absolute_file_name/2'. For information on file names refer to *note ref-fdi::. 3. The above predicates raise an exception if any of the files named in FILE does not exist, unless the `fileerrors' flag is set to `off'. Errors detected during compilation, such as an attempt to redefine a built-in predicate, also cause exceptions to be raised. However, these exceptions are caught by the compiler, an appropriate error message is printed, and compilation continues. 4. There are a number of "style warnings" that may appear when a file is compiled. These are designed to aid in catching simple errors in your programs and are initially `on', but can be turned `off' if desired by setting the appropriate flags, which are: `single_var_warnings' If `on', warnings are printed when a SENTENCE (*note ref-syn-syn-sen::) containing variables not beginning with `_' occurring once only is compiled or consulted. The Prolog flag `legacy_char_classification' (*note Prolog Flags: ref-lps-flg.) expands the set of variable names for which warnings are printed. When `legacy_char_classification' is in effect warnings are printed also for variables that occur only once and whose name begin with `_' followed by a character that is not an uppercase Latin 1 character. `redefine_warnings' This flag can take more values; see *note ref-lps-flg::. If `on', the user is asked what to do when: * a module or predicate is being redefined from a different file than its previous definition. * a predicate is being imported whilst it was locally defined already. * a predicate is being redefined locally whilst it was imported already. * a predicate is being imported whilst it was imported from another module already. `discontiguous_warnings' If `on', warnings are printed when clauses are not together in source files, and the relevant predicate has not been declared `discontiguous'. 5. By default, all clauses for a predicate are required to come from just one file. A predicate must be declared `multifile' if its clauses are to be spread across several different files. See the reference page for `multifile/1'. 6. If a file being loaded is not a module-file, all the predicates defined in the file are loaded into the source module. The form `load_files(Module:File)' can be used to load the file into the specified module. See *note ref-mod-def:: for information about module-files. If a file being loaded _is_ a module-file, it is first loaded in the normal way, the source module imports all the public predicates of the module-file except for `use_module/[1,2,3]' and `load_files/[1,2]' if you specify an import list. 7. If there are any directives in the file being loaded, that is, any terms with principal functor `:-/1' or `?-/1', these are executed as they are encountered. Only the first solution of directives is produced, and variable bindings are not displayed. Directives that fail or raise exceptions give rise to warning or error messages, but do not terminate the load. However, these warning or error messages can be intercepted by the hook `user:portray_message/2', which can call `abort/0' to terminate the load, if that is the desired behavior. 8. A common type of directive to have in a file is one that loads another file, such as :- [otherfile]. In this case, if otherfile is a relative filename it is resolved with respect to the directory containing the file that is being loaded, not the current working directory of the Prolog system. Any legal Prolog goal may be included as a directive. There is no difference between a `:-/1' and a `?-/1' goal in a file being compiled. 9. If FILE is the atom `user', or FILE is a list, and during loading of the list `user' is encountered, procedures are to be typed directly into Prolog from `user_input', e.g. the terminal. A special prompt, `| ', is displayed at the beginning of every new clause entered from the terminal. Continuation lines of clauses typed at the terminal are preceded by a prompt of five spaces. When all clauses have been typed in, the last should be followed by an end-of-file character, or the atom `end_of_file' followed by a full-stop. 10. During loading of source code, all terms being read in are subject to term expansion. Grammar rules is a special, built-in case of this mechanism. By defining the hook predicates `user:term_expansion/6' and `goal_expansion/5', you can specify any desired transformation to be done as clauses are loaded. 11. The current load context (module, file, stream, directory) can be queried using `prolog_load_context/2'. 12. Predicates loading source code are affected by the character-conversion mapping, cf. `char_conversion/2'.  File: sicstus.info, Node: ref-lod-rpx, Next: ref-lod-dcl, Prev: ref-lod-lod, Up: ref-lod 4.3.3 Redefining Procedures during Program Execution ---------------------------------------------------- You can redefine procedures during the execution of the program, which can be very useful while debugging. The normal way to do this is to use the `break' option of the debugger to enter a break state (see `break/0', *note ref-ere-int::), and then load an altered version of some procedures. If you do this, it is advisable, after redefining the procedures and exiting from the break state, to wind the computation back to the first call to any of the procedures you are changing: you can do this by using the `retry' option with an argument that is the invocation number of that call. If you do not wind the computation back like this, then: * if you are in the middle of executing a procedure that you redefine, you will find that the old definition of the procedure continues to be used until it exits or fails; * if you should backtrack into a procedure you have just redefined, alternative clauses in the old definition will still be used.  File: sicstus.info, Node: ref-lod-dcl, Next: ref-lod-exp, Prev: ref-lod-rpx, Up: ref-lod 4.3.4 Declarations and Initializations -------------------------------------- When a program is to be loaded, it is sometimes necessary to tell the system to treat some of the predicates specially. This information is supplied by including "declarations" about such predicates in the source file, preceding any clauses for the predicates that they concern. A declaration is written just as a directive is, beginning with `:-'. A declaration is effective from its occurrence through the end of file. Although declarations that affect more than one predicate may be collapsed into a single declaration, the recommended style is to write the declarations for a predicate immediately before its first clause. Operator declarations are not declarations proper, but rather directives that modify the global table of syntax operators. Operator declarations are executed as they are encountered while loading programs. The rest of this section details the available forms of predicate declarations. * Menu: * Multifile Declarations:: Multifile Declarations * Dynamic Declarations:: Dynamic Declarations * Volatile Declarations:: Volatile Declarations * Discontiguous Declarations:: Discontiguous Declarations * Block Declarations:: Block Declarations * Meta-Predicate Declarations:: Meta-Predicate Declarations * Module Declarations:: Module Declarations * Public Declarations:: Public Declarations * Mode Declarations:: Mode Declarations * Include Declarations:: Include Declarations * Initializations:: Initializations  File: sicstus.info, Node: Multifile Declarations, Next: Dynamic Declarations, Up: ref-lod-dcl 4.3.4.1 Multifile Declarations .............................. A declaration :- multifile :PREDSPEC, ..., :PREDSPEC. "ISO" where each PREDSPEC is a predicate spec, causes the specified predicates to become "multifile". This means that if more clauses are subsequently loaded from other files for the same predicate, the new clauses will not replace the old ones, but will be added at the end instead. An example where multifile declarations are particularly useful is in defining "hook predicates". A hook predicate is a user-defined predicate that somehow alters or customizes the behavior of SICStus Prolog. A number of such hook predicates are described in this manual. See also *note ref-sem-typ-hok::. Hook predicates should always be declared as multifile, as this is the convention followed in the library modules. Multifile declarations _must precede_ any other declarations for the same predicate(s)! If a file containing clauses for a multifile predicate is reloaded, the old clauses from the same file are removed. The new clauses are added at the end. If a multifile predicate is loaded from a file with no multifile declaration for it, the predicate is redefined as if it were an ordinary predicate (i.e. the user is asked for confirmation). If a multifile predicate is declared dynamic in one file, it must also be done so in the other files from which it is loaded.  File: sicstus.info, Node: Dynamic Declarations, Next: Volatile Declarations, Prev: Multifile Declarations, Up: ref-lod-dcl 4.3.4.2 Dynamic Declarations ............................ A declaration :- dynamic :PREDSPEC, ..., :PREDSPEC. "ISO" where each PREDSPEC is a predicate spec, causes the specified predicates to become dynamic, which means that other predicates may inspect and modify them, adding or deleting individual clauses. Dynamic predicates are always stored in interpreted form even if a compilation is in progress. This declaration is meaningful even if the file contains no clauses for a specified predicate--the effect is then to define a dynamic predicate with no clauses. The semantics of dynamic code is described in *note ref-mdb-bas::.  File: sicstus.info, Node: Volatile Declarations, Next: Discontiguous Declarations, Prev: Dynamic Declarations, Up: ref-lod-dcl 4.3.4.3 Volatile Declarations ............................. A declaration :- volatile :PREDSPEC, ..., :PREDSPEC. where each PREDSPEC is a predicate spec, causes the specified predicates to become "volatile". A predicate should be declared as volatile if it refers to data that cannot or should not be saved in a saved-state. In most cases a volatile predicate will be dynamic, and it will be used to keep facts about streams or memory references. When a program state is saved at runtime, the clauses of all volatile predicates will be left unsaved. The predicate definitions will be saved though, which means that the predicates will keep all its properties such as `volatile', `dynamic' or `multifile' when the saved-state is restored.  File: sicstus.info, Node: Discontiguous Declarations, Next: Block Declarations, Prev: Volatile Declarations, Up: ref-lod-dcl 4.3.4.4 Discontiguous Declarations .................................. By default, the development system issues warnings if it encounters clauses that are not together for some predicate. A declaration: :- discontiguous :PREDSPEC, ..., :PREDSPEC. "ISO" disables such warnings for the predicates specified by each PREDSPEC. The warnings can also be disabled globally by setting the `discontiguous_warnings' flag to `off'.  File: sicstus.info, Node: Block Declarations, Next: Meta-Predicate Declarations, Prev: Discontiguous Declarations, Up: ref-lod-dcl 4.3.4.5 Block Declarations .......................... The declaration :- block :BLOCKSPEC, ..., :BLOCKSPEC. where each BLOCKSPEC is a skeletal goal, specifies conditions for blocking goals of the predicate referred to by the skeletal goal (`f/3' say). The arguments of the skeletal goal can be: `-' see below `?' `anything else' ignored When a goal for `f/3' is to be executed, the mode specs are interpreted as conditions for blocking the goal, and if at least one condition evaluates to `true', the goal is blocked. A block condition evaluates to `true' if and only if all arguments specified as `-' are uninstantiated, in which case the goal is blocked until at least one of those variables is instantiated. If several conditions evaluate to `true', the implementation picks one of them and blocks the goal accordingly. The recommended style is to write the block declarations in front of the source code of the predicate they refer to. Indeed, they are part of the source code of the predicate, and must precede the first clause. For example, with the definition: :- block merge(-,?,-), merge(?,-,-). merge([], Y, Y). merge(X, [], X). merge([H|X], [E|Y], [H|Z]) :- H @< E, merge(X, [E|Y], Z). merge([H|X], [E|Y], [E|Z]) :- H @>= E, merge([H|X], Y, Z). calls to `merge/3' having uninstantiated arguments in the first _and_ third position _or_ in the second _and_ third position will suspend. The behavior of blocking goals for a given predicate on uninstantiated arguments cannot be switched off, except by abolishing or redefining the predicate.  File: sicstus.info, Node: Meta-Predicate Declarations, Next: Module Declarations, Prev: Block Declarations, Up: ref-lod-dcl 4.3.4.6 Meta-Predicate Declarations ................................... To ensure correct semantics in the context of multiple modules, some predicates are subject to module name expansion. Clauses or directives containing goals for such predicates need to have certain arguments annotated by a module prefix. A declaration: :- meta_predicate :METAPREDSPEC, ..., :METAPREDSPEC. where each METAPREDSPEC is a skeletal goal, informs the compiler which predicates and which of its arguments should be subject to such annotations. See *note ref-mod-met:: and *note ref-mod-mne:: for details.  File: sicstus.info, Node: Module Declarations, Next: Public Declarations, Prev: Meta-Predicate Declarations, Up: ref-lod-dcl 4.3.4.7 Module Declarations ........................... One of the following declarations: :- module(+MODULENAME, +EXPORTLIST). :- module(+MODULENAME, +EXPORTLIST, +OPTIONS). where EXPORTLIST is a list of predicate specs, declares that the forthcoming predicates should go into the module named MODULENAME and that the predicates listed should be exported. *Note ref-mod:: for details.  File: sicstus.info, Node: Public Declarations, Next: Mode Declarations, Prev: Module Declarations, Up: ref-lod-dcl 4.3.4.8 Public Declarations ........................... The only effect of a declaration :- public :PREDSPEC, ..., :PREDSPEC. where each PREDSPEC is a predicate spec, is to give the SICStus cross-referencer (*note The Cross-Referencer::) a starting point for tracing reachable code. In some Prologs, this declaration is necessary for making compiled predicates visible. In SICStus Prolog, predicate visibility is handled by the module system. *Note ref-mod::.  File: sicstus.info, Node: Mode Declarations, Next: Include Declarations, Prev: Public Declarations, Up: ref-lod-dcl 4.3.4.9 Mode Declarations ......................... A declaration :- mode :MODESPEC, ..., :MODESPEC. where each MODESPEC is a skeletal goal, has no effect whatsoever, but is accepted for compatibility reasons. Such declarations may be used as a commenting device, as they express the programmer's intention of data flow in predicates.  File: sicstus.info, Node: Include Declarations, Next: Initializations, Prev: Mode Declarations, Up: ref-lod-dcl 4.3.4.10 Include Declarations ............................. A directive :- include(+FILES). "ISO" where FILES is a file name or a list of file names, instructs the processor to literally embed the Prolog clauses and directives in FILES into the file being loaded. This means that the effect of the `include' directive is as if the `include' directive itself were being replaced by the text in the FILES. Including some files is thus different from loading them in several respects: * The embedding file counts as the source file of the predicates loaded, e.g. with respect to the built-in predicate `source_file/2'; *note ref-lps-apf::. * Some clauses of a predicate can come from the embedding file, and some from included files. * When including a file twice, all the clauses in it will be entered twice into the program (although this is not very meaningful). * The virtual clauses `beginning_of_file' and `end_of_file' are seen by term expansions for source files, but not for included files. SICStus Prolog uses the included file name (as opposed to the embedding file name) only in source-linked debugging and error reporting.  File: sicstus.info, Node: Initializations, Prev: Include Declarations, Up: ref-lod-dcl 4.3.4.11 Initializations ........................ A directive :- initialization :GOAL. "ISO" in a file includes GOAL to the set of goals that shall be executed "after" that file has been loaded. `initialization/1' is actually callable at any point during loading of a file. Initializations are saved by `save_modules/2' and `save_program/[1,2]', and so are executed after loading or restoring such files too. GOAL is associated with the file loaded, and with a module, if applicable. When a file, or module, is going to be reloaded, all goals earlier installed by that file, or in that module, are removed first.  File: sicstus.info, Node: ref-lod-exp, Next: ref-lod-cnd, Prev: ref-lod-dcl, Up: ref-lod 4.3.5 Term and Goal Expansion ----------------------------- During loading of source code, all terms being read in are subject to term expansion. Grammar rules is a special, built-in case of this mechanism. By defining the hook predicates `user:term_expansion/6' and `goal_expansion/5', you can specify any desired transformation to be done as clauses are loaded. Term expansions are added by defining clauses for the following hook predicate. Such clauses should follow the pattern: :- multifile user:term_expansion/6. user:term_expansion(Term1, Layout1, Ids, Term2, Layout2, [TOKEN|Ids]) :- ... nonmember(TOKEN, Ids), TOKEN_EXPANSION(Term1, Layout1, Term2, Layout2), !. where TOKEN_EXPANSION/4 should be a predicate defining how to transform a given TERM1 into TERM2. The hook is called for every TERM1 read, including at end of file, represented as the term `end_of_file'. If it succeeds, TERM2 is used for further processing; otherwise, the default grammar rule expansion is attempted. It is often useful to let a term expand to a list of directives and clauses, which will then be processed sequentially. A key idea here is IDS, which is used to look up what expansions have already been applied. The argument is supposed to be a list of tokens, each token uniquely identifying an expansion. The tokens are arbitrary atoms, and are simply added to the input list, before expansions recursively are applied. This token list is used to avoid cyclic expansions. The other arguments are for supporting source-linked debugging; see the reference page for details. Goal expansions are added by defining the hook predicate: M:goal_expansion(GOAL1, LAYOUT1, MODULE, GOAL2, LAYOUT2) :- ... which should define how to transform a given GOAL1 into GOAL2. Expansions are per module and should be defined in the module M in which GOAL1 is locally defined. It is called for every goal occurring in a clause being loaded, asserted, or meta-called. If it succeeds, GOAL2 is used for further processing, and may be arbitrarily complex. The other arguments are for supporting source-linked debugging and passing the source module; see the reference page for details. To invoke term expansion from a program, use: ?- expand_term(TERM1, TERM2). which transforms TERM1 into TERM2 using the built-in (for grammar rules) as well as user-defined term expansion rules.  File: sicstus.info, Node: ref-lod-cnd, Next: ref-lod-lis, Prev: ref-lod-exp, Up: ref-lod 4.3.6 Conditional Compilation ----------------------------- A pair of directives :- if(:GOAL). ... :- endif. will evaluate GOAL and, if the goal succeeds, the sentences between the `if/1' directive and the matching `endif/0' directive will be processed as usual. If the evaluation of GOAL does not succeed, i.e. fails or raises an exception, the sentences between the `if/1' directive and the `endif/0' directive are completely ignored, except that any conditional directives must be properly nested. In particular, term expansion will not be performed on such ignored sentences and the goals of any nested conditional directives will not be evaluated. The full form of conditional compilation directives include optional `else/0' and `elif/1' and are used as follows :- if(:GOAL1). ... :- else. ... :- endif. If the goal of the `if/1' directive succeeds, the sentences up to the matching `else/0' directive are processed as usual. Otherwise, if the goal fails or raises an exception, the sentences between the `else/0' directive and the matching `endif/0' directive are processed as usual. Finally, `elif/1' is available as a shorthand for nested uses of `if/1' and `else/0' :- if(:GOAL1). ... :- elif(:GOAL2). ... :- elif(:GOAL3). ... :- else. ... :- endif. will evaluate the goals in turn, until one of them succeeds in which case the following sentences will be processed as usual up to the corresponding `else/0', `endif/0' or `elif/1'. A valid sequence of conditional compilation directives must contain exactly one `if/1' directive followed by zero or more `elif/1' directives followed by at most one `else/0' directive followed by exactly one `endif/0' directive. Valid sequences of conditional directives can be nested. All directives that make up a sequence of conditional compilation directives must be in the same file. For instance, you cannot have a `if/1' directive in one file and then have the corresponding `endif/0' directive in a file included with an `include/1' directive. Nested conditional compilation sequences can of course be located in included files. Conditional compilation directives are handled very early in the processing of an input file. In particular, term expansion hooks will never see `if/1', `else/0', `elif/1' or `endif/0' directives. Also, neither of `if/1', `else/0', `elif/1' or `endif/0' are defined as predicates. If evaluation of a goal for `if/1' directive or an `elif/1' directive raises an exception, an error message will be written and the goal will be treated as if it failed. 4.3.6.1 Conditional Compilation Examples ........................................ Conditional compilation is useful for writing portable Prolog code since it makes it possible to adapt to peculiarities of various implementations. The Prolog flag `dialect', used by several Prolog implementations, is especially useful here. :- if(current_prolog_flag(dialect, sicstus). %% We are being compiled in SICStus %% Only SICStus has this library :- use_module(library(process), [process_create/2]). :- elif(current_prolog_flag(dialect, othervendor)). %% We are being compiled in Other Vendor, we need to provide our own %% compatibility layer :- use_module(...). process_create(A,B) :- ... :- else. %% We are being compiled in some unknown Prolog, give up. process_create(_,_) :- throw(not_implemented). :- endif. Another possible usage is for disabling, perhaps costly, debugging code when building an optimized version of the code. %% Only need environ/2 at compile-time for conditional compilation :- load_files(library(system), [when(compile_time), imports([environ/2])]). :- if(\+ environ(optimize, true)). %% This clause does some expensive sanity checks. Disabled when building %% an optimized version. foo(X) :- \+ valid_x(X), throw(invalid_x(X)). :- endif. %% This clause is always present. foo(X) :- do_x_things(X). Invoking the SICStus development system with an option `-Doptimize=true', to set the system property `optimize', and then compiling the above code will ensure that the first, sanity checking, clause is not part of the `foo/1' predicate. Invoking the development system without such an option will ensure that the sanity checking clause is part of the `foo/1' predicate.  File: sicstus.info, Node: ref-lod-lis, Prev: ref-lod-cnd, Up: ref-lod 4.3.7 Predicate List -------------------- Detailed information is found in the reference pages for the following: `[]' `[:F|+FS]' same as `load_files([F|FS])' `block :P "declaration"' predicates specified by P should block until sufficiently instantiated `compile(:F)' load compiled clauses from files F `consult(:F)' `reconsult(:F)' load interpreted clauses from files F `expand_term(+T,-X) "hookable"' term T expands to term X using `user:term_expansion/6' or grammar rule expansion `goal_expansion(+TERM1, +LAYOUT1, +MODULE, -TERM2, -LAYOUT2) "hook"' Defines transformations on goals while clauses are being compiled or asserted, and during meta-calls. `discontiguous :P "declaration,ISO"' clauses of predicates P do not have to appear contiguously `dynamic :P "declaration,ISO"' predicates specified by P are dynamic `elif(:GOAL "declaration"' Provides an alternative branch in a sequence of conditional compilation directives. `else "declaration"' Provides an alternative branch in a sequence of conditional compilation directives. `endif "declaration"' Terminates a sequence of conditional compilation directives. `ensure_loaded(:F) "ISO"' load F if not already loaded `if(:GOAL) "declaration"' Starts a sequence of conditional compilation directives for conditionally including parts of a source file. `include(+F) "declaration,ISO"' include the source file(s) F verbatim `initialization :G "declaration,ISO"' declares G to be run when program is started `load_files(:F)' `load_files(:F,+O)' load files according to options O `meta_predicate :P "declaration"' declares predicates P that are dependent on the module from which they are called `mode :P "declaration"' NO-OP: document calling modes for predicates specified by P `module(+M,+L) "declaration"' `module(+M,+L,+O) "declaration"' module M exports predicates in L, options O `multifile :P "declaration,ISO"' the clauses for P are in more than one file `public :P "declaration"' NO-OP: declare predicates specified by P public `restore(+F)' restore the state saved in file F `user:term_expansion(+TERM1, +LAYOUT1, +TOKENS1, -TERM2, -LAYOUT2, -TOKENS2) "hook"' Overrides or complements the standard transformations to be done by `expand_term/2'. `use_module(:F)' `use_module(:F,+I)' import the procedure(s) I from the module-file F `use_module(?M,:F,+I)' import I from module M, loading module-file F if necessary `volatile :P "declaration"' predicates specified by P are not to be included in saves  File: sicstus.info, Node: ref-sls, Next: ref-fdi, Prev: ref-lod, Up: Prolog Intro 4.4 Saving and Loading the Prolog Database ========================================== * Menu: * ref-sls-ove:: Overview of PO Files * ref-sls-sst:: Saved-States * ref-sls-ssl:: Selective Saving and Loading of PO Files * ref-sls-lis:: Predicate List  File: sicstus.info, Node: ref-sls-ove, Next: ref-sls-sst, Up: ref-sls 4.4.1 Overview of PO Files -------------------------- A "PO file" (Prolog object file) contains a binary representation of a set of modules, predicates, clauses and directives. They are portable between different platforms, except between 32-bit and 64-bit platforms. PO files are created by `save_files/2', `save_modules/2', and `save_predicates/2', which all save a selected set of code and data from the running application. They can be loaded by the predicates described in *note ref-lod::. PO files provide tremendous flexibility that can be used for many purposes, for example: * precompiling Prolog libraries for fast loading; * packaging Prolog code for distribution; * generating precompiled databases of application data; * selectively loading particular application databases (and rule bases); * saving Prolog data across application runs; * building and saving new application databases from within applications; The facilities for saving and loading PO files are more than just a convenience when developing programs; they are also a powerful tool that can be used as part of the application itself.  File: sicstus.info, Node: ref-sls-sst, Next: ref-sls-ssl, Prev: ref-sls-ove, Up: ref-sls 4.4.2 Saved-States ------------------ Saved-states are just a special case of PO files. The `save_program/[1,2]' predicate will save the execution state in a file. The state consists of all predicates and modules except built-in predicates and clauses of volatile predicates, the current operator declarations, the current character-conversion mapping, the values of all writable Prolog flags except those marked as "volatile" in *note ref-lps-flg::, any blackboard data (*note ref-mdb-bbd::), database data (*note ref-mdb-bas::), and as of release 4.2, information for source-linked debugging. A saved-state, can be restored using the `restore/1' predicate from within Prolog: | ?- restore(FILE). which will replace the current program state by the one in FILE. A saved-state can also be given as an option to the `sicstus' command: % sicstus -r FILE which will start execution by restoring FILE. The location (i.e. directory) of the saved-state, when it is created with `save_program/[1,2]' and loaded with `restore/1', is treated in a special way in order to make it possible locate files when the saved-state has been moved. *Note Saving:: for more information. The `save_program/2' predicate can be used to specify an initial goal that will be run when the saved-state is restored. For example: | ?- save_program(saved_state,initial_goal([a,b,c])). When `saved_state' is loaded `initial_goal/1' will be called. This allows saved-states to be generated that will immediately start running the user's program when they are restored. In addition to this `save_program/2' facility, see also the `initialization/1' facility to declare goal to be executed upon loading (*note Initializations::).  File: sicstus.info, Node: ref-sls-ssl, Next: ref-sls-lis, Prev: ref-sls-sst, Up: ref-sls 4.4.3 Selective Saving and Loading of PO Files ---------------------------------------------- The `save_program/[1,2]' and `restore/1' predicates discussed in the previous section are used for saving and restoring the entire Prolog database. To save selected parts of a Prolog database, the predicates `save_files/2', `save_modules/2', and `save_predicates/2' are used. To save everything that was loaded from the files `src1.pl' and `src2.pl' into `file1.po' (extensions optional), you would use: | ?- save_files([src1,src2],file1). Any module declarations, predicates, multifile clauses, or directives encountered in those files will be saved. Source file information as provided by `source_file/[1,2]' for the relevant predicates and modules is also saved. To save the modules `user' and `special' into `file2.po' you would use: | ?- save_modules([user,special],file2). The module declarations, predicates, multifile clauses and initializations belonging to those modules will be saved. Source file information and embedded directives (except initializations) are _not_ saved. To just save certain predicates into `file3.po' you would use: | ?- save_predicates([person/2,dept/4],file3). This will only save the predicates specified. When the PO file is loaded the predicates will be loaded into the same module they were in originally. Any PO file, however generated, can be loaded into Prolog with `load_files/[1,2]': | ?- load_files(file1). or, equivalently: | ?- [file1]. The information from each PO file loaded is incrementally added to the database. This means that definitions from later loads may replace definitions from previous loads. The predicates `load_files/[1,2]' are used for compiling and loading source files as well as PO files. If `file1.po' and `file1.pl' both exist (and `file1' does not), `load_files(file1)' will load the source (`.pl') or the PO, whichever is the most recent. Refer to *note ref-lod:: for more information on loading programs, and also to the reference page for `load_files/[1,2]'.  File: sicstus.info, Node: ref-sls-lis, Prev: ref-sls-ssl, Up: ref-sls 4.4.4 Predicate List -------------------- Detailed information is found in the reference pages for the following: `initialization :G "declaration,ISO"' declares G to be run when program is started `load_files(:F)' `load_files(:F,+O)' load files according to options O `user:runtime_entry(+S) "hook"' entry point for a runtime system `save_files(+L,+F)' Saves the modules, predicates and clauses and directives in the given files L into file F `save_modules(+L,+F)' save the modules specifed in L into file F `save_predicates(:L,+F)' save the predicates specified in L into file F `save_program(+F)' `save_program(+F,:G)' save all Prolog data into file F with startup goal G `volatile :P "declaration"' declares predicates specified by P to not be included in saves.  File: sicstus.info, Node: ref-fdi, Next: ref-iou, Prev: ref-sls, Up: Prolog Intro 4.5 Files and Directories ========================= * Menu: * ref-fdi-fsp:: The File Search Path Mechanism * ref-fdi-syn:: Syntactic Rewriting * ref-fdi-pre:: List of Predicates  File: sicstus.info, Node: ref-fdi-fsp, Next: ref-fdi-syn, Up: ref-fdi 4.5.1 The File Search Path Mechanism ------------------------------------ * Menu: * ref-fdi-fsp-def:: Defining File Search Paths * ref-fdi-fsp-ffs:: Frequently Used File Specifications * ref-fdi-fsp-pre:: Predefined File Search Paths As a convenience for the developer and as a means for extended portability of the final application, SICStus Prolog provides a flexible mechanism to localize the definitions of the system dependent parts of the file and directory structure a program relies on, in such a way that the application can be moved to a different directory hierarchy or to a completely new file system, with a minimum of effort. This mechanism, which can be seen as a generalization of the `user:library_directory/1' scheme available in previous releases, presents two main features: 1. An easy way to create aliases for frequently used directories, thus localizing to one single place in the program the physical directory name, which typically depends on the file system and directory structure. 2. A possibility to associate more than one directory specification with each alias, thus giving the developer full freedom in sub-dividing libraries, and other collections of programs, as it best suits the structure of the external file system, without making the process of accessing files in the libraries any more complicated. In this case, the alias can be said to represent a file search path, not only a single directory. The directory aliasing mechanism, together with the additional file search capabilities of `absolute_file_name/3', can effectively serve as an intermediate layer between the external world and a portable program. For instance, the developer can hide the directory representation by defining directory aliases, and he can automatically get a proper file extension added, dependent on the type of file he wants to access, by using the appropriate options to `absolute_file_name/3'. A number of directory aliases and file search paths, are predefined in the SICStus Prolog system. The most important of those is the `library' file search path, giving the user instant access to the SICStus library, consisting of several sub-directories and extensive supported programs and tools. Specifying a library file, using the alias, is possible simply by replacing the explicit file (and directory) specification with the following term: library(FILE) The name of the file search path, in this case `library', is the main functor of the term, and indicates that FILE is to be found in one of the library directories. The association between the alias `library' (the name of the search path) and the library directories (the definitions of the search path), is extended by Prolog facts, `user:library_directory/1', which are searched in sequence to locate the file. Each of these facts specifies a directory where to search for FILE, whenever a file specification of the form `library(FILE)' is encountered. The library mechanism discussed above, which can be extended with new directories associated with the alias `library', has become subsumed by a more general aliasing mechanism, in which arbitrary names can be used as aliases for directories. The general mechanism also gives the possibility of defining path aliases in terms of already defined aliases. In addition to `library', the following aliases are predefined in SICStus Prolog: `runtime', `system', `application', `temp', and `path'. The interpretation of the predefined aliases are explained below.  File: sicstus.info, Node: ref-fdi-fsp-def, Next: ref-fdi-fsp-ffs, Up: ref-fdi-fsp 4.5.1.1 Defining File Search Paths .................................. The information about which directories to search when an alias is encountered is extended by clauses for the hook predicate `user:file_search_path/2', of the following form: user:file_search_path(PATHALIAS, DIRECTORYSPEC). PATHALIAS must be an atom. It can be used as an alias for DIRECTORYSPEC. DIRECTORYSPEC Can either be an atom, spelling out the name of a directory, or a compound term using other path aliases to define the location of the directory. The directory path may be absolute, as in (A) or relative as in (B), which defines a path relative to the current working directory. Then, files may be referred to by using file specifications of the form similar to `library(FILE)'. For example, (C), names the file `/usr/jackson/.login', while (D) specifies the path `etc/demo/my_demo' relative to the current working directory. user:file_search_path(home, '/usr/jackson'). (A) user:file_search_path(demo, 'etc/demo'). (B) home('.login') (C) demo(my_demo) (D) As mentioned above, it is also possible to have multiple definitions for the same alias. If clauses (E) and (F) define the `home' alias, to locate the file specified by (G) each `home' directory is searched in sequence for the file `.login'. If `/usr/jackson/.login' exists, it is used. Otherwise, `/u/jackson/.login' is used if it exists. user:file_search_path(home, '/usr/jackson'). (E) user:file_search_path(home, '/u/jackson'). (F) home('.login') (G) The directory specification may also be a term of arity 1, in which case it specifies that the argument of the term is relative to the `user:file_search_path/2' defined by its functor. For example, (H) defines a directory relative to the directory given by the `home' alias. Therefore, the alias `sp_directory' represents the search path `/usr/jackson/prolog/sp' followed by `/u/jackson/prolog/sp'. Then, the file specification (I) refers to the file (J), if it exists. Otherwise, it refers to the file (K), if it exists. user:file_search_path(sp_directory, home('prolog/sp')). (H) sp_directory(test) (I) /usr/jackson/prolog/sp/test (J) /u/jackson/prolog/sp/test (K) Aliases such as `home' or `sp_directory' are useful because even if the `home' directory changes, or the `sp_directory' is moved to a different location, only the appropriate `user:file_search_path/2' facts need to be changed. Programs relying on these paths are not affected by the change of directories because they make use of file specifications of the form `home(FILE)' and `sp_directory(FILE)'. All built-in predicates that take file specification arguments allow these specifications to include path aliases defined by `user:file_search_path/2' facts. The main predicate for expanding file specifications is `absolute_file_name/[2,3]'. *Please note:* The `user:file_search_path/2' database may contain directories that do not exist or are syntactically invalid (as far as the operating system is concerned). If an invalid directory is part of the database, the system will fail to find any files in it, and the directory will effectively be ignored.  File: sicstus.info, Node: ref-fdi-fsp-ffs, Next: ref-fdi-fsp-pre, Prev: ref-fdi-fsp-def, Up: ref-fdi-fsp 4.5.1.2 Frequently Used File Specifications ........................................... Frequently used `user:file_search_path/2' facts are best defined using the initialization file `~/.sicstusrc' or `~/sicstus.ini', which is consulted at startup time by the Development System. Therefore, with reference to the examples from *note ref-fdi-fsp-def::, clauses like the one following should be placed in the initialization file so that they are automatically available to user programs after startup: :- multifile user:file_search_path/2. user:file_search_path(home, '/usr/jackson'). user:file_search_path(sp_directory, home('prolog/sp')). user:file_search_path(demo, 'etc/demo').  File: sicstus.info, Node: ref-fdi-fsp-pre, Prev: ref-fdi-fsp-ffs, Up: ref-fdi-fsp 4.5.1.3 Predefined File Search Paths .................................... `user:file_search_path/2' is undefined at startup, but all callers first try a number of default file search paths, almost as if `user:file_search_path/2' had the following initial clauses. Therefore, to expand file search paths, you should not call `user:file_search_path/2' directly, but instead call `absolute_file_name/[2,3]'. See *note ref-lps-flg:: for more info on the Prolog flag `host_type'. The system properties `SP_APP_DIR' and `SP_RT_DIR' expand respectively to the absolute path of the directory that contains the executable and the directory that contains the SICStus runtime. The system property `SP_TEMP_DIR' expands to a directory suitable for storing temporary files, it is particularly useful with the `open/4' option `if_exists(generate_unique_name)'. %% file_search_path/2 (virtual) initial clauses file_search_path(library, '$SP_LIBRARY_DIR'). file_search_path(library, Path) :- library_directory(Path). file_search_path(system, Platform) :- prolog_flag(host_type, Platform). file_search_path(application, '$SP_APP_DIR'). file_search_path(runtime, '$SP_RT_DIR'). file_search_path(temp, '$SP_TEMP_DIR'). file_search_path(path, Path) :- %% enumerate all directories in $PATH ... The only default expansion for the `library' file search path is the value of the system property `SP_LIBRARY_DIR'. However, you can add expansions for `library' by adding clauses to `user:library_directory/1' (which is initially undefined). This feature is mainly for compatibility with earlier releases. It is better to add your own names for file search paths directly to `user:file_search_path/2' and not extend the file search path `library' at all. :- multifile user:library_directory/1. user:library_directory('/home/joe/myprologcode/'). user:library_directory('/home/jane/project/code').  File: sicstus.info, Node: ref-fdi-syn, Next: ref-fdi-pre, Prev: ref-fdi-fsp, Up: ref-fdi 4.5.2 Syntactic Rewriting ------------------------- A file specification must be an atom or a compound term with arity 1. Such compound terms are transformed to atoms as described in *note ref-fdi-fsp::. Let FILESPEC be the given or transformed atomic file specification. The file specification `user' stands for the standard input or output stream, depending on context. A file specification FILESPEC other than `user' is subject to "syntactic rewriting". Depending on the operation, the resulting absolute filename is subject to further processing. Syntactic rewriting is performed wrt. a context directory CONTEXT (an absolute path), in the following steps: * Under Windows, all `\' characters are converted to `/'. This replacement is also performed, as needed, during all subsequent steps. * A `$VAR' in the beginning of FILESPEC, followed by `/' or the end of the path, is replaced by the absolute path of the value of the system property VAR. This is especially useful when the system property has no explicit value and thus takes its value from the environment variable with the same name. If VAR doesn't exist or its value is empty, a permission error is raised. A relative path that does not begin with `/' is made absolute by prepending CONTEXT followed by a `/'. Note that, under UNIX, all paths that begin with `/' are absolute. Under Windows only, a relative path that begins with a `/' is made absolute by prepending the root (see below) of CONTEXT. * A `~USER' in the beginning of FILESPEC, followed by `/' or the end of the path, is replaced by the absolute path of the home directory of USER. If the home directory of USER cannot be determined, a permission error is raised. Under Windows this has not been implemented, instead a permission error is raised. If the home directory of USER is a relative path, it is made absolute using CONTEXT if needed. * A `~' in the beginning of FILESPEC, followed by `/' or the end of the path, is replaced by the absolute path of the home directory of the current user. If the home directory of the current user cannot be determined, a permission error is raised. The the home directory of the current user is a relative path it is made absolute using CONTEXT if needed. Under Windows, the home directory of the current user is determined using the system properties or environment variables `HOMEDRIVE' and `HOMEPATH'. * If FILESPEC is a relative file name, CONTEXT is prepended to it. * The ROOT of the file name is determined. Under UNIX this is simply the initial `/', if any. Under Windows there are several variants of roots, as follows. - DRIVELETTER`:/' where DRIVELETTER is a single upper or lower case character in the range `a' to `z'. For example, `C:/'. - `//?/'DRIVELETTER`:/' This is transformed to DRIVELETTER`:/'. - `//'HOST`/'SHARE`/' (a `UNC' path, also known as a "network path") where HOST and SHARE are non-empty and do not contain `/'. - `//?/unc/'HOST`/'SHARE`/' This is transformed to `//'HOST`/'SHARE`/' If no ROOT can be determined a permission error is raised. A path is absolute if and only if it is begins with a root, as above. * The following steps are repeatedly applied to the last `/' of the ROOT and the characters that follow it repeatedly until no change occurs. 1. Repeated occurrences of `/' are replaced by a single `/'. 2. `/.', followed by `/' or the end of the path, is replaced by `/'. 3. `/'PARENT`/..', followed by `/' or the end of the path, is replaced by `/'. If the path still contains `/..', followed by `/' or the end of the path, a permission error is raised. * Any trailing `/' is deleted unless it is part of the ROOT. * Finally, under Windows, the path is normalized as follows: All Latin 1 characters (i.e. character codes in [0..255]) are converted to lower case. All other characters are converted to upper case. File systems under Windows are generally case insensitive. This step ensures that two file names that differ only in case, and therefore would reference the same file in the file system, will normalize to identical atoms. A downside to this normalization is that you cannot choose the case used for files created by SICStus Prolog on file systems such as NTFS that are case-preserving (but case-insensitive). For instance, you cannot create a file that has a mixed-case name in the file system, such as `MyClass.java'. Such a file would instead have a file system name `myclass.java'. This seldom matters, except for aesthetics, since any Windows application that tries to open a file named `MyClass.java' will also find `myclass.java'. The following UNIX examples assumes that CONTEXT is `/usr/'; that the environment variables `VAR1', `VAR2', `VAR3' have the values `/opt/bin', `foo' and `~/temp' respectively and that the home directory of the current user, `joe', is `/home/joe'. /foo/bar ==> /foo/bar /foo/.//bar/../blip/// ==> /foo/blip /foo//../bar/../../blip ==> error $VAR1/../local/ ==> /opt/local $VAR2/misc/. ==> /usr/foo/misc $VAR3/misc/. ==> /home/joe/temp/misc ~joe/../jenny/bin. ==> /home/jenny/bin The following Windows examples assume that CONTEXT is `C:/Source/proj1'; that the environment variables `VAR1', `VAR2', `VAR3' have the values `\\server\docs\brian', `foo' and `~/temp' respectively and that the home directory of the current user is `C:/home'. /foo/bar ==> C:/foo/bar foo//../../blip ==> c:/source/blip $VAR1/../local/ ==> //server/docs/local $VAR2/misc/. ==> c:/source/proj1/foo/misc $VAR3/misc/. ==> c:/home/temp/misc ~joe/../jenny/bin. ==> error  File: sicstus.info, Node: ref-fdi-pre, Prev: ref-fdi-syn, Up: ref-fdi 4.5.3 List of Predicates ------------------------ Detailed information is found in the reference pages for the following: `absolute_file_name(+R,-A) "hookable"' `absolute_file_name(+R,-A,+O) "hookable"' expand relative filename R to absolute file name A using options specified in O `user:file_search_path(+F,-D) "hook"' directory D is included in file search path F `user:library_directory(-D) "hook"' D is a library directory that will be searched  File: sicstus.info, Node: ref-iou, Next: ref-ari, Prev: ref-fdi, Up: Prolog Intro 4.6 Input and Output ==================== * Menu: * ref-iou-bas:: Introduction * ref-iou-str:: About Streams * ref-iou-tin:: Term Input * ref-iou-tou:: Term Output * ref-iou-cin:: Byte and Character Input * ref-iou-cou:: Byte and Character Output * ref-iou-sfh:: Stream and File Handling * ref-iou-sos:: Reading the State of Opened Streams * ref-iou-raf:: Random Access to Files * ref-iou-sum:: Summary of Predicates and Functions  File: sicstus.info, Node: ref-iou-bas, Next: ref-iou-str, Up: ref-iou 4.6.1 Introduction ------------------ Prolog provides two classes of predicates for input and output: those that handle individual bytes or characters, and those that handle complete Prolog terms. Input and output happen with respect to "stream"s. Therefore, this section discusses predicates that handle files and streams in addition to those that handle input and output of bytes, characters and terms.  File: sicstus.info, Node: ref-iou-str, Next: ref-iou-tin, Prev: ref-iou-bas, Up: ref-iou 4.6.2 About Streams ------------------- * Menu: * ref-iou-str-not:: Programming Note * ref-iou-str-sca:: Stream Categories A Prolog stream can refer to a file or to the user's terminal(1). Each stream is used either for input or for output, but typically not for both. A stream is either "text", for character and term I/O, or "binary", for byte I/O. At any one time there is a "current input" stream and a "current output" stream. Input and output predicates fall into two categories: 1. those that use the current input or output stream; 2. those that take an explicit stream argument; Initially, the current input and output streams both refer to the user's terminal. Each input and output built-in predicate refers implicitly or explicitly to a stream. The predicates that perform byte, character and term I/O operations come in pairs such that (A) refers to the current stream, and (B) specifies a stream. PREDICATE_NAME/N (A) PREDICATE_NAME/N+1 (B) ---------- Footnotes ---------- (1) At the C level, you can define more general streams, e.g. referring to pipes or to encrypted files.  File: sicstus.info, Node: ref-iou-str-not, Next: ref-iou-str-sca, Up: ref-iou-str 4.6.2.1 Programming Note ........................ Deciding which version to use involves a trade-off between speed and readability of code: in general, version (B), which specifies a stream, runs slower than (A). So it may be desirable to write code that changes the current stream and uses version (A). However, the use of (B) avoids the use of global variables and results in more readable programs.  File: sicstus.info, Node: ref-iou-str-sca, Prev: ref-iou-str-not, Up: ref-iou-str 4.6.2.2 Stream Categories ......................... SICStus Prolog streams are divided into two categories, those opened by `see/1' or `tell/1' and those opened by `open/[3,4]'. A stream in the former group is referred to by its "file specification", while a stream in the latter case is referred to by its "stream object" (see the figure "Categorization of Stream Handling Predicates"). For further information about file specifications, see *note ref-fdi::. Stream objects are discussed in *note ref-iou-sfh-sob::. Reading the state of open streams is discussed in *note ref-iou-sos::. Each operating system permits a different number of streams to be open.  File: sicstus.info, Node: ref-iou-tin, Next: ref-iou-tou, Prev: ref-iou-str, Up: ref-iou 4.6.3 Term Input ---------------- * Menu: * ref-iou-tin-trm:: Reading Terms: The "Read" Predicates * ref-iou-tin-cpr:: Changing the Prompt Term input operations include: * reading a term and * changing the prompt that appears while reading.  File: sicstus.info, Node: ref-iou-tin-trm, Next: ref-iou-tin-cpr, Up: ref-iou-tin 4.6.3.1 Reading Terms: The "Read" Predicates ............................................ The "Read" predicates are * `read(-TERM)' * `read(+STREAM, -TERM)' * `read_term(-TERM, +OPTIONS)' * `read_term(+STREAM, -TERM, +OPTIONS)' `read_term/[2,3]' offers many options to return extra information about the term. When Prolog reads a term from the current input stream the following conditions must hold: * The term must be followed by a full-stop. See *note ref-syn-syn-ove::. The full-stop is removed from the input stream but is not a part of the term that is read. `read/[1,2]' does not terminate until the full-stop is encountered. Thus, if you type at top-level | ?- read(X) you will keep getting prompts (first `|: ', and five spaces thereafter) every time you type , but nothing else will happen, whatever you type, until you type a full-stop. * The term is read with respect to current operator declarations. See *note ref-syn-ops:: for a discussion of operators. * When a syntax error is encountered, an error message is printed and then the "read" predicate tries again, starting immediately after the full-stop that terminated the erroneous `term'. That is, it does not fail on a syntax error, but perseveres until it eventually manages to read a term. This behavior can be changed with `prolog_flag/3' or using `read_term/[2,3]'. * If the end of the current input stream has been reached, `read(X)' will cause X to be unified with the atom `end_of_file'.  File: sicstus.info, Node: ref-iou-tin-cpr, Prev: ref-iou-tin-trm, Up: ref-iou-tin 4.6.3.2 Changing the Prompt ........................... To query or change the sequence of characters (prompt) that indicates that the system is waiting for user input, call `prompt/2'. This predicate affects only the prompt given when a user's program is trying to read from the terminal (for example, by calling `read/1' or `get_code/1'). Note also that the prompt is reset to the default `|: ' on return to the top-level.  File: sicstus.info, Node: ref-iou-tou, Next: ref-iou-cin, Prev: ref-iou-tin, Up: ref-iou 4.6.4 Term Output ----------------- * Menu: * ref-iou-tou-wrt:: Writing Terms: the "Write" Predicates * ref-iou-tou-cha:: Common Characteristics * ref-iou-tou-dis:: Distinctions Among the "write" Predicates * ref-iou-tou-dsp:: Displaying Terms * ref-iou-tou-por:: Using the Portray Hook * ref-iou-tou-pcl:: Portraying a Clause Term output operations include: * writing to a stream (various "write" Predicates) * displaying, usually on the user's terminal (`display/1') * changing the effects of `print/[1,2]' (`user:portray/1') * writing a clause as `listing/[0,1]' does, except original variable names are not retained (`portray_clause/[1,2]')  File: sicstus.info, Node: ref-iou-tou-wrt, Next: ref-iou-tou-cha, Up: ref-iou-tou 4.6.4.1 Writing Terms: the "Write" Predicates ............................................. * `write(+STREAM, +TERM)' * `write(+TERM)' * `writeq(+STREAM, +TERM)' * `writeq(+TERM)' * `write_canonical(+TERM)' * `write_canonical(+STREAM, +TERM)' * `write_term(+STREAM, +TERM, +OPTIONS)' * `write_term(+TERM, +OPTIONS)' `write_term/[2,3]' is a generalization of the others and provides a number of options.  File: sicstus.info, Node: ref-iou-tou-cha, Next: ref-iou-tou-dis, Prev: ref-iou-tou-wrt, Up: ref-iou-tou 4.6.4.2 Common Characteristics .............................. The output of the "Write" predicates is not terminated by a full-stop; therefore, if you want the term to be acceptable as input to `read/[1,2]', you must send the terminating full-stop to the output stream yourself. For example, | ?- write(a), put_code(0'.), nl. If TERM is uninstantiated, it is written as an anonymous variable (an underscore followed by a non-negative integer). `write_canonical/[1,2]' is provided so that TERM, if written to a file, can be read back by `read/[1,2]' regardless whether there are special characters in TERM or prevailing operator declarations.  File: sicstus.info, Node: ref-iou-tou-dis, Next: ref-iou-tou-dsp, Prev: ref-iou-tou-cha, Up: ref-iou-tou 4.6.4.3 Distinctions Among the "write" Predicates ................................................. * For `write' and `writeq', the term is written with respect to current operator declarations (See *note ref-syn-ops:: for a discussion of operators). `write_canonical(TERM)' writes TERM to the current or specified output stream in standard syntax (see *note ref-syn:: on Prolog syntax), and quotes atoms and functors to make them acceptable as input to `read/[1,2]'. That is, operator declarations are not used and compound terms are therefore always written in the form: PREDICATE_NAME(ARG1, ..., ARGN) * Atoms output by `write/[1,2]' cannot in general be read back using `read/[1,2]'. For example, | ?- write('a b'). a b If you want to be sure that the atom can be read back by `read/[1,2]', you should use `writeq/[1,2]', or `write_canonical/[1,2]', which put quotes around atoms when necessary, or use `write_term/[2,3]' with the `quoted' option set to `yes'. Note also that the printing of quoted atoms is sensitive to character escaping (*note ref-syn-ces::). * `write/[1,2]' and `writeq/[1,2]' treat terms of the form `'$VAR'(N)' specially: they write `A' if N=0, `B' if N=1, ...`Z' if N=25, `A1' if N=26, etc. Terms of this form are generated by `numbervars/3' (see *note ref-lte-anv::). Terms of the form `'$VAR'(X)', where X is not a number are written as unquoted terms. For example, | ?- writeq(a('$VAR'(0),'$VAR'('Test'))). a(A,Test) `write_canonical/1' does _not_ treat terms of the form `'$VAR'(N)' specially. It writes square bracket lists using `./2' and `[]' (that is, `[a,b]' is written as `.(a,.(b,[]))').  File: sicstus.info, Node: ref-iou-tou-dsp, Next: ref-iou-tou-por, Prev: ref-iou-tou-dis, Up: ref-iou-tou 4.6.4.4 Displaying Terms ........................ Like `write_canonical/[1,2]', `display/1' ignores operator declarations and shows all compound terms in standard prefix form. For example, the command | ?- display(a+b). produces the following: +(a,b) Calling `display/1' is a good way of finding out how Prolog parses a term with several operators. Unlike `write_canonical/[1,2]', `display/1' does not put quotes around atoms and functors.  File: sicstus.info, Node: ref-iou-tou-por, Next: ref-iou-tou-pcl, Prev: ref-iou-tou-dsp, Up: ref-iou-tou 4.6.4.5 Using the Portray Hook .............................. By default, the effect of `print/[1,2]' is the same as that of `write/[1,2]', but you can change its effect by providing clauses for the hook predicate `user:portray/1'. If X is a variable, it is printed using `write(X)'. Otherwise the user-definable procedure `user:portray(X)' is called. If this succeeds, it is assumed that X has been printed and `print/[1,2]' exits (succeeds). If the call to `user:portray/1' fails, and if X is a compound term, `write/[1,2]' is used to write the principal functor of X and `print/[1,2]' is called recursively on its arguments. If X is atomic, it is written using `write/[1,2]'. When `print/[1,2]' has to print a list, say `[X1,X2,...,Xn]', it passes the whole list to `user:portray/1'. As usual, if `user:portray/1' succeeds, it is assumed to have printed the entire list, and `print/[1,2]' does nothing further with this term. Otherwise `print/[1,2]' writes the list using bracket notation, calling `print/[1,2]' on each element of the list in turn. Since `[X1,X2,...,Xn]' is simply a different way of writing `.(X1,[X2,...,Xn])', one might expect `print/[1,2]' to be called recursively on the two arguments `X1' and `[X2,...,Xn]', giving `user:portray/1' a second chance at `[X2,...,Xn]'. This does _not_ happen; lists are a special case in which `print/[1,2]' is called separately for each of `X1,X2,...Xn'.  File: sicstus.info, Node: ref-iou-tou-pcl, Prev: ref-iou-tou-por, Up: ref-iou-tou 4.6.4.6 Portraying a Clause ........................... If you want to print a clause, `portray_clause/[1,2]' is almost certainly the command you want. None of the other term output commands puts a full-stop after the written term. If you are writing a file of facts to be loaded by `compile/1', use `portray_clause/[1,2]', which attempts to ensure that the clauses it writes out can be read in again as clauses. The output format used by `portray_clause/[1,2]' and `listing/[0,1]' has been carefully designed to be clear. We recommend that you use a similar style. In particular, never put a semicolon (disjunction symbol) at the end of a line in Prolog.  File: sicstus.info, Node: ref-iou-cin, Next: ref-iou-cou, Prev: ref-iou-tou, Up: ref-iou 4.6.5 Byte and Character Input ------------------------------ * Menu: * ref-iou-cin-ove:: Overview * ref-iou-cin-cha:: Reading Bytes and Characters * ref-iou-cin-pee:: Peeking * ref-iou-cin-ski:: Skipping * ref-iou-cin-elf:: Finding the End of Line and End of File  File: sicstus.info, Node: ref-iou-cin-ove, Next: ref-iou-cin-cha, Up: ref-iou-cin 4.6.5.1 Overview ................ The operations in this category are: * reading ("get" predicates), * peeking ("peek" predicates), * skipping ("skip" predicates), * checking for end of line or end of file ("at_end" predicates).  File: sicstus.info, Node: ref-iou-cin-cha, Next: ref-iou-cin-pee, Prev: ref-iou-cin-ove, Up: ref-iou-cin 4.6.5.2 Reading Bytes and Characters .................................... * `get_byte([STREAM,] N)' unifies N with the next consumed byte from the current or given input stream, which must be binary. * `get_code([STREAM,] N)' unifies N with the next consumed character code from the current or given input stream, which must be text. * `get_char([STREAM,] A)' unifies A with the next consumed character atom from the current or given input stream, which must be text.  File: sicstus.info, Node: ref-iou-cin-pee, Next: ref-iou-cin-ski, Prev: ref-iou-cin-cha, Up: ref-iou-cin 4.6.5.3 Peeking ............... Peeking at the next character without consuming it is useful when the interpretation of "this character" depends on what the next one is. * `peek_byte([STREAM,] N)' unifies N with the next unconsumed byte from the current or given input stream, which must be binary. * `peek_code([STREAM,] N)' unifies N with the next unconsumed character code from the current or given input stream, which must be text. * `peek_char([STREAM,] A)' unifies A with the next unconsumed character atom from the current or given input stream, which must be text.  File: sicstus.info, Node: ref-iou-cin-ski, Next: ref-iou-cin-elf, Prev: ref-iou-cin-pee, Up: ref-iou-cin 4.6.5.4 Skipping ................ There are two ways of skipping over characters in the current or given input stream: skip to a given character, or skip to the end of a line. * `skip_byte([STREAM,] N)' skips over bytes through the first occurrence of N from the current or given input stream, which must be binary. * `skip_code([STREAM,] N)' skips over character codes through the first occurrence of N from the current or given input stream, which must be text. * `skip_char([STREAM,] A)' skips over character atoms through the first occurrence of A from the current or given input stream, which must be text. * `skip_line' or `skip_line(STREAM)' skips to the end of line of the current or given input stream. Use of this predicate helps portability of code since it avoids dependence on any particular character code(s) being returned at the end of a line.  File: sicstus.info, Node: ref-iou-cin-elf, Prev: ref-iou-cin-ski, Up: ref-iou-cin 4.6.5.5 Finding the End of Line and End of File ............................................... To test whether the end of a line on the end of the file has been reached on the current or given input stream, use `at_end_of_line/[0,1]' or `at_end_of_stream/[0,1]'. Note that these predicates never block waiting for input. This means that they may fail even if the stream or line is in fact at its end. An alternative that will never guess wrong is to use `peek_code/[1,2]' or `peek_byte/[1,2]'.  File: sicstus.info, Node: ref-iou-cou, Next: ref-iou-sfh, Prev: ref-iou-cin, Up: ref-iou 4.6.6 Byte and Character Output ------------------------------- * Menu: * ref-iou-cou-cha:: Writing Bytes and Characters * ref-iou-cou-nln:: New Line * ref-iou-cou-fou:: Formatted Output The byte and character output operations are: * writing (putting) bytes and characters * creating newlines and tabs * flushing buffers * formatting output.  File: sicstus.info, Node: ref-iou-cou-cha, Next: ref-iou-cou-nln, Up: ref-iou-cou 4.6.6.1 Writing Bytes and Characters .................................... * `put_byte([STREAM,] N)' writes the byte N to the current or given output stream, which must be binary. * `put_code([STREAM,] N)' writes the character code N to the current or given output stream, which must be text. * `put_char([STREAM,] A)' writes the character atom A to the current or given output stream, which must be text. The byte or character is not necessarily printed immediately; they may be flushed if the buffer is full. See *note ref-iou-sfh-flu::.  File: sicstus.info, Node: ref-iou-cou-nln, Next: ref-iou-cou-fou, Prev: ref-iou-cou-cha, Up: ref-iou-cou 4.6.6.2 New Line ................ `nl' or `nl(STREAM)' terminates the record on the current or given output stream. A linefeed character is printed.  File: sicstus.info, Node: ref-iou-cou-fou, Prev: ref-iou-cou-nln, Up: ref-iou-cou 4.6.6.3 Formatted Output ........................ `format([STREAM,] CONTROL, ARGUMENTS)' interprets the ARGUMENTS according to the CONTROL string and prints the result on the current or given output stream. Alternatively, an output stream can be specified in an initial argument. This predicate is used to produce formatted output, like the following example. | ?- toc(1.5). Table of Contents i ************************ NICE TABLE ************************* * * * Right aligned Centered Left aligned * * 123 45 678 * * 1 2345 6789 * ************************************************************* For details, including the code to produce this example, see the example program in the reference page for `format/[2,3]'.  File: sicstus.info, Node: ref-iou-sfh, Next: ref-iou-sos, Prev: ref-iou-cou, Up: ref-iou 4.6.7 Stream and File Handling ------------------------------ * Menu: * ref-iou-sfh-sob:: Stream Objects * ref-iou-sfh-est:: Exceptions Related to Streams * ref-iou-sfh-sem:: Suppressing Error Messages * ref-iou-sfh-opn:: Opening a Stream * ref-iou-sfh-enc:: Text Stream Encodings * ref-iou-sfh-cis:: Finding the Current Input Stream * ref-iou-sfh-cos:: Finding the Current Output Stream * ref-iou-sfh-bos:: Finding Out About Open Streams * ref-iou-sfh-cst:: Closing a Stream * ref-iou-sfh-flu:: Flushing Output The operations implemented are opening, closing, querying status, flushing, error handling, setting. The predicates in the "see" and "tell" families are supplied for compatibility with other Prologs. They take either file specifications or stream objects as arguments (see *note mpg-ref::) and they specify an alternative, less powerful, mechanism for dealing with files and streams than the similar predicates (`open/[3,4]', etc.), which take stream objects (see the figure "Categorization of Stream Handling Predicates").  File: sicstus.info, Node: ref-iou-sfh-sob, Next: ref-iou-sfh-est, Up: ref-iou-sfh 4.6.7.1 Stream Objects ...................... Each input and output stream is represented by a unique Prolog term, a "stream object". In general, this term is of the form `user' Stands for the standard input or output stream, depending on context. `'$stream'(X)' A stream connected to some file. X is an integer. ATOM A stream alias. Aliases can be associated with streams using the `alias(ATOM)' option of `open/4'. There are also three predefined aliases: `user_input' An alias initially referring to the UNIX `stdin' stream. The alias can be changed with `prolog_flag/3' and accessed by the C variable `SP_stdin'. `user_output' An alias initially referring to the UNIX `stdout' stream. The alias can be changed with `prolog_flag/3' and accessed by the C variable `SP_stdout'. `user_error' An alias initially referring to the UNIX `stderr' stream. The alias can be changed with `prolog_flag/3' and accessed by the C variable `SP_stderr'. This stream is used by the Prolog top-level and debugger, and for all unsolicited messages by built-in predicates. Stream objects are created by the predicate `open/[3,4]' *note ref-iou-sfh-opn:: and passed as arguments to those predicates that need them. Representation for stream objects to be used in C code is different. Use `stream_code/2' to convert from one to the other when appropriate.  File: sicstus.info, Node: ref-iou-sfh-est, Next: ref-iou-sfh-sem, Prev: ref-iou-sfh-sob, Up: ref-iou-sfh 4.6.7.2 Exceptions Related to Streams ..................................... All predicates that take a stream argument will raise the following exceptions: `instantiation_error' STREAM argument is not ground `type_error' STREAM is not an input (or output) stream type. `existence_error' STREAM is syntactically valid but does not name an open stream. `permission_error' STREAM names an open stream but the stream is not open for the required operation, or has reached the end of stream on input, or is binary when text is required, or vice versa. The reference page for each stream predicate will simply refer to these as "Stream errors" and will go on to detail other exceptions that may be raised for a particular predicate.  File: sicstus.info, Node: ref-iou-sfh-sem, Next: ref-iou-sfh-opn, Prev: ref-iou-sfh-est, Up: ref-iou-sfh 4.6.7.3 Suppressing Error Messages .................................. If the `fileerrors' flag is set to `off', the built-in predicates that open files simply fail, instead of raising an exception if the specified file cannot be opened.  File: sicstus.info, Node: ref-iou-sfh-opn, Next: ref-iou-sfh-enc, Prev: ref-iou-sfh-sem, Up: ref-iou-sfh 4.6.7.4 Opening a Stream ........................ Before I/O operations can take place on a stream, the stream must be opened, and it must be set to be current input or current output. As illustrated in the figure "Categorization of Stream Handling Predicates", the operations of opening and setting are separate with respect to the stream predicates, and combined in the File Specification Predicates. * `open(FILE, MODE, STREAM)' attempts to open the file FILE in the mode specified (read,write or append). If the `open/3' request is successful, a stream object, which can be subsequently used for input or output to the given file, is unified with STREAM. The `read' mode is used for input. The `write' and `append' modes are used for output. The `write' option causes a new file to be created for output. If the file already exists, it is set to empty and its previous contents are lost. The `append' option opens an already-existing file and adds output to the end of it. The `append' option will create the file if it does not already exist. Options can be specified by calling `open/4'. * `set_input(STREAM)' makes STREAM the current input stream. Subsequent input predicates such as `read/1' and `get_code/1' will henceforth use this stream. * `set_output(STREAM)' makes STREAM the current output stream. Subsequent output predicates such as `write/1' and `put_code/1' will henceforth use this stream. Opening a stream and making it current are combined in `see' and `tell': * `see(S)' makes file S the current input stream. If S is an atom, it is taken to be a file specification, and - if there is an open input stream associated with the filename, and that stream was opened by `see/1', it is made the current input stream; - Otherwise, the specified file is opened for input and made the current input stream. If it is not possible to open the file, and the `fileerrors' flag is on (as it is by default), `see/1' raises an error exception. Otherwise, `see/1' merely fails. * `tell(S)' makes S the current output stream. - If there is an open output stream currently associated with the filename, and that stream was opened by `tell/1', it is made the current output stream; - Otherwise, the specified file is opened for output and made the current output stream. If the file does not exist, it is created. If it is not possible to open the file (because of protections, for example), and the `fileerrors' flag is on (which it is by default), `tell/1' raises an error exception. Otherwise, `tell/1' merely fails. It is important to remember to close streams when you have finished with them. Use `seen/0' or `close/1' for input files, and `told/0' or `close/1' for output files. * `open_null_stream(STREAM)' opens a text output stream that is not connected to any file and unifies its stream object with STREAM. Characters or terms that are sent to this stream are thrown away. This predicate is useful because various pieces of local state are kept for null streams: the predicates `character_count/2', `line_count/2' and `line_position/2' can be used on these streams (see *note ref-iou-sos::).  File: sicstus.info, Node: ref-iou-sfh-enc, Next: ref-iou-sfh-cis, Prev: ref-iou-sfh-opn, Up: ref-iou-sfh 4.6.7.5 Text Stream Encodings ............................. SICStus Prolog supports character codes up to 31 bits wide where the codes are interpreted as for Unicode for the common subset. When a character code (a "code point" in Unicode terminology) is read or written to a stream, it must be encoded into a byte sequence. The method by which each character code is encoded to or decoded from a byte sequence is called "character encoding". The following character encodings are currently supported by SICStus Prolog. `ANSI_X3.4-1968' The 7-bit subset of Unicode, commonly referred to as ASCII. `ISO-8859-1' The 8-bit subset of Unicode, commonly referred to as Latin 1. `ISO-8859-2' A variant of ISO-8859-1, commonly referred to as Latin 2. `ISO-8859-15' A variant of ISO-8859-1, commonly referred to as Latin 9. `windows 1252' The Microsoft Windows code page 1252. `UTF-8' `UTF-16' `UTF-16LE' `UTF-16BE' `UTF-32' `UTF-32LE' `UTF-32BE' The suffixes `LE' and `BE' denote respectively little endian and big endian. These encodings can be auto-detected if a Unicode signature is present in a file opened for read. A Unicode signature is also known as a Byte order mark (BOM). In addition, it is possible to use all alternative names defined by the IANA registry `http://www.iana.org/assignments/character-sets'. All encodings in the table above, except the UTF-XXX encodings, supports the `reposition(true)' option to `open/4' (*note mpg-ref-open::). The encoding to use can be specified when using `open/4' and similar predicates using the option `encoding/1'. When opening a file for input, the encoding can often be determined automatically. The default is `ISO-8859-1' if no encoding is specified and no encoding can be detected from the file contents. The encoding used by a text stream can be queried using `stream_property/2'. *Note mpg-ref-open:: for details on how character encoding is auto-detected when opening text files.  File: sicstus.info, Node: ref-iou-sfh-cis, Next: ref-iou-sfh-cos, Prev: ref-iou-sfh-enc, Up: ref-iou-sfh 4.6.7.6 Finding the Current Input Stream ........................................ * `current_input(STREAM)' unifies STREAM with the current input stream. * If the current input stream is `user_input', `seeing(S)' unifies S with `user'. Otherwise, if the current input stream was opened by `see(F)', `seeing(S)' unifies S with F. Otherwise, if the current input stream was opened by `open/[3,4]', `seeing(S)' unifies S with the corresponding stream object. `seeing/1' can be used to verify that a section of code leaves the current input stream unchanged as follows: /* nonvar(FileNameOrStream), */ see(FileNameOrStream), ... seeing(FileNameOrStream) _WARNING_: The sequence seeing(File), ... set_input(File), will signal an error if the current input stream was opened by `see/1'. The only sequences that are guaranteed to succeed are seeing(FileOrStream), ... see(FileOrStream) and current_input(Stream), ... set_input(Stream)  File: sicstus.info, Node: ref-iou-sfh-cos, Next: ref-iou-sfh-bos, Prev: ref-iou-sfh-cis, Up: ref-iou-sfh 4.6.7.7 Finding the Current Output Stream ......................................... * `current_output(STREAM)' unifies STREAM with the current output stream. * If the current output stream is `user_output', `telling(S)' unifies S with `user'. Otherwise, if the current output stream was opened by `tell(F)', `telling(S)' unifies S with F. Otherwise, if the current output stream was opened by `open/[3,4]', `telling(S)' unifies S with the corresponding stream object. `telling/1' can be used to verify that a section of code leaves the current output stream unchanged as follows: /* nonvar(FileNameOrStream), */ tell(FileNameOrStream), ... telling(FileNameOrStream) _WARNING_: The sequence telling(File), ... set_output(File), will signal an error if the current output stream was opened by `tell/1'. The only sequences that are guaranteed to succeed are telling(FileOrStream), ... tell(FileOrStream) and current_output(Stream), ... set_output(Stream)  File: sicstus.info, Node: ref-iou-sfh-bos, Next: ref-iou-sfh-cst, Prev: ref-iou-sfh-cos, Up: ref-iou-sfh 4.6.7.8 Finding Out About Open Streams ...................................... `current_stream(FILE, MODE, STREAM)' succeeds if STREAM is a stream that is currently open on file FILE in mode MODE, where MODE is either `read', `write', or `append'. None of the arguments need be initially instantiated. This predicate is nondeterminate and can be used to backtrack through all open streams. `current_stream/3' ignores certain pre-defined streams, including the initial values of the special streams for the standard input, output, and error channels. `stream_property(STREAM, PROPERTY)' succeeds if STREAM is a currently open stream with property PROPERTY. Pre-defined streams, like the three standard channels, are _not_ ignored.  File: sicstus.info, Node: ref-iou-sfh-cst, Next: ref-iou-sfh-flu, Prev: ref-iou-sfh-bos, Up: ref-iou-sfh 4.6.7.9 Closing a Stream ........................ * `close(X)' closes the stream corresponding to X, where X should be a stream object created by `open/[3,4]', or a file specification passed to `see/1' or `tell/1'. In the example: see(foo), ... close(foo) `foo' will be closed. However, in the example: open(foo, read, S), ... close(foo) an exception will be raised and `foo' will not be closed. * `told/0' closes the current output stream. The current output stream is then set to be `user_output'. * `seen/0' closes the current input stream. The current input stream is then set to be `user_input'.  File: sicstus.info, Node: ref-iou-sfh-flu, Prev: ref-iou-sfh-cst, Up: ref-iou-sfh 4.6.7.10 Flushing Output ........................ Output to a stream is not necessarily sent immediately; it is buffered. The predicate `flush_output/1' flushes the output buffer for the specified stream and thus ensures that everything that has been written to the stream is actually sent at that point. * `flush_output(STREAM)' sends all data in the output buffer to stream STREAM.  File: sicstus.info, Node: ref-iou-sos, Next: ref-iou-raf, Prev: ref-iou-sfh, Up: ref-iou 4.6.8 Reading the State of Opened Streams ----------------------------------------- * Menu: * ref-iou-sos-spt:: Stream Position Information for Terminal I/O Byte, character, line count and line position for a specified stream are obtained as follows: * `byte_count(STREAM, N)' unifies N with the total number of bytes either read or written on the open binary stream STREAM. * `character_count(STREAM, N)' unifies N with the total number of characters either read or written on the open text stream STREAM. * `line_count(STREAM, N)' unifies N with the total number of lines either read or written on the open text stream STREAM. A freshly opened text stream has a line count of 0, i.e. this predicate counts the number of newlines seen. * `line_position(STREAM, N)' unifies N with the total number of characters either read or written on the current line of the open text stream STREAM. A fresh line has a line position of 0, i.e. this predicate counts the length of the current line.  File: sicstus.info, Node: ref-iou-sos-spt, Up: ref-iou-sos 4.6.8.1 Stream Position Information for Terminal I/O .................................................... Input from Prolog streams that have opened the user's terminal for reading is echoed back as output to the same terminal. This is interleaved with output from other Prolog streams that have opened the user's terminal for writing. Therefore, all streams connected to the user's terminal share the same set of position counts and thus return the same values for each of the predicates `character_count/2', `line_count/2' and `line_position/2'.  File: sicstus.info, Node: ref-iou-raf, Next: ref-iou-sum, Prev: ref-iou-sos, Up: ref-iou 4.6.9 Random Access to Files ---------------------------- There are two methods of finding and setting the stream position, "stream positioning" and "seeking". The current position of the read/write pointer in a specified stream can be obtained by using `stream_position/2' or `stream_property/2'. It may be changed by using `set_stream_position/2'. Alternatively, `seek/4' may be used. Seeking is more general, and stream positioning is more portable. The differences between them are: * `stream_position/2' is similar to `seek/4' with OFFSET = 0, and METHOD = `current'. * Where `set_stream_position/2' asks for stream position objects, `seek/4' uses integer expressions to represent the position or offset. Stream position objects are obtained by calling `stream_position/2', and are discussed in the reference page.  File: sicstus.info, Node: ref-iou-sum, Prev: ref-iou-raf, Up: ref-iou 4.6.10 Summary of Predicates and Functions ------------------------------------------ Reference pages for the following provide further detail on the material in this section. `at_end_of_line' `at_end_of_line(+S)' testing whether at end of line on input stream S `at_end_of_stream "ISO"' `at_end_of_stream(+S) "ISO"' testing whether end of file is reached for the input stream S `flush_output "ISO"' `flush_output(+S) "ISO"' flush the output buffer for stream S `get_byte(-C) "ISO"' `get_byte(+S,-C) "ISO"' C is the next byte on binary input stream S `get_char(-C) "ISO"' `get_char(+S,-C) "ISO"' C is the next character atom on text input stream S `get_code(-C) "ISO"' `get_code(+S,-C) "ISO"' C is the next character code on text input stream S `nl "ISO"' `nl(+S) "ISO"' send a newline to stream S `peek_byte(+C) "ISO"' `peek_byte(+S,+C) "ISO"' looks ahead for next input byte on the binary input stream S `peek_char(+C) "ISO"' `peek_char(+S,+C) "ISO"' looks ahead for next input character atom on the text input stream S `peek_code(+C) "ISO"' `peek_code(+S,+C) "ISO"' looks ahead for next input character code on the text input stream S `put_byte(+C) "ISO"' `put_byte(+S,+C) "ISO"' write byte C to binary stream S `put_char(+C) "ISO"' `put_char(+S,+C) "ISO"' write character atom C to text stream S `put_code(+C) "ISO"' `put_code(+S,+C) "ISO"' write character code C to text stream S `skip_byte(+C)' `skip_byte(+S,+C)' skip input on binary stream S until after byte C `skip_char(+C)' `skip_char(+S,+C)' skip input on text stream S until after char C `skip_code(+C)' `skip_code(+S,+C)' skip input on text stream S until after code C `skip_line' `skip_line(+S)' skip the rest input characters of the current line (record) on the input stream S `byte_count(+S,-N)' N is the number of bytes read/written on binary stream S `character_count(+S,-N)' N is the number of characters read/written on text stream S `close(+F) "ISO"' `close(+F,+O) "ISO"' close file or stream F with options O `current_input(-S) "ISO"' S is the current input stream `current_output(-S) "ISO"' S is the current output stream `current_stream(?F,?M,?S)' S is a stream open on file F in mode M `line_count(+S,-N)' N is the number of lines read/written on text stream S `line_position(+S,-N)' N is the number of characters read/written on the current line of text stream S `open(+F,+M,-S) "ISO"' `open(+F,+M,-S,+O) "ISO"' file F is opened in mode M, options O, returning stream S `open_null_stream(+S)' new output to text stream S goes nowhere `prompt(-O,+N)' queries or changes the prompt string of the current input stream `see(+F)' make file F the current input stream `seeing(-N)' the current input stream is named N `seek(+S,+O,+M,+N)' seek to an arbitrary byte position on the stream S `seen' close the current input stream `set_input(+S) "ISO"' select S as the current input stream `set_output(+S) "ISO"' select S as the current output stream `set_stream_position(+S,+P) "ISO"' P is the new position of stream S `stream_code(?S,?C)' Converts between Prolog and C representations of a stream `stream_position(+S,-P)' P is the current position of stream S `stream_position_data(?FIELD,?POSITION,?DATA)' The FIELD field of the stream position term POSITION is DATA. `stream_property(?STREAM, ?PROPERTY)) "ISO"' Stream STREAM has property PROPERTY. `tell(+F)' make file F the current output stream `telling(-N)' to file N `told' close the current output stream `char_conversion(+INCHAR, +OUTCHAR) "ISO"' The mapping of INCHAR to OUTCHAR is added to the character-conversion mapping. `current_char_conversion(?INCHAR, ?OUTCHAR) "ISO"' INCHAR is mapped to OUTCHAR in the current character-conversion mapping. `current_op(?P,?T,?A) "ISO"' atom A is an operator of type T with precedence P `display(+T)' write term T to the user output stream in prefix notation `format(+C,:A)' `format(+S,+C,:A)' write arguments A on stream S according to control string C `op(+P,+T,+A) "ISO"' make atom A an operator of type T with precedence P `user:portray(+T) "hook"' tell `print/[1,2]' and `write_term/[2,3]' what to do `portray_clause(+C)' `portray_clause(+S,+C)' write clause C to the stream S `print(+T) "hookable"' `print(+S,+T) "hookable"' display the term T on stream S using `user:portray/1' or `write/2' `read(-T) "ISO"' `read(+S,-T) "ISO"' read term T from stream S `read_term(-T,+O) "ISO"' `read_term(+S,-T,+O) "ISO"' read T from stream S according to options O `write(+T) "ISO"' `write(+S,+T) "ISO"' write term T on stream S `write_canonical(+T) "ISO"' `write_canonical(+S,+T) "ISO"' write term T on stream S so that it can be read back by `read/[1,2]' `writeq(+T) "ISO"' `writeq(+S,+T) "ISO"' write term T on stream S, quoting atoms where necessary `write_term(+T,+O) "ISO,hookable"' `write_term(+S,+T,+O) "ISO,hookable"' writes T to S according to options O  File: sicstus.info, Node: ref-ari, Next: ref-lte, Prev: ref-iou, Up: Prolog Intro 4.7 Arithmetic ============== * Menu: * ref-ari-ove:: Overview * ref-ari-eae:: Evaluating Arithmetic Expressions * ref-ari-exc:: Exceptions Related to Arithmetic * ref-ari-acm:: Arithmetic Comparison * ref-ari-aex:: Arithmetic Expressions * ref-ari-sum:: Predicate Summary  File: sicstus.info, Node: ref-ari-ove, Next: ref-ari-eae, Up: ref-ari 4.7.1 Overview -------------- In Prolog, arithmetic is performed by certain built-in predicates, which take arithmetic expressions as their arguments and evaluate them. Arithmetic expressions can evaluate to integers or floating-point numbers (floats). The range of integers is `[-2^2147483616, 2^2147483616)'. Thus for all practical purposes, the range of integers can be considered infinite. The range of floats is the one provided by the C `double' type, typically `[4.9e-324, 1.8e+308]' (plus or minus). In case of overflow or division by zero, an evaluation error exception will be raised. Floats are represented by 64 bits and they conform to the IEEE 754 standard. The arithmetic operations of evaluation and comparison are implemented in the predicates described in *note ref-ari-eae:: and *note ref-ari-acm::. All of them take arguments of the type "Expr", which is described in detail in *note ref-ari-aex::.  File: sicstus.info, Node: ref-ari-eae, Next: ref-ari-exc, Prev: ref-ari-ove, Up: ref-ari 4.7.2 Evaluating Arithmetic Expressions --------------------------------------- The most common way to do arithmetic calculations in Prolog is to use the built-in predicate `is/2'. `-TERM is +EXPR' TERM is the value of arithmetic expression EXPR. TERM must not contain any uninstantiated variables. Do not confuse `is/2' with `=/2'.  File: sicstus.info, Node: ref-ari-exc, Next: ref-ari-acm, Prev: ref-ari-eae, Up: ref-ari 4.7.3 Exceptions Related to Arithmetic -------------------------------------- All predicates that evaluate arithmetic expressions will raise the following exceptions: `instantiation_error' `type_error' Atom given as expression, or float given where integer required. `evaluation_error' Attempting to divide by zero, or undefined function, or function undefined for the given argument. `representation_error' Integer value too large to be represented. The reference page for such predicates will simply refer to these as "Arithmetic errors" and will go on to detail other exceptions that may be raised for a particular predicate.  File: sicstus.info, Node: ref-ari-acm, Next: ref-ari-aex, Prev: ref-ari-exc, Up: ref-ari 4.7.4 Arithmetic Comparison --------------------------- Each of the following predicates evaluates each of its arguments as an arithmetic expression, then compares the results. If one argument evaluates to an integer and the other to a float, the integer is coerced to a float before the comparison is made. Note that two floating-point numbers are equal if and only if they have the same bit pattern. Because of rounding error, it is not normally useful to compare two floats for equality. `EXPR1 `=:=' EXPR2' succeeds if the results of evaluating terms EXPR1 and EXPR2 as arithmetic expressions are equal `EXPR1 `=\=' EXPR2' succeeds if the results of evaluating terms EXPR1 and EXPR2 as arithmetic expressions are not equal `EXPR1 `<' EXPR2' succeeds if the result of evaluating EXPR1 as an arithmetic expression is less than the result of evaluating EXPR2 as an arithmetic expression. `EXPR1 `>' EXPR2' succeeds if the result of evaluating EXPR1 as an arithmetic expression EXPR1 is greater than the result of evaluating EXPR2 as an arithmetic expression. `EXPR1 `=<' EXPR2' succeeds if the result of evaluating EXPR1 as an arithmetic expression is not greater than the result of evaluating EXPR2 as an arithmetic expression. `EXPR1 `>=' EXPR2' succeeds if the result of evaluating EXPR1 as an arithmetic expression is not less than the result of evaluating EXPR2 as an arithmetic expression.  File: sicstus.info, Node: ref-ari-aex, Next: ref-ari-sum, Prev: ref-ari-acm, Up: ref-ari 4.7.5 Arithmetic Expressions ---------------------------- Arithmetic evaluation and testing is performed by predicates that take arithmetic expressions as arguments. An "arithmetic expression" is a term built from numbers, variables, and functors that represent arithmetic functions. These expressions are evaluated to yield an arithmetic result, which may be either an integer or a float; the type is determined by the rules described below. At the time of evaluation, each variable in an arithmetic expression must be bound to a number or another arithmetic expression. If the expression is not sufficiently bound or if it is bound to terms of the wrong type, Prolog raises exceptions of the appropriate type (see *note ref-ere-hex::). Some arithmetic operations can also detect overflows. They also raise exceptions, e.g. division by zero results in a domain error being raised. Only certain functors are permitted in arithmetic expressions. These are listed below, together with a description of their arithmetic meanings. For the rest of the section, X and Y are considered to be arithmetic expressions. Unless stated otherwise, the arguments of an expression may be any numbers and its value is a float if any of its arguments is a float; otherwise, the value is an integer. Any implicit coercions are performed with the `integer/1' and `float/1' functions. All trigonometric and transcendental functions take float arguments and deliver float values. The trigonometric functions take arguments or deliver values in radians. The arithmetic functors are annotated with _[ISO]_, with the same meaning as for the built-in predicates; *note ISO Compliance::. `+(X)' The value is X. `-X' The value is the negative of X. "ISO" `X+Y' The value is the sum of X and Y. "ISO" `X-Y' The value is the difference between X and Y. "ISO" `X*Y' The value is the product of X and Y. "ISO" `X/Y' The value is the _float_ quotient of X and Y. "ISO" `X//Y "ISO"' The value is the _integer_ quotient of X and Y. The result is always truncated towards zero. X and Y have to be integers. `X rem Y "ISO"' The value is the _integer_ remainder after dividing X by Y, i.e. `integer(X)-integer(Y)*(X//Y)'. The sign of a nonzero remainder will thus be the same as that of the dividend. X and Y have to be integers. `X mod Y "ISO"' The value is X modulo Y, i.e. `integer(X)-integer(Y)*floor(X/Y)'. The sign of a nonzero remainder will thus be the same as that of the divisor. X and Y have to be integers. `integer(X)' The value is the closest integer between X and 0, if X is a float; otherwise, X itself. `float_integer_part(X) "ISO"' The same as `float(integer(X))'. X has to be a float. `float_fractional_part(X) "ISO"' The value is the fractional part of X, i.e. `X - float_integer_part(X)'. X has to be a float. `float(X) "ISO"' The value is the float equivalent of X, if X is an integer; otherwise, X itself. `X/\Y "ISO"' The value is the bitwise conjunction of the integers X and Y. X and Y have to be integers. `X\/Y "ISO"' The value is the bitwise disjunction of the integers X and Y. X and Y have to be integers. `X\Y' The value is the bitwise exclusive or of the integers X and Y. `\(X) "ISO"' The value is the bitwise negation of the integer X. X has to be an integer. `X<>Y "ISO"' The value is the integer X shifted right by Y places. X and Y have to be integers. `[X]' A list of just one number X evaluates to X. Since a quoted string is just a list of integers, this allows a quoted character to be used in place of its character code; e.g. `"A"' behaves within arithmetic expressions as the integer 65. `abs(X) "ISO"' The value is the absolute value of X. `sign(X) "ISO"' The value is the sign of X, i.e. -1, if X is negative, 0, if X is zero, and 1, if X is positive, coerced into the same type as X (i.e. the result is an integer, if and only if X is an integer). `gcd(X,Y)' The value is the greatest common divisor of the two integers X and Y. X and Y have to be integers. `min(X,Y)' The value is the lesser value of X and Y. `max(X,Y)' The value is the greater value of X and Y. `msb(X)' The value is the position of the most significant nonzero bit of the integer X, counting bit positions from zero. It is equivalent to, but more efficient than, `integer(log(2,X))'. X must be greater than zero, and X has to be an integer. `round(X) "ISO"' The value is the closest integer to X. If X is exactly half-way between two integers, it is rounded up (i.e. the value is the least integer greater than X). `truncate(X) "ISO"' The value is the closest integer between X and 0. `floor(X) "ISO"' The value is the greatest integer less or equal to X. `ceiling(X) "ISO"' The value is the least integer greater or equal to X. `sin(X) "ISO"' The value is the sine of X. `cos(X) "ISO"' The value is the cosine of X. `tan(X)' The value is the tangent of X. `cot(X)' The value is the cotangent of X. `sinh(X)' The value is the hyperbolic sine of X. `cosh(X)' The value is the hyperbolic cosine of X. `tanh(X)' The value is the hyperbolic tangent of X. `coth(X)' The value is the hyperbolic cotangent of X. `asin(X)' The value is the arc sine of X. `acos(X)' The value is the arc cosine of X. `atan(X) "ISO"' The value is the arc tangent of X. `atan2(X,Y)' The value is the four-quadrant arc tangent of X and Y. `acot(X)' The value is the arc cotangent of X. `acot2(X,Y)' The value is the four-quadrant arc cotangent of X and Y. `asinh(X)' The value is the hyperbolic arc sine of X. `acosh(X)' The value is the hyperbolic arc cosine of X. `atanh(X)' The value is the hyperbolic arc tangent of X. `acoth(X)' The value is the hyperbolic arc cotangent of X. `sqrt(X) "ISO"' The value is the square root of X. `log(X) "ISO"' The value is the natural logarithm of X. `log(BASE,X)' The value is the logarithm of X in the base BASE. `exp(X) "ISO"' The value is the natural exponent of X. `X ** Y "ISO"' `exp(X,Y)' The value is X raised to the power of Y. The following operation is included in order to allow integer arithmetic on character codes. `[X]' Evaluates to X for numeric X. This is relevant because character strings in Prolog are lists of character codes, that is, integers. Thus, for those integers that correspond to character codes, the user can write a string of one character in place of that integer in an arithmetic expression. For example, the expression (A) is equivalent to (B), which in turn becomes (C) in which case X is unified with 2: X is "c" - "a" (A) X is [99] - [97] (B) X is 99 - 97 (C) A cleaner way to do the same thing is X is 0'c - 0'a  File: sicstus.info, Node: ref-ari-sum, Prev: ref-ari-aex, Up: ref-ari 4.7.6 Predicate Summary ----------------------- `-Y is +X "ISO"' Y is the value of arithmetic expression X `+X =:= +Y "ISO"' the results of evaluating terms X and Y as arithmetic expressions are equal. `+X =\= +Y "ISO"' the results of evaluating terms X and Y as arithmetic expressions are not equal. `+X < +Y "ISO"' the result of evaluating X as an arithmetic expression is less than the result of evaluating Y as an arithmetic expression. `+X >= +Y "ISO"' the result of evaluating X as an arithmetic expression is not less than the result of evaluating Y as an arithmetic expression. `+X > +Y "ISO"' the result of evaluating X as an arithmetic expression X is greater than the result of evaluating Y as an arithmetic expression. `+X =< +Y "ISO"' the result of evaluating X as an arithmetic expression is not greater than the result of evaluating Y as an arithmetic expression.  File: sicstus.info, Node: ref-lte, Next: ref-lps, Prev: ref-ari, Up: Prolog Intro 4.8 Looking at Terms ==================== * Menu: * ref-lte-met:: Meta-logical Predicates * ref-lte-act:: Analyzing and Constructing Terms * ref-lte-acl:: Analyzing and Constructing Lists * ref-lte-c2t:: Converting between Constants and Text * ref-lte-atm:: Atom Operations * ref-lte-anv:: Assigning Names to Variables * ref-lte-cpt:: Copying Terms * ref-lte-cte:: Comparing Terms * ref-lte-mut:: Mutable Terms * ref-lte-sum:: Summary of Predicates  File: sicstus.info, Node: ref-lte-met, Next: ref-lte-act, Up: ref-lte 4.8.1 Meta-logical Predicates ----------------------------- * Menu: * ref-lte-met-typ:: Type Checking * ref-lte-met-usu:: Unification "Meta-logical" predicates are those predicates that allow you to examine the current instantiation state of a simple or compound term, or the components of a compound term. This section describes the meta-logical predicates as well as others that deal with terms as such.  File: sicstus.info, Node: ref-lte-met-typ, Next: ref-lte-met-usu, Up: ref-lte-met 4.8.1.1 Type Checking ..................... The following predicates take a term as their argument. They are provided to check the type of that term. The reference pages for these predicates include examples of their use. `atom(+T) "ISO"' term T is an atom `atomic(+T) "ISO"' term T is an atom or a number `callable(+T)' T is an atom or a compound term `compound(+T) "ISO"' T is a compound term `db_reference(+X)' X is currently instantiated to a db_reference `float(+N) "ISO"' N is a floating-point number `ground(+T)' term T is a nonvar, and all substructures are nonvar `integer(+T) "ISO"' term T is an integer `mutable(+X)' X is currently instantiated to a mutable term `nonvar(+T) "ISO"' term T is one of atom, number, compound (that is, T is instantiated) `number(+N) "ISO"' N is an integer or a float `simple(+T)' T is not a compound term; it is either atomic or a var `var(+T) "ISO"' term T is a variable (that is, T is uninstantiated)  File: sicstus.info, Node: ref-lte-met-usu, Prev: ref-lte-met-typ, Up: ref-lte-met 4.8.1.2 Unification ................... The following predicates are related to unification. Unless mentioned otherwise, unification is performed without occurs-check (*note ref-sem-occ::). To unify two terms, simply use: ?- X = Y. *Please note:* * Do not confuse this predicate with `=:=/2' (arithmetic comparison) or `==/2' (term identity). * `=/2' binds free variables in X and Y in order to make them identical. To unify two terms with occurs-check, use: ?- unify_with_occurs_check(X,Y). To check whether two terms do not unify, use the following, which is equivalent to `\+ (X=Y)': ?- X \= Y. To check whether two terms are either strictly identical or do not unify, use the following. This construct is useful in the context of `when/2': ?- ?=(X,Y). To constrain two terms to not unify, use the following. It blocks until `?=(X,Y)' holds: ?- dif(X,Y).  File: sicstus.info, Node: ref-lte-act, Next: ref-lte-acl, Prev: ref-lte-met, Up: ref-lte 4.8.2 Analyzing and Constructing Terms -------------------------------------- The built-in predicate `functor/3': * decomposes a given term into its name and arity, or * given a name and arity, constructs the corresponding compound term creating new uninstantiated variables for its arguments. The built-in predicate `arg/3' unifies a term with a specified argument of another term. The built-in predicate TERM `=..' LIST unifies LIST with a list whose head is the atom corresponding to the principal functor of TERM and whose tail is a list of the arguments of TERM.  File: sicstus.info, Node: ref-lte-acl, Next: ref-lte-c2t, Prev: ref-lte-act, Up: ref-lte 4.8.3 Analyzing and Constructing Lists -------------------------------------- To combine two lists to form a third list, use `append(HEAD, TAIL, LIST)'. To analyze a list into its component lists in various ways, use `append/3' with LIST instantiated to a proper list. The reference page for `append/3' includes examples of its usage, including backtracking. To check the length of a list call `length(LIST, LENGTH)'. To produce a list of a certain length, use `length/2' with LENGTH instantiated and LIST uninstantiated or instantiated to a list whose tail is a variable. To check if a term is the element of a list, use `memberchk(ELEMENT, LIST)'. To enumerate the elements of a list via backtracking, use `member(ELEMENT, LIST)'. To check that a term is NOT the element of a list, use `nonmember(ELEMENT, LIST)', which is equivalent to `\+member(ELEMENT, LIST)'.  File: sicstus.info, Node: ref-lte-c2t, Next: ref-lte-atm, Prev: ref-lte-acl, Up: ref-lte 4.8.4 Converting between Constants and Text ------------------------------------------- Three predicates convert between constants and lists of character codes: `atom_codes/2', `number_codes/2', and `name/2'. Two predicates convert between constants and lists of character atoms: `atom_chars/2', `number_chars/2'. `atom_codes(ATOM, CODES)' is a relation between an atom ATOM and a list CODES consisting of the character codes comprising the printed representation of ATOM. Initially, either ATOM must be instantiated to an atom, or CODES must be instantiated to a proper code-list. `number_codes(NUMBER, CODES)' is a relation between a number NUMBER and a list CODES consisting of the character codes comprising the printed representation of NUMBER. Initially, either NUMBER must be instantiated to a number, or CODES must be instantiated to a proper code-list. Similarly, `atom_chars(ATOM, CHARS)' and `number_chars(ATOM, CHARS)' are relations between a constant and a list consisting of the character atoms comprising the printed representation of the constant. `name/2' converts between a constant and a code-list. Given a code-list, `name/2' will convert it to a number if it can, otherwise to an atom. This means that there are atoms that can be constructed by `atom_codes/2' but not by `name/2'. `name/2' is retained for backwards compatibility with other Prologs. New programs should use `atom_codes/2' or `number_codes/2' as appropriate. `char_code/2' converts between a character atom and a character code.  File: sicstus.info, Node: ref-lte-atm, Next: ref-lte-anv, Prev: ref-lte-c2t, Up: ref-lte 4.8.5 Atom Operations --------------------- To compute LENGTH, the number of characters of the atom ATOM, use: ?- atom_length(ATOM,LENGTH). To concatenate ATOM1 with ATOM2 giving ATOM12, use the following. The predicate can also be used to split a given ATOM12 into two unknown parts: ?- atom_concat(ATOM1,ATOM2,ATOM12). To extract a sub-atom SUBATOM from ATOM, such that the number of characters preceding SUBATOM is BEFORE, the number of characters after SUBATOM is AFTER, and the length of SUBATOM is LENGTH, use the following. Only ATOM needs to be instantiated: ?- sub_atom(ATOM,BEFORE,LENGTH,AFTER,SUBATOM).  File: sicstus.info, Node: ref-lte-anv, Next: ref-lte-cpt, Prev: ref-lte-atm, Up: ref-lte 4.8.6 Assigning Names to Variables ---------------------------------- Each variable in a term is instantiated to a term of the form `'$VAR'(N)', where N is an integer, by the predicate `numbervars/3'. The "write" predicates (`write/[1,2]', `writeq/[1,2]', and `write_term/[2,3]' with the `numbervars(true)' option) transform these terms into upper case letters.  File: sicstus.info, Node: ref-lte-cpt, Next: ref-lte-cte, Prev: ref-lte-anv, Up: ref-lte 4.8.7 Copying Terms ------------------- The meta-logical predicate `copy_term/2' makes a copy of a term in which all variables have been replaced by brand new variables, and all mutables by brand new mutables. This is precisely the effect that would have been obtained from the definition: copy_term(Term, Copy) :- recorda(copy, copy(Term), DBref), instance(DBref, copy(Temp)), erase(DBref), Copy = Temp. although the built-in predicate `copy_term/2' is more efficient. When you call `clause/[2,3]' or `instance/2', you get a new copy of the term stored in the database, in precisely the same sense that `copy_term/2' gives you a new copy. One of the uses of `copy_term/2' is in writing interpreters for logic-based languages; with `copy_term/2' available you can keep "clauses" in a Prolog data structure and pass this structure as an argument without having to store the "clauses" in the Prolog database. This is useful if the set of "clauses" in your interpreted language is changing with time, or if you want to use clever indexing methods. A naive way to attempt to find out whether one term is a copy of another is shown in this example: identical_but_for_variables(X, Y) :- \+ \+ ( numbervars(X, 0, N), numbervars(Y, 0, N), X = Y ). This solution is sometimes sufficient, but will not work if the two terms have any variables in common. If you want the test to succeed even when the two terms do have some variables in common, you need to copy one of them; for example, identical_but_for_variables(X, Y) :- \+ \+ ( copy_term(X, Z), numbervars(Z, 0, N), numbervars(Y, 0, N), Z = Y ). *Please note*: If the term being copied contains attributed variables (*note lib-atts::) or suspended goals (*note ref-sem-sec::), those attributes are not retained in the copy. To retain the attributes, you can use: copy_term(Term, Copy, Body) which in addition to copying the term unifies BODY with a goal such that executing BODY will reinstate the attributes in the COPY. COPY as well as BODY contain brand new (unattributed) variables only. `copy_term/2' is efficient enough to use without hesitation if there is no solution that does not require the use of meta-logical predicates. However, for the sake of both clarity and efficiency, such a solution should be sought before using `copy_term/2'.  File: sicstus.info, Node: ref-lte-cte, Next: ref-lte-mut, Prev: ref-lte-cpt, Up: ref-lte 4.8.8 Comparing Terms --------------------- * Menu: * ref-lte-cte-bas:: Introduction * ref-lte-cte-sot:: Standard Order of Terms * ref-lte-cte-sor:: Sorting Terms  File: sicstus.info, Node: ref-lte-cte-bas, Next: ref-lte-cte-sot, Up: ref-lte-cte 4.8.8.1 Introduction .................... The predicates described in this section are used to compare and order terms, rather than to evaluate or process them. For example, these predicates can be used to compare variables; however, they never instantiate those variables. These predicates should not be confused with the arithmetic comparison predicates (see *note ref-ari-acm::) or with unification.