Prolog syntax and semantics

The syntax and semantics of Prolog, a programming language, are the sets of rules that define how a Prolog program is written and how it is interpreted, respectively. The rules are laid out in ISO standard ISO/IEC 13211 although there are differences in the Prolog implementations.

Data types
Prolog is dynamically typed. It has a single data type, the term, which has several subtypes: atoms, numbers, variables and compound terms.

An atom is a general-purpose name with no inherent meaning. It is composed of a sequence of characters that is parsed by the Prolog reader as a single unit. Atoms are usually bare words in Prolog code, written with no special syntax. However, atoms containing spaces or certain other special characters must be surrounded by single quotes. Atoms beginning with a capital letter must also be quoted, to distinguish them from variables. The empty list, written, is also an atom. Other examples of atoms include,  ,  , and.

Numbers can be floats or integers. Many Prolog implementations also provide unbounded integers and rational numbers.

Variables are denoted by a string consisting of letters, numbers and underscore characters, and beginning with an upper-case letter or underscore. Variables closely resemble variables in logic in that they are placeholders for arbitrary terms. A variable can become instantiated (bound to equal a specific term) via unification. A single underscore denotes an anonymous variable and means "any term". Unlike other variables, the underscore does not represent the same value everywhere it occurs within a predicate definition.

A compound term is composed of an atom called a "functor" and a number of "arguments", which are again terms. Compound terms are ordinarily written as a functor followed by a comma-separated list of argument terms, which is contained in parentheses. The number of arguments is called the term's arity. An atom can be regarded as a compound term with arity zero.

Examples of compound terms are  and. Compound terms with functors that are declared as operators can be written in prefix or infix notation. For example, the terms,   and   can also be written as  ,   and  , respectively. Users can declare arbitrary functors as operators with different precedences to allow for domain-specific notations. The notation f/n is commonly used to denote a term with functor f and arity n.

Special cases of compound terms:


 * Lists are defined inductively: The atom  is a list. A compound term with functor   (dot) and arity 2, whose second argument is a list, is itself a list. There exists special syntax for denoting lists:   is equivalent to  . For example, the list   can also be written as , or even more compactly as.
 * Strings: A sequence of characters surrounded by quotes is equivalent to a list of (numeric) character codes, generally in the local character encoding or Unicode if the system supports Unicode.

Prolog programs
Prolog programs describe relations, defined by means of clauses. Pure Prolog is restricted to Horn clauses, a Turing-complete subset of first-order predicate logic. There are two types of clauses: Facts and rules. A rule is of the form

and is read as "Head is true if Body is true". A rule's body consists of calls to predicates, which are called the rule's goals. The built-in predicate  (meaning a 2-arity operator with name  ) denotes conjunction of goals, and   denotes disjunction. Conjunctions and disjunctions can only appear in the body, not in the head of a rule.

Clauses with empty bodies are called facts. An example of a fact is:

which is equivalent to the rule:

another example is:

and when you run it, the result will be

The built-in predicate  is always true.

Evaluation
Execution of a Prolog program is initiated by the user's posting of a single goal, called the query. Logically, the Prolog engine tries to find a resolution refutation of the negated query. The resolution method used by Prolog is called SLD resolution. If the negated query can be refuted, it follows that the query, with the appropriate variable bindings in place, is a logical consequence of the program. In that case, all generated variable bindings are reported to the user, and the query is said to have succeeded. Operationally, Prolog's execution strategy can be thought of as a generalization of function calls in other languages, one difference being that multiple clause heads can match a given call. In that case, the system creates a choice-point, unifies the goal with the clause head of the first alternative, and continues with the goals of that first alternative. If any goal fails in the course of executing the program, all variable bindings that were made since the most recent choice-point was created are undone, and execution continues with the next alternative of that choice-point. This execution strategy is called chronological backtracking.

This results in the following query being evaluated as true:

This is obtained as follows: Initially, the only matching clause-head for the query  is the first one, so proving the query is equivalent to proving the body of that clause with the appropriate variable bindings in place, i.e., the conjunction. The next goal to be proved is the leftmost one of this conjunction, i.e.,. Two clause heads match this goal. The system creates a choice-point and tries the first alternative, whose body is. This goal can be proved using the fact, so the binding   is generated, and the next goal to be proved is the second part of the above conjunction:. Again, this can be proved by the corresponding fact. Since all goals could be proved, the query succeeds. Since the query contained no variables, no bindings are reported to the user. A query with variables, like:

enumerates all valid answers on backtracking.

Notice that with the code as stated above, the query  also succeeds. One would insert additional goals to describe the relevant restrictions, if desired.

Loops and recursion
Iterative algorithms can be implemented by means of recursive predicates. Prolog systems typically implement a well-known optimization technique called tail call optimization (TCO) for deterministic predicates exhibiting tail recursion or, more generally, tail calls: A clause's stack frame is discarded before performing a call in a tail position. Therefore, deterministic tail-recursive predicates are executed with constant stack space, like loops in other languages.

Cuts
A cut inside a rule will prevent Prolog from backtracking any predicates behind the cut:

will fail if the first-found value of  for which   is true leads to   being false.

Anonymous variables
Anonymous variables  are never bound to a value and can be used multiple times in a predicate.

For instance searching a list for a given value:

Negation
The built-in Prolog predicate  provides negation as failure, which allows for non-monotonic reasoning. The goal  in the rule

is evaluated as follows: Prolog attempts to prove the. If a proof for that goal can be found, the original goal (i.e., ) fails. If no proof can be found, the original goal succeeds. Therefore, the  prefix operator is called the "not provable" operator, since the query   succeeds if Goal is not provable. This kind of negation is sound if its argument is "ground" (i.e. contains no variables). Soundness is lost if the argument contains variables. In particular, the query  can now not be used to enumerate all things that are legal.

Semantics
Under a declarative reading, the order of rules, and of goals within rules, is irrelevant since logical disjunction and conjunction are commutative. Procedurally, however, it is often important to take into account Prolog's execution strategy, either for efficiency reasons, or due to the semantics of impure built-in predicates for which the order of evaluation matters. Also, as Prolog interpreters try to unify clauses in the order they're provided, failing to give a correct ordering can lead to infinite recursion, as in:

Given this ordering, any query of the form

will recur until the stack is exhausted. If, however, the last 3 lines were changed to: the same query would lead to a No. outcome in a very short time.

Definite clause grammars
There is a special notation called definite clause grammars (DCGs). A rule defined via  instead of   is expanded by the preprocessor (, a facility analogous to macros in other languages) according to a few straightforward rewriting rules, resulting in ordinary Prolog clauses. Most notably, the rewriting equips the predicate with two additional arguments, which can be used to implicitly thread state around, analogous to monads in other languages. DCGs are often used to write parsers or list generators, as they also provide a convenient interface to list differences.

Parser example
A larger example will show the potential of using Prolog in parsing.

Given the sentence expressed in Backus–Naur form:

This can be written in Prolog using DCGs, corresponding to a predictive parser with one token look-ahead:

This code defines a relation between a sentence (given as a list of tokens) and its abstract syntax tree (AST). Example query:

The AST is represented using Prolog terms and can be used to apply optimizations, to compile such expressions to machine-code, or to directly interpret such statements. As is typical for the relational nature of predicates, these definitions can be used both to parse and generate sentences, and also to check whether a given tree corresponds to a given list of tokens. Using iterative deepening for fair enumeration, each arbitrary but fixed sentence and its corresponding AST will be generated eventually: