Vous êtes sur la page 1sur 53

Suleyman Demirel University Mikhail Peretyatkin

Prolog Textbook
Part 1

Logical Fundamentals of

P U RE P ROLOG
Version: December 1, 2007
Abstract

In this Textbook, Logical basis of Prolog programming language is presented. Concepts of Propositional and Predicate logic are explained. Class of Horn formulas is dened and their role in Prolog is shown. Main mechanisms of Prolog-machine are unication for atomic formulas and search-for-solution procedure. Understanding these fundamental concepts of Prolog programming language represent some gate to real programming on Prolog.

Introduction in Formal Logic


Formal logic is also named as Symbolic logic or Mathematical logic.

There are two levels of formal logic. First level is named Propositional logic, while second more common level is named Predicate logic. As a matter of fact, Propositional logic represents very simple particular case of Predicate logic. In ordinary courses of discrete mathematics only Propositional logic is often studied. While for studying Prolog, Predicate logic is required. Thus, we have to give detailed exposition of concepts related to Predicate logic.

1.1

Propositional logic

We start to describe rst level of formal logic which is named as Propositional logic. In this logic we introduce Propositional variables and logical operations. Then we dene formulas of this logic and study their properties. We start denitions concerning to Propositional logic.

1.2

Propositional (elementary logical) variables

Propositional variables mean the same as elementary logical variables. They denote statements that can have two values true and false. We use capital roman letters such as A, B, X, etc. for propositional variables. Subindices and upper indices can also be used for them. Examples of propositional variables: A, A1 , A , B1 , etc. Notice that variables in Prolog program are dened by some special rule which is explained later. Often more simple records 1 and 0 are used instead of truth values true and false. Namely, symbol 0 means false while symbol 1 means true.

1.3

Propositional operations

There exist the following logical operations which ordinarily are included in most of logical considerations: & operation of conjunction (connective and), operation of disjunction (connective or), operation of implication (connective if ... then ...), operation of negation (connective not). Often, in applications of logic some other logical operations are used, particularly, (connective ... if and only if ...), | (connective Scheuer bar which is equivalent to (X&Y)), (connective ... plus ... modulo 2), etc. We do not include them because Prolog programming language does not use these operations, while listed above four operations &, , , and are directly included in Prolog system.

1.4

Truth tables for logical operations

The following truth tables characterize the four logical operations we are considering: 2

X 0 0 1 1

Y 0 1 0 1

X&Y 0 0 0 1

X 0 0 1 1

Y 0 1 0 1

XY 0 1 1 1

X 0 0 1 1

Y 0 1 0 1

XY 1 1 0 1

X 0 1

X 1 0

In this course it is supposed that students well enough understand what mean the tables given above. Therefore, any extra explanations are not included to here.

1.5

Propositional formulas (recursive denition)

Some complex records obtained from propositional variables, logical operations and brackets will be referred as formulas. Constant values 0 and 1 are often included in formulas as well. Definition of propositional formula. (a) Each propositional variable is formula. (b) If A and B are formulas then records of the form (A)&(B), (A) (B), (A) (B), and (A) are also formulas. End of definition. Notice that the denition is recursive. Item (a) gives some class of formulas of the simplest form. Another item (b) gives rule how to construct more complicated formulas from more simple ones. Moreover, item (b) can be applied recursively (i.e., repeatedly). Examples of formulas of propositional logic: A, B, AB, ((A)(B)), etc.

1.6

Priority order for operations

It is supposed that all logical operations are ordered by their priority in the following way: , &, ,
(more strong ...... more weak)

This will help us to use more simple records with minimum brackets for formulas. It is supposed that missed brackets are inserted in such way that more strong operations are performed rst. Example: short record XZ&Y corresponds to full ( (X))((Z)&(Y)) 3

1.7

Truth tables for formulas

It is dened some natural concept of subformula for given propositional formula. To build truth table for a formula we have to list all its subformulas in order from simplest to more complicated, used in assembling of the formula corresponding to the denition. After that, we construct summary table with appropriate set of variables. With n variables, we have to construct 2n lines presenting all possible combinations of values for the variables. Finally, we ll in the table with appropriate truth values by columns. Example: given formula A (CB) List of its subformulas: A, B, C, CB, (CB), A (CB) At last we build resulting truth table of the formula: A 0 0 0 0 1 1 1 1 B 0 0 1 1 0 0 1 1 C 0 1 0 1 0 1 0 1 CB 0 1 1 1 0 1 1 1 (CB) 1 0 0 0 1 0 0 0 A (CB) 1 1 1 1 1 0 0 0

1.8

Types of formulas

A propositional formula A is called tautology if value of A is 1 for all values of its variables, i.e., if the last column in the truth-table of this formula consists of all 1. A formula A is called contradictory if value of A is 0 for all values of its variables. A formula A is called consistent if value of A is 1 for at leas one set of values of its variables. Two formulas A and B are called equivalent if for any set of values for their variables the formulas have the same truth value. We write A B to show that formulas A and B are equivalent. To check that A is tautology, one should make the following: (a) build truth table of the formula; (b) if the column of values for A consists of all 1, A is tautology, otherwise not. To check that A and B are equivalent one should make the following: (a) list joint set of the variables occurred in both formulas; (b) build jointed truth table with this set of variables including there both formulas A and B; 4

(c) if columns of values for A and B coincide, the formulas are equivalent, otherwise they are non-equivalent. Some useful criteria Lemma 1.8.1. The formulas A and B of Propositional logic are equivalent if and only if formula (A B)&(B A) is a tautology. Proof. Immediately.

1.9

Horn formulas
0, a formula A of the form A1 &A2 &...&An B (1.9.1)

For any n

is called Horn formula, where A1 , A2 ,... ,An , and B are logical variables. In particular case n = 0, formula (1.9.1) is simply B. Examples of Horn formulas: A, B&AC, B&A&CB, A&B&C&DX. Notice that, in general, only Horn formulas are used in Prolog programming language (while some other special types of formulas may be used as well).

1.10

Alternative denotations for logical operations

Some alternative versions of symbols used for logical operations are presented in table 1.10.1 below. Also their versions are pointed which are used in Prolog programming language. Table 1.10.1. operation & various alternative denotations AB, AB, AB, A&&B, A|B, A||B, A+B, or -A, A, A, , not and in Prolog , ; not( ) :

In Prolog, brackets are used only for the logical operation not( ). Moreover, they are never used in other parts of Prolog formulas. In general, brackets ( and ) are used in Prolog but they have some special meaning explained later (they are used in terms). Implication in Prolog is denoted by : which in fact means reverse 5

implication . By grammar of Prolog, each its formula should be ended with a dot symbol . which is an analogue of semicolon ; in language C++ ending each operator of C++ program. In Prolog there exists an alternative system of denotations shown below:
Prolog operations Alternative form

: , ;

if and or

Below, a few examples are given which show ordinary formulas and their equivalent presentation as Horn formulas in Prolog programming language:
Ordinary formula Equivalent presentation in Prolog Alternative in Prolog

A AB A&B&CX A&B C&D X

A. B: A. X: A,B,C. XA,B;C,D.

A. B if A. X if A and B and C. X if A and B or C and D.

On this, our denitions concerned to concepts of Propositional logic are nished. Now, we will start to give some preparations required for determining concepts of Predicate logic.

1.11

Algebraic systems shortly

Concept of an algebraic system or shortly a model must be introduced before we start description of Predicate logic. In short, an algebraic system consists of a nonempty set M on which some complex of constants, functions, and predicates is determined. Now we pass to the denitions in detail.

1.12

Cartesian power of a set

Let A and B be sets. By A B we denote the set of all pairs (a,b) where a,b are elements of these sets. In detail: A B = {(a,b) | a A, b B} If A is a set and n 0, we denote by An the n-th power of the set using the operation of Cartesian product. 6

In detail: A0 = {()}, A1 = A, A2 = A A = {(a,b) | a,b A}, A3 = A A A = {(a,b,c) | a,b,c A}, ................................................... An = An1 A = {(a1 ,...,an ) | a1 ,...,an A}, n N. Examples: {0,1} {1,2,3} = {(0,1),(0,2),(0,3),(1,1),(1,2),(1,3)}, {0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)}.
(this set contains the only tuple of length 0)

(1.12.1)

1.13

Predicates, functions, and constants

Let a nonempty set M be given. We will dene concepts of a predicate, a function, and a constant on the set. Predicates. Let an integer number n 0 be given. An arbitrary subset P M n is called n-ary predicate on the set M . For the statement that a tuple (a1 ,...,an ) of elements of M belongs to predicate P , i.e., (a1 ,...,an ) P (1.13.1) we can use either of the following records:
(a) (b) (c) (d) (e)

P is true on the tuple (a1 ,...,an ), P (a1 ,...,an ) is true, P (a1 ,...,an ) = true, P (a1 ,...,an ), tuple (a1 ,...,an ) satises to predicate P.

(1.13.2)

One can say that n-ary predicate P on the set M is similar to a propositional variable, whose truth value depends of n parameters which are element of the set M . Example 1. P = {(0,1,0),(0,1,1),(1,0,1),(1,1,0)} is 3-ary predicate dened on the set {0,1}. 7

Example 2. Set P = {(a,b) | a,b are elements of N, such that a < b} is a binary predicate on the set of natural numbers. Actually it is called predicate of order on the set N. Particularly, P (5,5) is false, P (5,10) is true, P (10,5) is false. Functions. Let an integer number n 0 be given. An arbitrary subset f M n+1 is called n-ary function on the set M if the following conditions are satised: For any elements a1 ,...,an of the set M there is an element b M such that (a1 ,...,an ,b) f ;
(a)

For any elements a1 ,...,an ,b,b of the set M , if (a1 ,...,an ,b) f and (a1 ,...,an ,b ) f then b = b .
(b)

For the statement that a tuple (a1 ,...,an ,b) of elements of M belongs to the set f , i.e., (a1 ,...,an ,b) f (1.13.3) we can use either of the following records:
(a) (b) (c) (d)

value of f on the tuple (a1 ,...,an ) is equal b, f (a1 ,...,an ) is equal to b, f (a1 ,...,an ) = b, tuple (a1 ,...,an ,b) belongs to graphic of function f.

(1.13.4)

Concept of a function on a set is often used in various branches of both pure mathematics and its applications. Here, we have introduced some formal denition for this concept based on set-theoretical approach. Example. f = {(0,0,0),(0,1,1),(1,0,1),(1,1,0)} is a binary function dened on the set {0,1}. Constants. A constant on the set M is some xed element c of this set. As an example one can mention number = 3.14159.. as a constant element on the set R of real numbers. We use special symbol for this special constant.

1.14
0

Nulary predicates as propositional variables

By the denition, 0-ary predicate P on the set M is a subset of set M = {()}, where M 0 contains the only empty tuple. Therefore, there are only two possibilities for such set: Case 1. P = ; 8

Case 2. P = M 0 = {()}. In Case 1, P is identically false. This case corresponds to propositional variable whose value is false. In Case 2, P is identically true. This case corresponds to propositional variable whose value is true. Thus, we have the following important fact: any 0-ary predicate is a propositional variable, whose values may be 0 (i.e., false), or 1 (i.e., true).

1.15

Nulary functions as constant symbols

A nulary function f () on set M depends of none arguments, therefore its value is a xed element of the set M . This means that such function is in fact a constant on the set M . Thus, we have the following important fact: any 0-ary function is constant on the set where the function is dened.

1.16

Algebraic systems

Algebraic system or simply model is a mathematical system of the following form n n m M = M ; P1 1 ,...,Pk k ,f1 1 ,ftmt ,c1 ,...,cs (1.16.1) where M is a nonempty set (called universe set of the model),
n n P1 1 ,...,Pk k are predicates on the set M , predicate Pi has arity ni , m f1 1 ,...,ftmt are functions on the set M , function fi has arity mi ,

c1 ,...,cs are constants on the set M . Notice that, most complicated objects considered in both pure mathematics and its various applications are algebraic systems of such form. Give a few examples. Example 1. N = N; P (x,y),f (x,y),g(x,y),c0 ,c1 such form has known system of integer numbers, where P is predicate of order, f (x,y) is + operation, g(x,y) is operation, while c0 and c1 are constants 0 and 1. Example 2. N = N; <,+,,0,1 an alternative record for the system given in Example 1. Here the predicates, functions and constants are immediately pointed such that none extra comments are required. Example 3. R = R; +,,0,1 the eld of real numbers. 9

Concept of an algebraic system is an abstraction of these particular examples. An algebraic system consists of a nonempty set M on which an arbitrary family of predicates, functions and constants is determined, as it is pointed in (1.16.1). Concept of an algebraic system is required in explaining of semantic for Prolog programming language.

1.17

Predicate logic

Now, we are in a position to start main denitions concerning Predicate logic. First, we dene concept of signature and algebraic system of signature , then we dene terms and formulas of signature . Finally we give semantic of these concepts. This gives main complex of denitions of Predicate logic required for studying Prolog.

1.18

Signature

Some beforehand given set of symbols of predicates, functions and constants (used then for formulas) is called set of primitive symbols for formulas of Predicate Logic, or for brevity it is called signature. In writing of a signature, arity of each predicate symbol and each function symbol should be pointed out. General form of a signature:
n n m = {P1 1 ,...,Pk k ,f1 1 ,ftmt ,c1 ,...,cs }

(1.18.1)

where
n n P1 1 ,...,Pk k are symbols of predicates, predicate symbol Pi has arity ni , m f1 1 ,...,ftmt are symbols of functions, function symbol fi has arity mi ,

c1 ,...,cs are symbols of constants. Suppose that a signature (1.18.1) is given. With this signature we can make the following things: 1) we can consider the set of all algebraic systems of this signature, 2) we can give denition of formulas of this signature, 3) as a matter of fact, each Prolog program has some predened set of primitive symbols used in the program, i.e., some signature is dened for each Prolog program. This set contains names of predicates, functions and constants, arities of predicates and functions should be dened by programmer for correct using them in the program. 10

1.19

Terms and formulas of Predicate logic

Now we start denition of formulas of a beforehand given signature written in (1.18.1). First, we dene terms of this signature, after that we dene class of atomic formulas and then we give denition of formulas of signature . 1. Terms of signature . First, we determine some innite (countable) set of object variables of the form x0 ,x1 ,...,xn ,... ; n N. (1.19.1)

Essence of object variables is that they may be assigned to elements of various algebraic system of the signature we are considering. Definition of term of signature . (a) Each variable in the list (1.19.1) is term. (b) Each constant symbol ci in , 1 i s, is term. (c) If f m is a symbol of m-ary function in and 1 ,...,m are terms, then record f (1 ,...,m ) is term. End of definition The denition is recursive. Items (a) and (b) give class of simplest terms, while rule (c) shows how to construct more complicated terms from more simple ones. Moreover, item (c) can be applied recursively. 2. Atomic formulas of signature . Any formula having either of two following forms (1.19.2) (a) 1 = 1 ,
(b)

P (1 ,2 ,...,n ),

is called atomic formula of signature , where 1 ,2 ,...,m are arbitrary terms of signature , while P n is an n-ary predicate symbol in signature . 3. Formulas of signature . Now we can give denition of formulas. Definition of formulas of signature . (a) Each atomic formula of the form (1.19.2) is formula of signature . (b) If A and B are formulas of signature then the following records (A)&(B), (A) (B), (A) (B), (A) are formulas of signature . (c) If A is a formula of signature and xi is a variable in the list (1.19.1), then records (xi )(A) and (xi )(A) are formulas of signature . End of definition. 11

The denition is recursive. Item (a) gives the class of simplest formulas while items (b) and (c) show how to construct more complicated formulas from more simple ones. Moreover, items (b) and (c) can be applied recursively. Symbols and in Item (c) mean quantier operations, which are new logical operations dened in Predicate logic, while in Propositional logic they are not considered. Expression (x)(..x..) means for all x, statement (..x..) is satised, while (x)(..x..) means there exists x such that statement (..x..) is satised Remark on quantiers and . The denition given above represents full power of Predicate logic which is used in mathematical applications. While, in Prolog programming language, the new quantier operations and are not used. Thus, we will not use formulas obtained with Item (c) in studying of Prolog. Examples of terms and formulas. Suppose that we have the following signature = {P 2 ,Q3 ,R1 ,f 2 ,g 1 ,h3 ,c1 ,c2 ,c3 } (1.19.3) Then, we can build expressions of the following types:
(a) (b) (c) (d) (e) (f) (g) (h) (i) (j) (k) (l) (m) (n) (o) (p)

x2 term (variable), c3 term (constant), f (c3 ,x2 ) term, g(x3 ) term, g(g(x3 )) term, h x1 ,f (c3 ,x2 ),g(g(x3 )) term, h(x1 ,x2 ,x2 ) term, h(x1 ,g(x3 )) bad expression (incorrect arity), f (x1 ,f (x1 ,x4 ) bad expression (incorrect brackets), x1 = g(x3 ) formula (atomic formula) P h(x1 ,x2 ,x2 ),g(g(c2 )) formula (atomic formula), x1 = x2 = c1 bad expression, x1 = (x2 = c1 ) bad expression, R(x3 ,c1 ) bad expression (incorrect arity), R(x1 ) Q(x2 ,g(x1 ),g(g(c2 ))) formula, P (x2 ,c1 ) Q(c1 ,c1 ,g(x0 )) (x2 = c1 ) formula, 12

(q) (r) (s)

f (x1 ,x2 ) g(c2 ) bad expression, (x1 ) R(x1 ) (x2 )P (g(x2 ),c2 ) formula (with quantiers), (x1 )(x2 )f x1 ,g(x2 ) bad expression.

1.20

Some useful rules

Give some useful rules concerning general properties of terms and formulas in both Predicate logic and ordinary mathematics. Term term is a correct expression constructed from object variables, constants and functions corresponding to their arities. Term is a correct expression whose meaning is an element. Polynomials and other arithmetical expressions in mathematics are examples of terms. Examples: x2 + x + 2, ex 3 sin(x) + 2x, etc. Atomic formula either equality of two terms, or predicate of terms whose quantity corresponds to arity of the predicate. Formulas formulas are any correct expressions constructed from atomic formulas with the help of logical operations &, , , , and two quantiers and applicable for object variables. Formula is a correct expression whose meaning is a truth value, either true or false. Examples of formulas in mathematics: 1) x2 + 2x + 3 = 0 this equation is equality of two terms therefore, this is a formula; 2) if x > 0 then sin2 (x) 0 this is correct expression which is a formula.

1.21

Propositional variables in Predicate logic

We can use a 0-ary predicate is signature of Predicate logic. Such predicate has exactly the same meaning as Propositional variable in Propositional logic. For example, consider the following signature = {P 2 ,Q1 ,R0 ,S 0 ,f 2 ,c1 ,c2 } (1.21.1)

We can write simply R and S instead of R() and S() for the 0-ary predicates. Thus, the following expressions are formulas of this signature: S R, S &P (x0 ,c1 ) R, S &(x1 ) P (f (c1 ,x1 ),x2 ) R , etc. Notice that formulas R and S are atomic formulas in signature (1.21.1). So, one can say that Propositional logic represents some particular case 13

of Predicate logic when only 0-ary predicates are included in signature, and we do not use atomic formulas with the equality symbol =.

1.22

Horn formulas in Predicate logic


0, a formula B of the form A1 &A2 &...&An A (1.22.1)

For any n

is called Horn formula in Predicate logic, where A1 , A2 ,..., An , and A are atomic formulas. In particular case n = 0, formula (1.22.1) is simply A. Examples of Horn formulas of signature (1.21.1) in Predicate logic: P (x1 ,f (x2 ,c1 )) & Q(f (f (x1 ,c2 ),x2 )) & P (x1 ,x1 ) Q(x2 ), P (x1 ,c2 )&R S, R&S R, S R, R, P (f (x1 ,x2 ),f (x2 ,x1 )) Examples of the same formulas written in Prolog notation: Q(x2 ) : P (x1 ,f (x2 ,c1 )), Q(f (f (x1 ,c2 ),x2 )), P (x1 ,x1 ). S : P (x1 ,c2 ), R. R : R, S. R : S . R. P (f (x1 ,x2 ),f (x2 ,x1 )).

1.23

Formal system Predicate Calculus

Finally, we say some general words towards Predicate logic. For Predicate logic often its complete title First-Order Predicate Logic is used. Predicate Calculus is some important part of Predicate logic where concept of mathematical proof is presented. In Prolog, these sophisticated parts of Predicate logic are not used at all. In general, one can say that, classical rst-order Predicate Logic is extremely interesting object because it represents a rm foundation for mathe14

matics. Most important mathematical theories can be formally exact founded on the base of rst-order Predicate Calculus with equality (while, some logicians point out logical incompleteness of such approach). At the same time, some particular part of Predicate logic represent basis for Prolog programming language. Now, all is ready to turn to Prolog programming

15

Available Prolog Versions

It will be useful to characterize main available versions of Prolog programming language to understand better what parts of Prolog we are studying and what their signicance.

2.1

Main versions and levels of Prolog

Figure 2.1.1 below represents scheme of Prolog versions/levels which is important for our Course. Give explanations of some details.

Pure Prolog it is absolutely standard part of each Prolog. Essence of Prolog-machine is presented here. To understand what is Prolog, it is required to know how Prolog system works. Unication and backtracking are main operations of Prolog-machine. They represent kernel part of each particular Prolog. This textbook titled Logical Fundamentals of Pure Prolog is exactly attended to explain the kernel concepts of Prolog. ISO Prolog standard specication of Prolog supported by International Standard Organization. It extends Pure Prolog concepts with standard specications of input-output, string processing, namespaces, error handling, debugging, etc. Each particular Prolog should follow these specications. Primitive ISO Prolog some simple part of ISO Prolog including all principal concepts of Prolog, and ignoring some its advanced capabilities. 16

It is enough powerful to develop most of academic programs required in teaching of students. Module ISO Prolog an advanced level of ISO Prolog. Concept of module is required to develop large Prolog programs. Each module uses some separate namespace such that variables described in various modules do not aect to each other. Concept of module is ordinarily included in each programming language. Swi Prolog particular Prolog which is currently most appropriate for student teaching process. It has well organized dialog-mode and debugging tools. While, it does not produce exe-les. Gnu Prolog another particular Prolog compiler useful in teaching process. It can work in both dialog-mode and compiler-mode producing exe-les if required. Moreover, prepared on C/C++ obj-les can be jointed to resulting exe-le.

2.2

Other dialects of Prolog

Turbo Prolog 2.0 (initially version 1.0) was very popular version of Prolog starting from 1988. It has excellent manual named Turbo Prolog, Users Guide, see reference [1]. This Version of Prolog was 16-bit product for DOS. Of course, it did not support ISO-standard which was appeared later. Edinburgh Prolog very important academic version of Prolog, starting from approximately 1988. It has possibility to use terms in both prex and inx forms, not only in ordinary functional form. In Turbo Prolog there was no such possibility. In fact, Edinburgh Prolog advanced with some useful moments of Turbo Prolog, became a prototype for developing ISO Standard for Prolog.

2.3

A few general notes

In this section we give some simple basic rules for Prolog programs. Files. Extension .pl for les of Prolog programs is considered as standard. While, it is possible to use other extensions, if required. Case of letters. Prolog is case-dependent language. Upper-case letters in identiers are dierent from lower-case letters. Particularly, this gives some rules to distinguish constants from variables in Prolog programs. 17

Comments. There are two types of comments. First has form of special brackets / ..... / similar to C++; Second type of comment uses a percentage symbol % ........ such that all the rest of this string after the % is considered as comment. Interpreter/compiler. Prolog system can be used in interpreter mode (called as dialog mode). It is possible to test program and its main parts in this mode. Interpreter mode is often used while studying Prolog. In the other compiler mode, Prolog system works as an ordinary compiler, it simply produces an .exe le. Integrated Development Environment. Currently, academic versions of Prolog do not have special IDE. While, there is some simple handmade IDE based on the editor EditPlus 2. Start EditPlus 2, and then press F4. Some help le will be shown which explains how to use available IDE possibilities with Prolog.

18

Grammar of Pure Prolog


Now, we start description of structure of a Prolog program.

Notice that lot of moments concerned rules for elements of a Prolog program is a consequence of keyboard restrictions. It is impossible to use neither sub-indices nor upper indices for text of a Prolog program. Thus, it is required to establish some special rules such that Prolog system would interpret some names as names of variables, while others as names of predicates, functions and constants, etc. All this should be made in such manner that to obtain as minimal complexity of texts of Prolog programs as possible.

3.1

General structure of a Prolog program

We have to x some signature of the form (1.18.1) before we start to write Prolog program. But, no necessity to give special declaration of signature symbols for Prolog program itself. Programmer should have the signature in his/her mind to obtain correct text of the program. Often, it is useful to list the declarations of signature symbols in commented part of the program. Prolog program consists of two main parts. 1. Body of the program, is also called clause section. It consists of a sequence of Horn-formulas, each of them should be ended by a dot symbol . Clause section is required in each Prolog program. 2. Goal is also called as Query to Prolog system. Query for Prolog system is written (with ending dot symbol .) as ? A1 ,A2 ,...,An . where A1 ,...,An are some atomic formulas. In simplest case it represents a single atomic formula of Predicate Logic. In general case, a query may have form of a sequence of atomic formulas separated by commas. This part query is optional. If goal is presented immediately in text of the program, Prolog searches rst solution realizing the goal, after that, the program stops. If goal is not presented immediately in text of the program, a dialog window is built in which Prolog asks the programmer to input goal. When goal is typed (ending with dot symbol .), Prolog starts to search solution, after that, it answers to the question. Then, it again asks to input some other goal, etc. Main dierence between the two modes: 19

in dialog mode, some dialog is organized in special window, in compiler mode (when goal is included in the text of program) none dialog appears. Only those messages are sent to output which are realized by write(..) operations included in the program. Program immediately stops when rst solution is found.

3.2

Signature symbols in Prolog program

Atoms or simply names in Prolog play role symbols for predicates, functions, constants, and variables (sometimes they are called identiers as in ordinary languages). Names are built from both small and capital letters, digits and underline symbol _ . Starting symbol of a name should be either symbol _ or a letter (not digit). Each predicate is presented by a name in Prolog program. Each function is presented by a name in Prolog program. Constants and variables are presented by names in dierent forms. Constants are names whose leading symbol is a small letter. Apart from that, symbolic records presenting integers, real numbers, strings, and chars are also considered as constants. Examples of constants of various types: john (name presenting an abstract constant), 123 (integer), 1.23E-4 (real), "John Smith" (string), and a (char). Exact denitions are given in Textbook Part 2 (Primitive ISO Prolog). Variables are names whose leading symbol is either one of the capital letters AZ, or the underline symbol _ . Variable _ plays some special role, it is called anonymous variable. Examples of constants/variables: _ anonymous variable, __ a variable, _one a variable, _OnE a variable, X a variable, Some a variable, x a constant, x_e_123_zero a constant, 20

2nd_user

incorrect name (leading digit) incorrect name (an incorrect symbol inside)

third-part

3.3

An anonymous variable

Anonymous variable _ has special role in Prolog. While process of unication it can be assigned to some value, but at once, it forgets the obtained value and becomes again free. It has meaning undened value or a value which is not important. It may be used in both body of program and in its query.

3.4

How Prolog determines signature

Prolog system receives body and goal of a program given by programmer. At rst stage, it determines list of predicate symbols as follows. Firstly Prolog system divides the text of the program on separate parts representing atomic formulas shown schematically inside boxes in Figure 3.4.1. It computes and checks position of balancing brackets and separating symbols :?- , . according to the grammar rules we discussed earlier. If such division is impossible, error is reporting. If the division exists, it immediately gives complete list of predicates existed in the program. Notice that pointed in Fig 3.4.1 names of predicates P1, P2, etc., are not necessarily dierent, some of them may be coincided.

21

At second stage, Prolog determines names of functions, constants and variables. It searches them inside the brackets of atomic formulas corresponding to the division built at First stage. Names bounded at the left with either leading bracket ( or inside bracket ( or comma , are detected. If such name is immediately followed by bracket ( it is name of a function as it is shown in Figure 3.4.2 below.

If such name is followed by a comma , or by closing bracket ) it is name of a constant as it is shown in Figures 3.4.3 below:

or of a variable as it is shown in Figures 3.4.4 below:

Thus, all names of functions and constants/variables are determined. Notice that this algorithm cannot distinguish variables from symbolic constants by their position in program. For this aim, some special rules are established to distinguish constants and variables by their records. They were explained above in Section 3.2. At the last third stage, Prolog checks, if all found names of predicates are dierent from any other names found inside brackets. If all is ok, signature is successfully constructed by the algorithm. Otherwise (if some problems occur), algorithm reports an error.

3.5

The same predicate name for dierent arities

Prolog allows to use the same name for two or more predicates of dierent arities. For instance, name Pred can be used for some 2-ary predicate and simultaneously for some other 3-ary predicate. In such case, these predicates of dierent arities are considered by Prolog system as absolutely dierent predicates, and each of them is processed separately. 22

This useful possibility is provided by the fact that the algorithm given in section 3.4 can easily nd arity of each occurrence of each predicate in Prolog program.

3.6

Facts and rules in clause section

Formulas in clause section of a program (i.e., in its body) may be either general Horn formulas with n > 0 in (1.2.2), or singular Horn formulas with n = 0. Singular Horn formulas of the form A, A is an atomic formula, are called facts in Prolog program. General Horn formulas of the form A : A1 ,...,An , n > 0, are called rules in a Prolog program. Their role will be discussed later. Atomic formula A in the following Horn formula A : A1 ,...,An is called its head, while list of formulas Ai in right-hand side is called its body. Obviously, a singular Horn formula consists of the only head, while its body is empty.

3.7

Nulary predicates as Boolean variables

As it was mentioned in section 1.14, nulary predicates play role of propositional variables. We can use such predicates in Prolog programs. If boo() is such predicate, we can use it in both form boo() or boo depending of programmers wishes. It is obvious that the algorithm given in section 3.4 can easily detect that either of the two records represents a nul-ary predicate. So, no problems to use either of the records in any Prolog program.

3.8

Two ways to dene a constant in Prolog

In Section 1.15 it was mentioned that nulary functions have exactly the same meaning as constants. This gives two alternative possibilities for denition symbolic constants in Prolog program. For instance, we can use names abc and bcd() for two abstract constants, where bcd() is a nul-ary function, equivalent to constant element. Of course, using both records abc and abc() for a constant in the same program will cause an error reporting. Sometimes, this alternative possibility for a constant may be useful.

23

3.9

Demonstration of Prolog programs

For the sake of demonstration, give a few examples of short Prolog programs. They can be used to show most of concepts introduced earlier. Also, style of preparation of Prolog programs is presented in these texts. In a program, all used predicates and functions with their arities should be listed in some commented space. This information is not required for Prolog, but it is useful to read Prolog program and understand what it does. Now, we list a few Prolog programs. 1. Program likes.pl food preferences.
% predicates likes( % ?- likes(sam,X). , ) indian( ) italian( ) mild( )

likes(sam,Food) :- indian(Food), mild(Food). likes(sam,Food) :- italian(Food),Food<>pizza. likes(sam,chips). indian(tandoori). indian(kurma). mild(dahl). mild(kurma). italian(pizza). italian(spaghetti).

2. Program anketa.pl a simple database.


% predicates: anketa( , , , ) children( ) % functions: age( ) addr( , , ) hobby( ) %------------------------------------------------------------------anketa(tom,age(47),addr("Almaty","Abai Street",26),hobby(sport)). anketa(kelly,age(46),addr("Almaty","Abai Street",26),hobby(dog)). anketa(mary,age(23),addr("Akmola","Abai Street",8),hobby(music)). anketa(bill,age(2),addr("Djambul","Kazybek-bi",22),hobby(toy)). %\old{defis} children(Some) :- anketa(Some,age(A),_,_),A<12. % ?- children(X),write("Children="),write(X).

3. Program nod.pl computes general common divisor of two integers.


% predicates nod(integer,integer,integer) nod(0,X,X):- !. nod(X,Y,Z):- Y<X, nod(Y,X,Z). nod(X,Y,Z):- X=<Y, Y1 is Y-X, nod(X,Y1,Z). %\old{defis} % ?- nod(28,48,X).

24

4. Program nodx.pl computes general common divisor (advanced).


% predicates nod(integer,integer,integer) nod(X,Y,_):- nl,write(nod(),write(X),write(,), write(Y),write()=),fail. nod(X,0,X):- !,write(X),nl. nod(X,Y,Z):- Y<X,nod(Y,X,Z). nod(X,Y,Z):- X=<Y,Y1 is (Y-X),nod(X,Y1,Z). %\old{defis} % ?- nod(28,48,X).

25

Unication and Backtracking

Unication and backtracking are two main operations that Prolog-system uses in search for a solution process. They represent main procedures used with Prolog-system for both Pure Prolog and any its extensions.

4.1

General scheme of unication

To explain essence of unication process we have to consider three its stages. First stage represents the moment before unication starts. Second stage is process of unication itself. Third stage is some new complex of assignments for variables appeared as result of the unication. Scheme of unication in detail. First Stage (beginning). We have some complex V of assignments for variables by this moment. For unication we have some two atomic formulas P1 (1 ,2 ,...,k ) and P2 (1 ,2 ,...,t ). (4.1.1)

where P1 and P2 are two arbitrary signature predicates whose arities are respectively k and t, while i and j are terms of signature . Second Stage (main unication procedure). Special unication procedure starts for the pair of atomic formulas (4.1.1). The unication can be either successful or failed, dependently of these formulas. (a) In the case when the unication fails, initial complex of assignments V stays unchanged, and Prolog-system returns to the state existed at First Stage, and then tries to apply unication procedure to some other pairs of atomic formulas. (b) In the case when the unication is successful, some new complex W of assignments is appeared, and Prolog system passes to Third Stage. Third Stage (results). If unication is successful, some new complex W of assignments for variables is appeared as result of the unication. In such case, Prolog-system inserts previous complex of assignments V in stack, and uses new complex W as current in further unications (later, under some particular conditions, Prolog-system may return to previous state V getting this complex of assignments from stack). Thus, Prolog-system intensively uses stack in its work. Note that unication uses two expressions a and b, and, as a matter of fact, their order does not any matter. Namely, unication with expressions a and b gives exactly the same as unication of b with a. 26

4.2

Unication procedure in detail

Two atomic formulas (4.1.1) are given as input parameters for unication procedure. In Figure 4.2.1 below they are presented in some more details corresponding to real records in text of Prolog program.

Unication procedure for the atomic formulas consists of two phases. At rst stage it makes some general estimate, at second stage it calls a recursive subroutine uniterm which performs unication for terms. In more detail. First Phase. If either PredicateName1 is dierent from PredicateName2 or arity k is dierent from arity t, then the unication at a whole is considered as failed. Otherwise, if PredicateName1 coincides with PredicateName2 and k = t, then subroutine uniterm is called for pairs of terms Term-1,i and Term-2,i, i = 1,2,...,k, existed at correspondent places in the atomic formulas pointed in Figure 4.2.1. Second Phase (works recursively, i.e., it can call itself). Procedure uniterm receives some two terms and of signature . Then, they are analyzed, after that, the subroutine performs the following actions. Six cases presented in Figure 4.2.2 are possible for the terms. Case 1. Terms of the form f (1 ,...,p ) and f (1 ,...,q ) are considered, where f and f are signature functions, while i and j are terms. If f is dierent from f , the unication at a whole is considered as failed. If f and f are in fact the same signature symbol (and therefore p = q), procedure uniterm is called for pairs of terms i and i , i = 1,2,...,p, and unication continues. Case 2. Terms of the form f (1 ,...,p ) and c are considered, where f is a signature function while c is a signature or data constant. In this case, the unication at a whole is considered as failed. Case 3. Terms of the form f (1 ,...,p ) and x are considered, where f is a signature function while x is a variable. In this case, value of variable x is assigned to term f (1 ,...,p ), and unication continues. Case 4. Terms of the form c and c are considered, where c and c are signature or data constants. If c and c are dierent, the unication at a whole is considered as failed. Otherwise, if c and c are the same, 27

unication continues. Case 5. Terms of the form c and x are considered, where c is a signature or data constant, while x is a variable. In this case, value of variable x is assigned to constant c, and unication continues. Case 6. Terms of the form x and x are considered, where x and x are variables. In this case, value of variable x is assigned to variable x , and value of variable x is assigned to variable x (thus, the variables become having the same value), and unication continues.

Description of the six cases is nished. If at least in one of the cases occurred while unication process for terms we have obtained failed, the unication at a whole is considered as failed. Otherwise, if all the cases for terms were unied ok, the unication at a whole is considered as successful, and as a result, values of some variables become assigned to some terms of signature . In such case new extended complex W of assignments is obtained as addition to previous state V of all these new assignments occurred while unication.

28

4.3

Unication in the case of an anonymous variable

In the case when the anonymous variable participates at unication, there are some particular rules, which are in the following. While unication process (cases 3, 5, or 6), the anonymous variable can be assigned to a term (or to a variable) as it was described above. But, at once, the variable looses (i.e., forgets) its value and it can participate in unication process again, as free variable (many times, as required).

4.4

Backtracking

In denite situations Prolog-system may want to cancel results of some successful unication performed in past. In this case, Prolog-system simply extracts previous complex of assignments V for variables, which was saved in stack. This operation is called backtracking.

29

Essence of Prolog processing

When a Prolog program is dened and there is a query, Prolog-machine starts its work. Essence of the work represents some process which is called search for a solution. It is possible that none solutions will be found at all, in such case Prolog gives message NO in the dialog window. In some cases, there is the only solution, while the case when many dierent solutions exist is also possible. We often use terms Prolog-system and Prolog-machine (they are synonyms) which are used to mention the algorithm how Prolog searches solutions for given query with given program. In this section, we describe how Prolog searches the solutions.

5.1

Query, goals and subgoals

Similar terms query and goal will denote, in fact, a bit dierent things. A query is some sequence of atomic formulas separated with commas (given to Prolog by programmer), for instance: ?- likes(sam,X),X<>pizza,write(X). Often a query consists of the only atomic formula. A goal, as well as a subgoal, mean a single atomic formula, something like this: likes(sam,X) or maybe write(X). Some xed query should be given to start the search process for a solution. While terms goal and subgoal correspond to objects appearing in this process. While realizing some goal G it is required to initialize process realization of another goal G and maybe some others, we say that G is subgoal in process realization of goal G . While, each subgoal itself is considered as new goal in search for asolution process.

5.2

Matches

For the sake of deniteness, in Figure 5.2.1, as well as in gures further, some Prolog program is presented schematically, which includes a clause section consisting of seven formulas. In all these gures, each box denote an atomic formula. We consider this program to explain some moments appeared in search for a solution process for a separate goal G depicted in the upper part of the Figures. 30

When Prolog considers an atomic formula Q as goal, it tries to match it with head of some Horn formula of the program. It begins from the rst formula available in the clause section, then it tries to match goal with head of the second formula etc. In this sequence of attempts, match is established if unication of the goal G with head of corresponding Horn formula is successful. Four main principles in search for a solution process are the following: (a) A match of goal G with a header Hi may be established if unication of G with Hi is successful. (b) If match of goal G is established with head Hi of a fact, (eg., H3 ), this goal G is considered as realized. (c) If match of goal G is established with head Hi of a rule (eg., H5 ), right-hand parts of this rule (namely, G51 , G52 and G53 ) are considered as new goals, which are called subgoals of given goal G. Process with given goal G is replaced for processing these new goals in right-hand side of the rule. When all subgoals in this sequence are realized, then initial goal G is considered as realized. (d) If match of goal G is established with head Hi of a formula in clause section, in future, operation of backtracking may be performed which discards this match. Backtracking is applicable in certain circumstances which will be considered later.

Now, we pass to further details of match attempts for a separate goal G. At the very beginning, Prolog-machine try to nd match of given goal G with the rst formula available in the clause section (shown in Figure 5.2.3), 31

then it tries to match goal with head of the second formula etc. Figure 5.2.4 presents situation when matches of G with H1 and H2 were not established, while match with H3 was successfully established.

Suppose that match of goal G with head H3 is established. Figure 5.2.4 presents situation when match of goal Q with head H3 is established.

In future, this match may be discarded with backtracking operation, and new match of goal G with head H5 may be established as it is shown in Figure 5.2.5. This match may be discarded as well, and in some moment all the possibilities to establish match may be ended, as it is shown in Figure 5.2.6. In such case, goal G is considered as failed, and the process of search

32

for solutions for this goal is over.

So, we have described processing of a separate goal, from the beginning to its end. Now, we pass to characterize process of search for a solution at a whole.

5.3

Search for a solution process


?-Q1 ,Q2 ,Q3 . (5.3.1)

Suppose that query of the following form consisting of three atomic formulas Q1 , Q2 and Q3 is given to Prologmachine, as it is presented in Figure 5.3.1.

33

Atomic formulas Qi in (5.3.1) are considered as goals that are to be satised successively, i.e., goal Q1 should be realized rst, then goal Q2 is be realized, and nally, goal Q3 is be realized. Suppose that match of goal Q1 with header H2 of formula A2 was established at some moment, such that its subgoals G21 and G22 were successfully realized (process for the last two goals is not presented in gure). Also suppose that afterwards match of goal Q2 with header H5 of formula A5 was established, which immediately give realization of goal Q2 because A5 is fact. At this moment, goal Q3 of query is starting to realization. Prolog-machine tries to establish match of goal Q3 with head H1 of formula A1 , then, if required, with head H2 of formula A2 , and so on. If this search realizes Q3 , given query (5.3.1) at a whole is considered as successively realized. In such case, Prolog gives message YES (denoting that solution exists), and it also writes values of variables assigned by successful unications during the process of search of a solution. In the contrary case, if goal Q3 cannot be realized, Prolog-machine performs backtracking operation as follows. Prolog considers match of Q2 with header H4 of formula A4 as bad (not giving a solution), and discards it by backtracking operation. Then it tries to nd other match for Q2 , and then organizes search for a solution for goal Q3 again, and so on.

5.4

Particularities in dialog/compiler modes

Now, we can exactly characterize dierences of the search for a solution process in the two modes. (a) In compiler mode, Prolog searches only rst solution. When the solution is found, it immediately stops the process (i.e., program ends). (b) In dialog mode, Prolog-machine searches all the solutions. For this aim, it organizes the process described in previous section in some special manner. It tries to nd the rst solution. If this is done, Prolog-machine saves it and tries to nd the second solution and so on. As a result, it is obtained the list of all solutions which is shown on the screen during the dialog.

5.5

What is a solution?

Solution found by Prolog-machine represents the set of values assigned to variables by successful unications during the search for a solution process. 34

If backtracking is performed, values assigned by corresponding unication (occurred earlier) are completely erased. They represent non-successive attempt in search for a solution process, something like dead end (in the search space having form of a tree). Only values for variables included in query are considered as solution. Anonymous variable _ is not printed out during the dialog showing the solutions. The following general rule is acting: All variables participating in search for a solution process are always considered as local variables in Pure Prolog. Any variable is included in namespace of only that formula where it appears. While, any coincided variables of dierent formulas are considered as absolutely dierent variables. For instance, suppose that variable X is occurred in query and in some formulas Ai included in the clause section. In such case, Prolog-machine counts that it has dierent variables X_in_query, X_in_A1, X_in_A2, etc.

5.6

Built-in predicate fail

In Prolog, there is special built-in 0-ary predicate fail which is considered as identically false. If term fail is included in query or in a rule, it always results in backtracking. In some cases, this predicate is useful in programming on Prolog.

5.7

Built-in predicate not

In Prolog, there is special built-in 1-ary predicate not which is used as logical negation. It can be used in the following form only: not(A) where A is an arbitrary atomic formula. To say more precisely, not( ) is not predicate, while only negation operation, specially dened in Prolog. Example of a formula with not: likes(sam,X):-not(likes(tom,X)),indian(X).

35

5.8

Built-in predicate cut

There is some special built-in 0-ary predicate cut which can be written in other form ! as well. While search for a solution process in forward direction, it is considered as true. While it prevents any backtracking operations over itself. If backtracking is required over ! by the algorithm, search for a solution process is immediately terminated. In some cases, this predicate is very useful in programming on Prolog.

5.9

Built-in predicate is as assignment operator

There is special inx binary predicate is in Prolog. Inx means that atomic formulas with this predicate are written as follows: P1 is P2 , (5.9.1) where P1 and P2 are its arguments (i.e., in is set between arguments). For this predicate, left argument P1 must be a variable, while right argument P2 may be any arithmetic expression with mathematical functions dened in Prolog. Predicate is realizes ordinary assignment operator (well known in C++ and Pascal). It computes value of arithmetical expression given in second parameter, and assigns its to the variable given as rst parameter. Example. ?- X is 2+3*4,write(X). prints out 14.

5.10

Processing in Prolog of other built-in predicates

There are some predened (system) predicates in Prolog programming language, such as write(..), openfile(..) etc. While search for a solution process in forward direction, each of them is considered as true. While backtracking operations over such predicates the algorithm of search for a solution simply passes over them, none new possibilities for solutions are considered.

36

Lists in Prolog

Prolog has some special data type called lists. As a matter of fact, lists can be presented in the form of termal data type. Nevertheless, the list type is considered separately, and it is considered as some standard possibility of Pure Prolog. A list is a nite sequence of any elements taken in brackets [ and ]. The elements inside brackets should be separated by commas. Examples of lists: [sam,john,kelly,bill], [1,2,3]. An empty list is denoted by []. Elements of a list may be lists again. Also, elements of a list may be any termal expressions.

6.1

Constants and operations over lists

Empty list is denoted by []. It is considered as special constant element in Prolog. There is the only binary operation over list. If a is an element and L is a list, this operation denoted by [a|L], gives new list where a is head element, while L is tail of the list. So, list [a|L] is obtained by adding element a as new head element to list L. Notice that each list can be presented as some expression over the constant [] and the binary operation [ | ]. Examples: [bill]=[bill|[]], [1,2]=[1|[2|[]]], etc. Expressions of the form [bill], [1,2], [1,2,3,7,2,1,5], etc. presenting lists of xed lengths are allowed in Prolog. Prolog-machine automatically transforms each such record into the form of an expression over operation [ | ] and constant [], and then operates with them.

6.2

Unication for lists

Unication with lists is performed exactly as it was described in Section 4.2. While unication, empty list [] is considered as constant, while [ | ] is considered as binary operation. Examples. 1. Unication of [X,2|L] with [1|List] is successful and as a result variables get the following values: X=1, List=[2|L]. 37

2. Unication of [5,X] and [Y,3] is successful, and variables get the following values: X=3, and Y=5. 3. Unication of [1,X] and [2,3] is failed. 4. Unication of [1,X,7] and [Y,3] is failed. 5. Unication of [1,X,7,Z] and [Y|L] is successful, and variables get the following values: Y=1, L=[X,7,Z].

38

Prologs terms as universal data type

Ordinary programming languages such as C++ or Java have a few predened data types (int, oat, double, char, etc.). More complicated data types are introduced as classes dened by programmer. Programming of classes is known as object oriented programming. In Prolog, there are also available primitive data types such as int, oat, double, char, etc. Moreover, Prolog has some very powerful data type called Prolog-termal data type. As a matter of fact, this type is universal. It can represent suitable data for most purposes in programming. Moreover, no necessity to introduce complex data types (similar to classes). This makes Prolog-programs more short in comparison with C++ because of absence denition for new data types.

7.1

Prolog-termal data type

In this section we explain how the only universal Prolog-termal data type can support most of programmers goals. Give main denitions. Definition 1. [Pure logical definition] Prolog-termal data type consists of the set of all constant terms constructed over signature symbols available in Prolog program. Remaind that, a term is called constant if it does not include variables. Example. If signature includes functions and constants {f 2 ,g 3 ,h1 ,b,c,d}, then the following terms are exemplars of Prolog-termal data type: f(g(b,c,c),h(f(b,d))), h(h(h(a))), etc. Definition 2. [Practical denition] Prolog-termal data type consists of the set of all constant terms constructed over signature symbols available in Prolog program, where constants of predened primitive types integer, oat, double, char, string and symbol can be used. Example. If signature of a Prolog-program includes functions and constants {f 2 ,g 3 ,h1 ,b,c,d}, then the following terms belong to Prolog-termal data type: f(g(c,12.5), "abcdefghijk"), f(a,"abcdefghijk"), etc.

39

7.2

Lists as Prolog-termal data

Lists in Prolog, in fact, do not represent independent data type. Show that lists are just Prolog-termal expressions of some special form. Standard Prolog has one predened constant denoted by [] (empty list) and one binary functor denoted by a single dot .( , ) This functor has the following meaning: rst argument is head, while second argument is tail of a list. For the sake of demonstration, in this section, we will use alternative names nil for [], and ht for dot . (ht means head-tail). The following series of examples shows various records for lists. Prologs list [] [a] [2,X,"abc"] Prolog-termal form [] .(a,[]) .(2,.(X,.("abc",[]))) Demonstration form nil ht(a,nil) ht(2,ht(X,ht("abc",nil)))

Why base list operations . and [] are chosen of such strange form? The answer is that, owing to them, no necessity to use additional identiers for system using. On the other hand, grammar of Prolog language is such that these operations can be correctly parsed and distinguished in Prolog programs.

7.3

Operations with Prolog-termal data type

Prolog-programs can eectively operate with Prolog-termal expressions by way of unication operation. There is possibility to write Prologs code that can both parse an expression, and match suitable case to a given term. Example. Suppose that Prologs variable T can get value of a term covering the following cases with various integer values in brackets: (a) ans(pos(3,5)), (b) ans(pos(7,7),you_loss), (c) ans(pos(7,8),you_win). The following Prolog code will operate with these cases: operat operat operat operat ::::T=ans(pos(X,Y)), !, operate_a(X,Y). T=ans(pos(X,Y),Z), Z=you_win, !, operate_b(X,Y). T=ans(pos(X,Y),Z), Z=you_loss, !, operate_c(X,Y). operate_unknown_case.

Dependently of the case of term T, Prolog chooses suitable scheme operate_a, 40

operate_b, operate_c, or operate_unknown_case. Moreover, while unication T=ans(pos(X,Y),...), variables X and Y get integer values which are available in the body of the expression T. Especially note, that none extra denitions of possible form of term T should be included in the Prolog-program. It is required only that the part of program analyzing terms would cover all possible cases of analyzed terms.

7.4

Input terms with predicate read

Prolog has built-in predicate read which has unary form read(term), and binary form read(device,term). In unary form, predicate read reads a term from keyboard, while in binary form it reads a term from given device device which can be assigned (and later reassigned) to either le or keyboard. When predicate read(X) is considered as a goal in Prolog program, Prolog waits while complete term followed by a dot symbol and then a blank symbol is typed on the keyboard. If correct expression is typed, variable X gets this value. If the record is incorrect (for instance, balancing brackets are wrong) error message is generated by Prolog. Note that other similar predicates such as read_term may cause error because none waiting is supported by these predicates. Example. The following short program reads terms typed on keyboard and reects them on the screen. Each typed term should be ended with a dot symbol and then with Enter pressed. Cltr-c causes value end_of_file for X and the program terminates.
% Program READ_KBD.PL :- initialization(( write(input any terms followed by a dot and then Enter),nl, write((example: abc(t(x,123),"aba")., etc.)),nl, repeat, read(X), write(Term=<),write(X),write(>),nl, X=end_of_file )).

7.5

Prolog-termal data type and XML-language

In this section we demonstrate that Prolog-termal data type is equivalent, in a sense, to the set of texts marked with XML, called XML-marked 41

documents or texts. This fact becomes obvious after we give some demonstrations of the same data portions in these two languages. As an example, consider the following Prolog-termal expression: ans(pos(5,7),you_win) Obviously, it can be equivalently presented as XML-marked text as follows: <answer> <position> <x_ordinate> 5 </x_ordinate> <y_ordinate> 7 </y_ordinate> </position> <type_of_position> you_win </type_of_position> </answer> Both transformation from Prolog-termal expression to XML-marked text and backwards can be organized in dierent ways (not uniquely). Nevertheless, both expression represent the same sense. Prolog-termal expressions seem to be more strong because XML-marked documents use marks similar to balancing brackets (binary symbols), while Prolog-termal expression can include n-ary symbols for arbitrary nite n. On the other hand, the following Prolog-termal expression f(arg1,arg2,arg3) is obviously presented in the following form via XML-marked text <three_ary_function_f> <argument_one> arg1 </argument_one> <argument_two> arg2 </argument_two> <argument_three> arg3 </argument_three> </three_ary_function_f> 42

Similar constructions exist also for Prologs functors of any nite arity. The example above shows that n-ary functions can be easily described as XMLmarked text. This shows that Prolog-termal data type is indeed equivalent to type presented as the set of all XML-marked texts.

7.6

Marking sentences in human languages

Note that any grammatically correct sentence in a natural human language can be either marked with XML or presented as Prolog-termal expression. Note known fact that, the set of languages admitting XML-marking (or Prolog-termal presentation) exactly coincides with the set of all context-free languages. As an example, consider two following sentences in English (1) I have a book (2) I do not like winter The following Prolog-termal expressions mark grammar structure of the sentences: sentence( noun(I), verb(positive(have)), complement(article(a),noun(book)) ) sentence( noun(I), verb(aux(do),negation(not),indefinite(have)), complement(noun(winter)) ) Of course, these sentences can also be presented as XML-marked texts as follows: <sentence> <noun> I </noun> <verb> <positive> have </positive> </verb> <complement> 43

<article> a </article> <noun> book </noun> </complement> <\sentence> <sentence> <noun> I </noun> <verb> <aux> do </aux> <neg> not </neg> <indefinite> have </indefinite> </verb> <complement> <noun> winter </noun> </complement> <\sentence>

44

Prolog in conjunction with Qt graphic

There is natural way to integrate Prolog programming language with Qt language (extending standard C++) providing powerful graphic user interface. Actually, one can uniformly integrate also other Logic programming languages such as Lisp, Clips, etc., with graphic interface of Qt.

8.1

Integration Qt+Prolog

The system Qt itself exists on various platforms: Linux, Windows, and others. This system is developed as maximum portable in various operating systems. By this reason, Qt is preferable for education process. Although exist graphic extensions of Prolog such as XPCE, Visual Prolog, etc., nevertheless, it is more preferable to use stable graphic user interface of Qt. Essence of integration Qt+Prolog in short. In the integrated system Qt+Prolog these language play dierent roles. All graphic interface is written in Qt. As for Prolog, it perform mostly complicated data transformation, playing role of intelligence center in the project. In this method, Prolog is not overloaded with routine technical details required in graphic interface. The best way to link Qt and Logic Programming language is to capture standard input-output. This possibility exists in console project of any Logic programming language including Standard Prolog, both Standard and Common Lisp, base versions of Clips etc.

45

General scheme of integration Qt+Prolog is shown in Fig. 1 above. For the sake of deniteness, Prolog program QUEENS.PL is considered which is compiled in executable le QUEENS.EXE presented in Fig. 1. This program can search solutions for the n queens problem: place n queens on an n by n rectangular chessboard so that each of them is unable to attack each other in a single move. Special class Shell is an important part of the integration. It inherits Qtclass QProcess. Its role is to organize communication between Qt codes and an executable le compiled from Prolog program. An object PROCESS of class Shell is created which is linked to the executable QUEENS.EXE. This object PROCESS can start QUEENS.EXE, and may terminate it as needed. When QUEENS.EXE is active, PROCESS sends sequences of input symbols, waits for answer, and reads the output sequence generated by QUEENS.EXE. An example of dialog between Qt and QUEENS.EXE supported through the object PROCESS of class Shell is shown below: DIALOG STARTED FOR NEW GAME: Prologs start message --- Prolog is waiting for Nqueens. Query to Prolog --- dim(5). Prologs Answer --- Nqueens=5 is accepted. Prolog is ready. Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,2),q(2,4),q(3,1),q(4,3),q(5,5)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,3),q(2,1),q(3,4),q(4,2),q(5,5)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,1),q(2,3),q(3,5),q(4,2),q(5,4)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,2),q(2,5),q(3,3),q(4,1),q(5,4)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,1),q(2,4),q(3,2),q(4,5),q(5,3)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,5),q(2,2),q(3,4),q(4,1),q(5,3)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,4),q(2,1),q(3,3),q(4,5),q(5,2)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,5),q(2,3),q(3,1),q(4,4),q(5,2)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,3),q(2,5),q(3,2),q(4,4),q(5,1)] Query to Prolog --- get_next_solution. Prologs Answer --- [q(1,4),q(2,2),q(3,5),q(4,3),q(5,1)] Query to Prolog --- get_next_solution. Prologs Answer --- .......... List of solutions complete. 46

Of course, Qt part of the project recognizes and reects each of the positions passed from Prolog in graphic form for user. For this, special graphic eld is dened in the project. Moreover, in Qt part, special C++ code analyzes passed position and draws it in graphical form in the screen.

8.2

Available demonstrations

There is a few projects in Qt+Prolog and in pure Prolog prepared for students. The projects demonstrate statements and examples given in this paper. They are described in the following list: 1. queens.exe Qt+Prolog project, n queens problem. 2. hanoi.exe Qt+Prolog project, Hanoi Tower game. 3. king.exe Qt+Prolog project, King game where one player is human, while another is Prolog-solver. 4. kings_garden.exe Qt+Prolog project, a game where one player is human, while another is Prolog-solver. There is a well prepared demonstration sample, and a hundred of various versions included in task-PDF for students (as Exercise 10). 5. compiler.exe console Prolog project, demonstrates transformation of Prolog-termal data in dierent forms.

47

Summary
These are some important ideas weve considered in this paper:

1. Prolog-termal data type is equivalent to the type consisting of the set of all XML-marked documents. 2. Prologs terms can be read by read predicate, and then they can be effectively parsed by performing unication with templates corresponding to possible forms of the term. 3. Lists in Prolog represent particular case of Prolog-termal data type. 4. Prolog programming language seems to be convenient to build parsers and compilers as well as other programs developing context-free languages. In conclusion one can say that, integrated complex Qt+Prolog seems to be useful in educational process. First, it requires to know only Standard Prolog, Standard C++, and base level of Qt programming system, which exist in very stable versions and therefore are suitable for educational aims. Programming in Prolog with capable graphic interface forces increasing interest of students to this language. Further, very powerful Prolog-termal data type used in this project is, in fact, equivalent to XML language. Knowing deep possibilities available for this data type is useful in studying programming. Finally, Prolog programming language itself is very appropriate to write programs of compilers, parsers, and language interfaces for software. This also makes it useful in educational process.

48

10

Appendix: Simple built-in predicates

Notice that a plenty of predicates, operations and special possibilities are available in ISO Prolog. Most common of them are listed below: X=Y --- unification not(...) --- system Prolog negation not \+(...) --- other denotation for Prolog negation not not(A) --- goal A is not true \+(A) --- equivalent to not(A) \+(X=Y) --- unification fails \+(CallableTerm) --- goal fails X==Y --- equality of the objects \+(X==Y) --- inequality of objects X<Y --- less that X>Y --- greater than X=<Y --- less or equal than X>=Y --- greater or equal than X=\=Y --- not equal not(X=Y) --- not unified X is Expression --- assignment operation (eg. X is 2*Y+Z.) (Y mod Z) --- remainder of division Y/Z --- float division Y//Z --- intrger division (floor rounding to an integer) random(X) --- random number X satisfying 0=< X =< 1 random(A,B,X) -- random integer X satisfying A=< X =< B abs(X) --- absolute value (module) of X sign(X) --- sign of X (1 if X>0, 0 if X=0, -1 if X<0) max(X,Y) --- maximum of X and Y min(X,Y) --- minimum of X and Y sqrt(X) --- square root of X round(X) --- float X is rounding to an integer value findall(Variable,CallableTerm,List) --- find all solutions Give some recommendation for strings. In general, Prolog has conventions for string that in general are similar to that in C++. For instance, slashsymbol \n in strings means new line. For exact descriptions of rules for strings, see Textbook, Part 2, Primitive ISO Prolog. Finally, list simple built-in predicates for writing: write(variable/constant) prints out current value of the expression (variable that has got a value or constant) on the screen. 49
1)

2)

nl performs new line while printing on the screen.

Examples: ?- likes(sam,X),write("X="),write(X). write("first-line"),nl,write("second-line") is equivalent to the following: write("first-line\nsecond-line")

50

11

References

1. Textbook: Turbo Prolog 2.0, Materials originally distributed with Turbo Prolog 2.0 package, 1988, 384p. 2. Electronic Textbook: Visual Prolog Version 5.0 (Language tutorial), Prolog Development Center, Copenhagen, Denmark, A/S, (c) Copyright 19861997, 479p. 3. Daniel Diaz. GNU Prolog. A Native Prolog Compiler with Constraint Solving over Finite Domains. Edition 1.7, for GNU Prolog version 1.2.16, September 25, 2002. 4. Jan Wielemaker. SWI-Prolog 5.6 Reference Manual Updated for version 5.6.0, December 2005. University of Amsterdam HumanComputer Studies (HCS, formerly SWI). 5. Maks Schlee. Qt. Professional programming on C++. BHV, St.Petersburg (Russian), 2005, 544 p. 6. U. Klocksin and K. Mellish, Programming on Prolog, Springer Verlag, BerlinHeidelbergNew York, 1989, 340p. 7. I. Bratko, Prolog Programming for articail intelligence, Second edition, Wokingham, UK, Addison-Wesley, 1990, 559p. 8. John Hopcroft, Rajeev Motwani, Jeffry Ullman. Introduction to Automata, Theory, Languages, and Computations. Addison Wesley Publishing Company, 2001, 528 p. 9. L. Sterling, and E. Shapiro, The Art of Prolog, Cambridge, Massachisets, MIT Press, 450p. 10. E. Mendelson, Introduction to Mathematical Logic, Princeton, New Jersey, Toronto, New York, London, 1976. 11. Robert I. Soare, Recursively Enumerable Sets and Degrees, Springer Verlag, BerlinHeidelbergNew York, 1986, 437p.

51

Contents
1 Introduction in Formal Logic 1.1 Propositional logic . . . . . . . . . . . . . . 1.2 Propositional (elementary logical) variables . 1.3 Propositional operations . . . . . . . . . . . 1.4 Truth tables for logical operations . . . . . . 1.5 Propositional formulas (recursive denition) 1.6 Priority order for operations . . . . . . . . . 1.7 Truth tables for formulas . . . . . . . . . . . 1.8 Types of formulas . . . . . . . . . . . . . . . 1.9 Horn formulas . . . . . . . . . . . . . . . . . 1.10 Alternative denotations for logical operations 1.11 Algebraic systems shortly . . . . . . . . . . . 1.12 Cartesian power of a set . . . . . . . . . . . 1.13 Predicates, functions, and constants . . . . . 1.14 Nulary predicates as propositional variables . 1.15 Nulary functions as constant symbols . . . . 1.16 Algebraic systems . . . . . . . . . . . . . . . 1.17 Predicate logic . . . . . . . . . . . . . . . . . 1.18 Signature . . . . . . . . . . . . . . . . . . . . 1.19 Terms and formulas of Predicate logic . . . . 1.20 Some useful rules . . . . . . . . . . . . . . . 1.21 Propositional variables in Predicate logic . . 1.22 Horn formulas in Predicate logic . . . . . . . 1.23 Formal system Predicate Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2 2 2 2 3 3 4 4 5 5 6 6 7 8 9 9 10 10 11 13 13 14 14 16 16 17 17 19 19 20 21 21 22 23 23 23 24 26 26 27 29 29 30 30 30 33 34 34 35 35 36 36 36 37 37 37 39 39 40 40 41

Available Prolog Versions 2.1 Main versions and levels of Prolog . . . . . . . . . . . . . . . . . . . . . . . . . 2.2 Other dialects of Prolog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3 A few general notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Grammar of Pure Prolog 3.1 General structure of a Prolog program . . . . 3.2 Signature symbols in Prolog program . . . . 3.3 An anonymous variable . . . . . . . . . . . . 3.4 How Prolog determines signature . . . . . . . 3.5 The same predicate name for dierent arities 3.6 Facts and rules in clause section . . . . . . . 3.7 Nulary predicates as Boolean variables . . . 3.8 Two ways to dene a constant in Prolog . . . 3.9 Demonstration of Prolog programs . . . . . . Unication and Backtracking 4.1 General scheme of unication . . . . . . 4.2 Unication procedure in detail . . . . . 4.3 Unication in the case of an anonymous 4.4 Backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . variable . . . . .

Essence of Prolog processing 5.1 Query, goals and subgoals . . . . . . . . . . . . 5.2 Matches . . . . . . . . . . . . . . . . . . . . . . 5.3 Search for a solution process . . . . . . . . . . 5.4 Particularities in dialog/compiler modes . . . . . 5.5 What is a solution? . . . . . . . . . . . . . . . . 5.6 Built-in predicate fail . . . . . . . . . . . . . . 5.7 Built-in predicate not . . . . . . . . . . . . . . . 5.8 Built-in predicate cut . . . . . . . . . . . . . . . 5.9 Built-in predicate is as assignment operator . 5.10 Processing in Prolog of other built-in predicates

Lists in Prolog 6.1 Constants and operations over lists . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Unication for lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Prologs terms as universal data type 7.1 Prolog-termal data type . . . . . . . . . 7.2 Lists as Prolog-termal data . . . . . . . . 7.3 Operations with Prolog-termal data type 7.4 Input terms with predicate read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

52

7.5 7.6 8

Prolog-termal data type and XML-language . . . . . . . . . . . . . . . . . . . Marking sentences in human languages . . . . . . . . . . . . . . . . . . . . . .

41 43 45 45 47 48 49 51

Prolog in conjunction with Qt graphic 8.1 Integration Qt+Prolog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2 Available demonstrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Summary

10 Appendix: Simple built-in predicates 11 References

53