prolog textbook 1

Upload: amandeep651

Post on 05-Apr-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Prolog Textbook 1

    1/53

    Suleyman Demirel University

    Mikhail Peretyatkin

    Prolog Textbook

    Part 1

    Logical Fundamentals of

    PURE PROLOG

    Version: December 1, 2007

    Abstract

    In this Textbook, Logical basis of Prolog programming language is pre-sented. Concepts of Propositional and Predicate logic are explained.

    Class of Horn formulas is defined and their role in Prolog is shown.

    Main mechanisms of Prolog-machine are unification for atomic for-

    mulas and search-for-solution procedure. Understanding these funda-

    mental concepts of Prolog programming language represent some gate

    to real programming on Prolog.

    1 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 Propositionallogic, while second more common level is named Predicate logic. As a matterof fact, Propositional logic represents very simple particular case of Predicatelogic.

    In ordinary courses of discrete mathematics only Propositional logic isoften studied. While for studying Prolog, Predicate logic is required. Thus,we have to give detailed exposition of concepts related to Predicate logic.

  • 7/31/2019 Prolog Textbook 1

    2/53

    1.1 Propositional logic

    We start to describe first level of formal logic which is named as Propo-sitional logic. In this logic we introduce Propositional variables and logicaloperations. Then we define formulas of this logic and study their properties.

    We start definitions 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 usecapital roman letters such as A, B, X, etc. for propositional variables. Sub-

    indices and upper indices can also be used for them. Examples of proposi-tional variables: A, A1, A

    , B1, etc. Notice that variables in Prolog programare defined by some special rule which is explained later.

    Often more simple records 1 and 0 are used instead of truth values trueand false. Namely, symbol 0 means false while symbol 1 means true.

    1.3 Propositional operations

    There exist the following logical operations which ordinarily are includedin 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 Scheuffer barwhich is equivalent to (X&Y)), (connective ... plus ... modulo 2), etc.We do not include them because Prolog programming language does notuse these operations, while listed above four operations &, , , and aredirectly included in Prolog system.

    1.4 Truth tables for logical operations

    The following truth tables characterize the four logical operations we areconsidering:

    2

  • 7/31/2019 Prolog Textbook 1

    3/53

    X Y X&Y0 0 0

    0 1 0

    1 0 0

    1 1 1

    X Y XY0 0 0

    0 1 1

    1 0 1

    1 1 1

    X Y XY0 0 1

    0 1 1

    1 0 0

    1 1 1

    X X

    0 1

    1 0

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

    1.5 Propositional formulas (recursive definition)

    Some complex records obtained from propositional variables, logical op-

    erations and brackets will be referred as formulas. Constant values 0 and 1are often included in formulas as well.

    Definition of propositional formula.

    (a) Each propositional variable is formula.

    (b) IfA and Bare formulas then records of the form (A)&(B), (A) (B),(A) (B), and (A) are also formulas.

    End of definition.

    Notice that the definition is recursive. Item (a) gives some class of for-mulas of the simplest form. Another item (b) gives rule how to constructmore complicated formulas from more simple ones. Moreover, item (b) canbe 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 inthe following way:

    , &, , (more strong ...... more weak)

    This will help us to use more simple records with minimum brackets forformulas. It is supposed that missed brackets are inserted in such way that

    more strong operations are performed first.Example: short record XZ&Y corresponds to full ((X))((Z)&(Y))

    3

  • 7/31/2019 Prolog Textbook 1

    4/53

    1.7 Truth tables for formulas

    It is defined some natural concept of subformula for given propositionalformula. To build truth tablefor a formula we have to list all its subformulasin order from simplest to more complicated, used in assembling of the formulacorresponding to the definition. After that, we construct summary table withappropriate set of variables. With n variables, we have to construct 2n linespresenting all possible combinations of values for the variables. Finally, wefill 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 B C CB (CB) A(CB)0 0 0 0 1 1

    0 0 1 1 0 1

    0 1 0 1 0 1

    0 1 1 1 0 1

    1 0 0 0 1 1

    1 0 1 1 0 0

    1 1 0 1 0 0

    1 1 1 1 0 0

    1.8 Types of formulas

    A propositional formula A is called tautology if value of A is 1 for allvalues of its variables, i.e., if the last column in the truth-table of this formulaconsists of all 1. A formula A is called contradictory if value of A is 0 for allvalues 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 toshow that formulas A and B are equivalent.

    To check that A is tautology, one should make the following: (a) buildtruth table of the formula; (b) if the column of values for A consists of all1, 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 jointedtruth table with this set of variables including there both formulas A and B;

    4

  • 7/31/2019 Prolog Textbook 1

    5/53

    (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 equiv-alent if and only if formula (A B)&(B A) is a tautology.

    Proof. Immediately.

    1.9 Horn formulas

    For any n0, a formula A of the form

    A1 &A2 &...&AnB (1.9.1)

    is called Horn formula, where A1, A2,... ,An, and B are logical variables. Inparticular 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 program-ming language (while some other special types of formulas may be used aswell).

    1.10 Alternative denotations for logical operations

    Some alternative versions of symbols used for logical operations are pre-sented in table 1.10.1 below. Also their versions are pointed which are usedin Prolog programming language.

    Table 1.10.1.

    operation various alternative denotations in Prolog

    & AB, AB, AB, A&&B, and ,

    A|B, A||B, A+B, or ;

    -A, A, A, not not( )

    , :

    In Prolog, brackets are used only for the logical operation not( ). More-over, 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

  • 7/31/2019 Prolog Textbook 1

    6/53

    implication . By grammar of Prolog, each its formula should be endedwith 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 theirequivalent presentation as Horn formulas in Prolog programming language:

    Ordinary formula Equivalent presentation in Prolog Alternative in Prolog

    A A. A.AB B: A. B if A.A&B&CX X: A,B,C. X if A and B and C.A&B C&D X XA,B ;C,D. X if A and B or C and D.

    On this, our definitions concerned to concepts of Propositional logic arefinished. Now, we will start to give some preparations required for deter-mining concepts of Predicate logic.

    1.11 Algebraic systems shortly

    Concept of an algebraic system or shortly a model must be introducedbefore we start description of Predicate logic. In short, an algebraic systemconsists of a nonempty set M on which some complex of constants, functions,and predicates is determined.

    Now we pass to the definitions 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) wherea,b are elements of these sets.

    In detail:A B = {(a,b) | a A, b B}

    If A is a set and n0, we denote by An the n-th power of the set using theoperation of Cartesian product.

    6

  • 7/31/2019 Prolog Textbook 1

    7/53

    In detail:

    A0 = {()}, (this set contains the only tuple of length 0)

    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.

    (1.12.1)

    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)}.

    1.13 Predicates, functions, and constants

    Let a nonempty set M be given. We will define concepts of a predicate,a function, and a constant on the set.

    Predicates. Let an integer number n0 be given. An arbitrary subset

    P Mn

    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) P is true on the tuple (a1,...,an),

    (b) P(a1,...,an) is true,

    (c) P(a1,...,an) = true,

    (d) P(a1,...,an),

    (e) tuple (a1,...,an) satisfies to predicate P.

    (1.13.2)

    One can say that n-ary predicate P on the set M is similar to a proposi-tional variable, whose truth value depends ofn parameters which are elementof the set M.

    Example 1. P= {(0,1,0),(0,1,1),(1,0,1),(1,1,0)} is 3-ary predicate de-fined on the set {0,1}.

    7

  • 7/31/2019 Prolog Textbook 1

    8/53

    Example 2. Set P= {(a,b) | a,b are elements of N, such that a < b} is abinary predicate on the set of natural numbers. Actually it is called predicateof 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 n0 be given. An arbitrary subsetf Mn+1 is called n-ary function on the set M if the following conditionsare satisfied:

    (a) For any elements a1,...,an of the set M there is an element b Msuch that (a1,...,an,b) f;

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

    (a1,...,an,b) f then b = b.

    For the statement that a tuple (a1

    ,...,an,b) of elements of M belongs tothe set f, i.e.,

    (a1,...,an,b) f (1.13.3)

    we can use either of the following records:

    (a) value of f on the tuple (a1,...,an) is equal b,

    (b) f(a1,...,an) is equal to b,

    (c) f(a1,...,an) = b,

    (d) 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 bothpure mathematics and its applications. Here, we have introduced some for-mal definition 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 de-fined on the set {0,1}.

    Constants. A constant on the set M is some fixed element c of this set.As an example one can mention number = 3.14159.. as a constant elementon the set R of real numbers. We use special symbol for this special constant.

    1.14 Nulary predicates as propositional variables

    By the definition, 0-ary predicate P on the set M is a subset of setM0 = {()}, where M0 contains the only empty tuple. Therefore, there are

    only two possibilities for such set:Case 1. P=;

    8

  • 7/31/2019 Prolog Textbook 1

    9/53

    Case 2. P= M0 = {()}.

    In Case 1, P is identically false. This case corresponds to propositionalvariable whose value is false. In Case 2, P is identically true. This casecorresponds to propositional variable whose value is true.

    Thus, we have the following important fact: any 0-ary predicate is apropositional 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 itsvalue is a fixed element of the set M. This means that such function is infact a constant on the set M.

    Thus, we have the following important fact: any 0-ary function is con-stant on the set where the function is defined.

    1.16 Algebraic systems

    Algebraic system or simply model is a mathematical system of the follow-ing form

    M= M; P

    n1

    1 ,...,Pnk

    k ,fm1

    1 ,fmt

    t ,c1,...,cs (1.16.1)where

    M is a nonempty set (called universe set of the model),

    Pn11 ,...,Pnkk are predicates on the set M, predicate Pi has arity ni,

    fm11 ,...,fmtt 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 mathe-matics 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 knownsystem of integer numbers, where P is predicate of order, f(x,y) is + oper-ation, g(x,y) is operation, while c0 and c1 are constants 0 and 1.

    Example 2. N= N;

  • 7/31/2019 Prolog Textbook 1

    10/53

    Concept of an algebraic system is an abstraction of these particular ex-amples. An algebraic system consists of a nonempty set M on which anarbitrary family of predicates, functions and constantsis determined, as it ispointed 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 definitions concerning Predi-cate logic. First, we define concept of signature and algebraic system ofsignature , then we define terms and formulas of signature . Finally wegive semantic of these concepts. This gives main complex of definitions of

    Predicate logic required for studying Prolog.

    1.18 Signature

    Some beforehand given set of symbols of predicates, functions and con-stants (used then for formulas) is called set of primitive symbols for formulasof Predicate Logic, or for brevity it is called signature. In writing of a sig-nature, arity of each predicate symbol and each function symbol should be

    pointed out.General form of a signature:

    = {Pn11 ,...,Pnkk ,f

    m11 ,f

    mtt ,c1,...,cs} (1.18.1)

    where

    Pn11 ,...,Pnkk are symbols of predicates, predicate symbol Pi has arity ni,

    fm11 ,...,fmtt 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 definition of formulas of this signature,

    3) as a matter of fact, each Prolog program has some predefined set ofprimitive symbols used in the program, i.e., some signature is defined for

    each Prolog program. This set contains names of predicates, functions andconstants, arities of predicates and functions should be defined by program-mer for correct using them in the program.

    10

  • 7/31/2019 Prolog Textbook 1

    11/53

    1.19 Terms and formulas of Predicate logic

    Now we start definition of formulas of a beforehand given signature written in (1.18.1). First, we define terms of this signature, after that wedefine class of atomic formulas and then we give definition of formulas ofsignature .

    1. Terms of signature . First, we determine some infinite (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 ofvarious 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) Iffm is a symbol ofm-ary function in and 1,...,m are terms, thenrecord f(1,...,m) is term.

    End of definition

    The definition is recursive. Items (a) and (b) give class of simplest terms,while rule (c) shows how to construct more complicated terms from moresimple ones. Moreover, item (c) can be applied recursively.

    2. Atomic formulas of signature . Any formula having either oftwo following forms

    (a) 1 = 1,

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

    (1.19.2)

    is called atomic formulaof signature , where 1,2,...,m are arbitrary terms

    of signature , while Pn is an n-ary predicate symbol in signature .

    3. Formulas of signature . Now we can give definition 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) IfA 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

  • 7/31/2019 Prolog Textbook 1

    12/53

    The definition is recursive. Item (a) gives the class of simplest formulaswhile items (b) and (c) show how to construct more complicated formulasfrom more simple ones. Moreover, items (b) and (c) can be applied recur-sively.

    Symbols and in Item (c) mean quantifier operations, which are newlogical operations defined in Predicate logic, while in Propositional logic theyare not considered. Expression (x)(..x..) means for all x, statement (..x..)is satisfied, while (x)(..x..) means there exists x such that statement(..x..) is satisfied

    Remark on quantifiers and . The definition given above representsfull power of Predicate logic which is used in mathematical applications.While, in Prolog programming language, the new quantifier 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 followingsignature

    = {P2,Q3,R1,f2,g1,h3,c1,c2,c3} (1.19.3)

    Then, we can build expressions of the following types:

    (a) x2 term (variable),

    (b) c3 term (constant),(c) f(c3,x2) term,

    (d) g(x3) term,

    (e) g(g(x3)) term,

    (f) h

    x1,f(c3,x2),g(g(x3))

    term,

    (g) h(x1,x2,x2) term,

    (h) h(x1,g(x3)) bad expression (incorrect arity),

    (i) f(x1,f(x1,x4) bad expression (incorrect brackets),

    (j) x1 = g(x3) formula (atomic formula)

    (k) P

    h(x1,x2,x2),g(g(c2))

    formula (atomic formula),

    (l) x1 = x2 = c1 bad expression,

    (m) x1 = (x2 = c1) bad expression,

    (n) R(x3,c1) bad expression (incorrect arity),

    (o) R(x1) Q(x2,g(x1),g(g(c2))) formula,

    (p) P(x2,c1) Q(c1,c1,g(x0)) (x2 = c1)

    formula,

    12

  • 7/31/2019 Prolog Textbook 1

    13/53

    (q) f(x1,x2) g(c2) bad expression,

    (r) (x1)

    R(x1) (x2)P(g(x2),c2)

    formula (with quantifiers),

    (s) (x1)(x2)f

    x1,g(x2)

    bad expression.

    1.20 Some useful rules

    Give some useful rules concerning general properties of terms and formu-las 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 correctexpression whose meaning is an element. Polynomials and other arithmetical

    expressions in mathematics are examples of terms. Examples: x2

    + x + 2,ex 3sin(x) + 2x, etc.

    Atomic formula either equality of two terms, or predicate of termswhose quantity corresponds to arity of the predicate.

    Formulas formulas are any correct expressions constructed from atomicformulas with the help of logical operations &, , , , and two quanti-fiers and applicable for object variables. Formula is a correct expressionwhose 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 termstherefore, this is a formula; 2) if x > 0 then sin2(x)0 this is correctexpression which is a formula.

    1.21 Propositional variables in Predicate logic

    We can use a 0-ary predicate is signature of Predicate logic. Such predi-cate has exactly the same meaning as Propositional variable in Propositional

    logic.For example, consider the following signature

    = {P2,Q1,R0,S0,f2,c1,c2} (1.21.1)

    We can write simply R and S instead ofR() 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

  • 7/31/2019 Prolog Textbook 1

    14/53

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

    1.22 Horn formulas in Predicate logic

    For any n0, a formula B of the form

    A1 &A2 &...&An A (1.22.1)

    is called Horn formula in Predicate logic, where A1, A2,..., An, and A areatomic 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 Logicis used. Predicate Calculus is some important part of Predicate logic whereconcept of mathematical proof is presented. In Prolog, these sophisticatedparts of Predicate logic are not used at all.

    In general, one can say that, classical first-order Predicate Logic is ex-tremely interesting object because it represents a firm foundation for mathe-

    14

  • 7/31/2019 Prolog Textbook 1

    15/53

    matics. Most important mathematical theories can be formally exact foundedon the base of first-order Predicate Calculus with equality (while, some logi-cians point out logical incompleteness of such approach). At the same time,some particular part of Predicate logic represent basis for Prolog program-

    ming language.Now, all is ready to turn to Prolog programming

    15

  • 7/31/2019 Prolog Textbook 1

    16/53

    2 Available Prolog Versions

    It will be useful to characterize main available versions of Prolog program-ming language to understand better what parts of Prolog we are studying

    and what their significance.

    2.1 Main versions and levels of Prolog

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

    Pure Prolog it is absolutely standard part of each Prolog. Essenceof Prolog-machine is presented here. To understand what is Prolog, it is re-quired to know how Prolog system works. Unification and backtracking are

    main operations of Prolog-machine. They represent kernel part of each par-ticular Prolog. This textbook titled Logical Fundamentals of Pure Prologis exactly attended to explain the kernel concepts of Prolog.

    ISO Prolog standard specification of Prolog supported by Interna-tional Standard Organization. It extends Pure Prolog concepts with stan-dard specifications of input-output, string processing, namespaces, error han-dling, debugging, etc. Each particular Prolog should follow these specifica-tions.

    Primitive ISO Prolog some simple part of ISO Prolog including allprincipal concepts of Prolog, and ignoring some its advanced capabilities.

    16

  • 7/31/2019 Prolog Textbook 1

    17/53

    It is enough powerful to develop most of academic programs required inteaching of students.

    Module ISO Prolog an advanced level of ISO Prolog. Concept ofmodule is required to develop large Prolog programs. Each module uses

    some separate namespace such that variables described in various modulesdo not affect to each other. Concept of module is ordinarily included in eachprogramming language.

    Swi Prolog particular Prolog which is currently most appropriate forstudent teaching process. It has well organized dialog-mode and debuggingtools. While, it does not produce exe-files.

    Gnu Prolog another particular Prolog compiler useful in teachingprocess. It can work in both dialog-mode and compiler-mode producing

    exe-files if required. Moreover, prepared on C/C++ obj-files can be jointedto resulting exe-file.

    2.2 Other dialects of Prolog

    Turbo Prolog 2.0 (initially version 1.0) was very popular version ofProlog 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 appearedlater.

    Edinburgh Prolog very important academic version of Prolog, startingfrom approximately 1988. It has possibility to use terms in both prefix andinfix forms, not only in ordinary functional form. In Turbo Prolog there wasno such possibility. In fact, Edinburgh Prolog advanced with some usefulmoments of Turbo Prolog, became a prototype for developing ISO Standardfor Prolog.

    2.3 A few general notes

    In this section we give some simple basic rules for Prolog programs.

    Files. Extension .pl for files of Prolog programs is considered as stan-dard. While, it is possible to use other extensions, if required.

    Case of letters. Prolog is case-dependent language. Upper-case letters

    in identifiers are different from lower-case letters. Particularly, this givessome rules to distinguish constants from variables in Prolog programs.

    17

  • 7/31/2019 Prolog Textbook 1

    18/53

    Comments. There are two types of comments. First has form of spe-cial brackets / ..... / similar to C++; Second type of comment uses apercentage 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 partsin this mode. Interpreter mode is often used while studying Prolog. In theother compiler mode, Prolog system works as an ordinary compiler, it simplyproduces an .exe file.

    Integrated Development Environment. Currently, academic ver-sions of Prolog do not have special IDE. While, there is some simple hand-made IDE based on the editor EditPlus 2. Start EditPlus 2, and then press

    F4. Some help file will be shown which explains how to use available IDEpossibilities with Prolog.

    18

  • 7/31/2019 Prolog Textbook 1

    19/53

    3 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 useneither sub-indices nor upper indices for text of a Prolog program. Thus,it is required to establish some special rules such that Prolog system wouldinterpret some names as names of variables, while others as names of predi-cates, functions and constants, etc. All this should be made in such mannerthat to obtain as minimal complexity of texts of Prolog programs as possible.

    3.1 General structure of a Prolog program

    We have to fix some signature of the form (1.18.1) before we start to writeProlog program. But, no necessity to give special declaration of signaturesymbols for Prolog program itself. Programmer should have the signature inhis/her mind to obtain correct text of the program. Often, it is useful to listthe 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 systemis 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 haveform of a sequence of atomic formulas separated by commas.

    This part query is optional. If goal is presented immediately in text ofthe program, Prolog searches first solution realizing the goal, after that, theprogram 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 searchsolution, after that, it answers to the question. Then, it again asks to input

    some other goal, etc.Main difference between the two modes:

    19

  • 7/31/2019 Prolog Textbook 1

    20/53

    in dialog mode, some dialog is organized in special window,

    in compiler mode (when goal is included in the text of program) nonedialog appears. Only those messages are sent to output which are realizedby write(..) operations included in the program. Program immediately

    stops when first solution is found.

    3.2 Signature symbols in Prolog program

    Atoms or simply names in Prolog play role symbols for predicates, func-tions, constants, and variables (sometimes they are called identifiers as inordinary 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 different forms.

    Constants are names whose leading symbol is a small letter. Apart fromthat, symbolic records presenting integers, real numbers, strings, and charsare 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 definitions are given in Text-book Part 2 (Primitive ISO Prolog).

    Variables are names whose leading symbol is either one of the capitalletters 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

  • 7/31/2019 Prolog Textbook 1

    21/53

    2nd_user incorrect name (leading digit)

    third-part incorrect name (an incorrect symbol inside)

    3.3 An anonymous variableAnonymous variable _ has special role in Prolog. While process of unifi-

    cation it can be assigned to some value, but at once, it forgets the obtainedvalue and becomes again free. It has meaning undefined value or a valuewhich is not important. It may be used in both body of program and in itsquery.

    3.4 How Prolog determines signatureProlog system receives body and goal of a program given by programmer.

    At first stage, it determines list of predicate symbols as follows.

    Firstly Prolog system divides the text of the program on separate partsrepresenting atomic formulas shown schematically inside boxes in Figure3.4.1. It computes and checks position of balancing brackets and separatingsymbols

    :- ?- , .

    according to the grammar rules we discussed earlier. If such division isimpossible, error is reporting. If the division exists, it immediately givescomplete list of predicates existed in the program. Notice that pointed inFig 3.4.1 names of predicates P1, P2, etc., are not necessarily different, someof them may be coincided.

    21

  • 7/31/2019 Prolog Textbook 1

    22/53

    At second stage, Prolog determines names of functions, constants andvariables. It searches them inside the brackets of atomic formulas corre-sponding 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 ofa 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. No-tice that this algorithm cannot distinguish variables from symbolic constantsby their position in program. For this aim, some special rules are establishedto distinguish constants and variables by their records. They were explainedabove in Section 3.2.

    At the last third stage, Prolog checks, if all found names of predicates aredifferent from any other names found inside brackets. If all is ok, signature

    is successfully constructed by the algorithm. Otherwise (if some problemsoccur), algorithm reports an error.

    3.5 The same predicate name for different arities

    Prolog allows to use the same name for two or more predicates of differentarities. For instance, name Pred can be used for some 2-ary predicate andsimultaneously for some other 3-ary predicate. In such case, these predicates

    of different arities are considered by Prolog system as absolutely differentpredicates, and each of them is processed separately.

    22

  • 7/31/2019 Prolog Textbook 1

    23/53

    This useful possibility is provided by the fact that the algorithm givenin section 3.4 can easily find arity of each occurrence of each predicate inProlog program.

    3.6 Facts and rules in clause section

    Formulas in clause section of a program (i.e., in its body) may be eithergeneral Horn formulas with n > 0 in (1.2.2), or singular Horn formulas withn = 0.

    Singular Horn formulas of the form A, A is an atomic formula, are calledfacts in Prolog program. General Horn formulas of the form A : A1,...,An,n > 0, are called rulesin a Prolog program. Their role will be discussed later.

    Atomic formula A in the following Horn formula A : A1,...,An is calledits head, while list of formulas Ai in right-hand side is called its body. Ob-viously, a singular Horn formula consists of the only head, while its body isempty.

    3.7 Nulary predicates as Boolean variables

    As it was mentioned in section 1.14, nulary predicates play role of propo-sitional 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 ofprogrammers wishes.

    It is obvious that the algorithm given in section 3.4 can easily detect thateither of the two records represents a nul-ary predicate. So, no problems touse either of the records in any Prolog program.

    3.8 Two ways to define a constant in PrologIn Section 1.15 it was mentioned that nulary functions have exactly the

    same meaning as constants. This gives two alternative possibilities for defini-tion symbolic constants in Prolog program. For instance, we can use namesabc 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

  • 7/31/2019 Prolog Textbook 1

    24/53

    3.9 Demonstration of Prolog programs

    For the sake of demonstration, give a few examples of short Prolog pro-grams. 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 shouldbe listed in some commented space. This information is not required forProlog, 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( , ) indian( ) italian( ) mild( )

    % ?- likes(sam,X).

    likes(sam,Food) :- indian(Food), mild(Food).

    likes(sam,Food) :- italian(Food),Foodpizza.

    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

  • 7/31/2019 Prolog Textbook 1

    25/53

    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

  • 7/31/2019 Prolog Textbook 1

    26/53

    4 Unification and Backtracking

    Unification and backtracking are two main operations that Prolog-systemuses 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 unification

    To explain essence of unification process we have to consider three itsstages. First stage represents the moment before unification starts. Secondstage is process of unification itself. Third stage is some new complex ofassignments for variables appeared as result of the unification.

    Scheme of unification in detail.

    First Stage (beginning). We have some complex V of assignments forvariables by this moment. For unification 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 arerespectively k and t, while i and

    j are terms of signature .

    Second Stage (main unification procedure). Special unification procedure

    starts for the pair of atomic formulas (4.1.1). The unification can be eithersuccessful or failed, dependently of these formulas.

    (a) In the case when the unification fails, initial complex of assignmentsV stays unchanged, and Prolog-system returns to the state existed at FirstStage, and then tries to apply unification procedure to some other pairs ofatomic formulas.

    (b) In the case when the unification is successful, some new complex Wof assignments is appeared, and Prolog system passes to Third Stage.

    Third Stage (results). If unification is successful, some new complex Wof assignments for variables is appeared as result of the unification. In suchcase, Prolog-system inserts previous complex of assignments V in stack, anduses new complex W as current in further unifications (later, under someparticular conditions, Prolog-system may return to previous state V gettingthis complex of assignments from stack).

    Thus, Prolog-system intensively uses stack in its work.

    Note that unification uses two expressions a and b, and, as a matter offact, their order does not any matter. Namely, unification with expressionsa and b gives exactly the same as unification of b with a.

    26

  • 7/31/2019 Prolog Textbook 1

    27/53

    4.2 Unification procedure in detail

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

    Unification procedure for the atomic formulas consists of two phases. Atfirst stage it makes some general estimate, at second stage it calls a recursivesubroutine uniterm which performs unification for terms.

    In more detail.First Phase. If either PredicateName1 is different from PredicateName2

    or arity k is different from arity t, then the unification at a whole is consideredas failed. Otherwise, if PredicateName1 coincides with PredicateName2and k = t, then subroutine uniterm is called for pairs of terms Term-1,iand Term-2,i, i = 1,2,...,k, existed at correspondent places in the atomicformulas 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

    different from f, the unification at a whole is considered as failed. If f andf are in fact the same signature symbol (and therefore p = q), procedureuniterm is called for pairs of terms i and

    i , i = 1,2,...,p, and unification

    continues.

    Case 2. Terms of the form f(1,...,p) and c are considered, where f is asignature function while c is a signature or data constant. In this case, theunification at a whole is considered as failed.

    Case 3. Terms of the form f(1,...,p) and x are considered, where f isa signature function while x is a variable. In this case, value of variable x isassigned to term f(1,...,p), and unification 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 different, the unificationat a whole is considered as failed. Otherwise, if c and c are the same,

    27

  • 7/31/2019 Prolog Textbook 1

    28/53

  • 7/31/2019 Prolog Textbook 1

    29/53

    4.3 Unification in the case of an anonymous variable

    In the case when the anonymous variable participates at unification, thereare some particular rules, which are in the following. While unificationprocess (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 unification process again, asfree variable (many times, as required).

    4.4 Backtracking

    In definite situations Prolog-system may want to cancel results of somesuccessful unification performed in past. In this case, Prolog-system simplyextracts previous complex of assignments V for variables, which was savedin stack. This operation is called backtracking.

    29

  • 7/31/2019 Prolog Textbook 1

    30/53

    5 Essence of Prolog processing

    When a Prolog program is defined and there is a query, Prolog-machinestarts 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, insuch case Prolog gives message NO in the dialog window. In some cases,there is the only solution, while the case when many different solutions existis also possible.

    We often use terms Prolog-system and Prolog-machine (they aresynonyms) which are used to mention the algorithm how Prolog searchessolutions 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 differentthings. A query is some sequence of atomic formulas separated with commas(given to Prolog by programmer), for instance:

    ?- likes(sam,X),Xpizza,write(X).

    Often a query consists of the only atomic formula.

    A goal, as well as a subgoal, mean a single atomic formula, somethinglike this: likes(sam,X) or maybe write(X). Some fixed query should begiven to start the search process for a solution. While terms goal andsubgoal correspond to objects appearing in this process. While realizingsome goal G it is required to initialize process realization of another goalG 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 searchfor asolution process.

    5.2 Matches

    For the sake of definiteness, in Figure 5.2.1, as well as in figures further,some Prolog program is presented schematically, which includes a clausesection consisting of seven formulas. In all these figures, each box denote

    an atomic formula. We consider this program to explain some momentsappeared in search for a solution process for a separate goal G depictedin the upper part of the Figures.

    30

  • 7/31/2019 Prolog Textbook 1

    31/53

    When Prolog considers an atomic formula Q as goal, it tries to matchit with head of some Horn formula of the program. It begins from the firstformula available in the clause section, then it tries to match goal with headof the second formula etc. In this sequence of attempts, match is established

    if unification of the goal G with head of corresponding Horn formula issuccessful.

    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 unificationof 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 asnew goals, which are called subgoals of given goal G. Process with givengoal G is replaced for processing these new goals in right-hand side of therule. When all subgoals in this sequence are realized, then initial goal G isconsidered as realized.

    (d) If match of goal G is established with head Hi of a formula in clausesection, in future, operation ofbacktrackingmay be performed which discardsthis 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 find match of given goal Gwith the first formula available in the clause section (shown in Figure 5.2.3),

    31

  • 7/31/2019 Prolog Textbook 1

    32/53

    then it tries to match goal with head of the second formula etc. Figure 5.2.4presents 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.4presents situation when match of goal Q with head H3 is established.

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

    32

  • 7/31/2019 Prolog Textbook 1

    33/53

    for solutions for this goal is over.

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

    5.3 Search for a solution process

    Suppose that query of the following form

    ?-Q1,Q2,Q3. (5.3.1)

    consisting of three atomic formulas Q1, Q2 and Q3 is given to Prolog-machine, as it is presented in Figure 5.3.1.

    33

  • 7/31/2019 Prolog Textbook 1

    34/53

    Atomic formulas Qi in (5.3.1) are considered as goals that are to besatisfied successively, i.e., goal Q1 should be realized first, then goal Q2 isbe realized, and finally, goal Q3 is be realized.

    Suppose that match of goal Q1 with header H2 of formula A2 was estab-

    lished at some moment, such that its subgoals G21 and G22 were successfullyrealized (process for the last two goals is not presented in figure). Also sup-pose that afterwards match of goal Q2 with header H5 of formula A5 wasestablished, which immediately give realization of goal Q2 because A5 is fact.At this moment, goal Q3 of query is starting to realization. Prolog-machinetries to establish match of goal Q3 with head H1 of formula A1, then, ifrequired, 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 (denot-ing that solution exists), and it also writes values of variables assigned bysuccessful unifications during the process of search of a solution.

    In the contrary case, if goal Q3 cannot be realized, Prolog-machine per-forms backtracking operation as follows. Prolog considers match of Q2 withheader H4 of formula A4 as bad (not giving a solution), and discards it bybacktracking operation. Then it tries to find other match for Q2, and thenorganizes search for a solution for goal Q3 again, and so on.

    5.4 Particularities in dialog/compiler modes

    Now, we can exactly characterize differences of the search for a solutionprocess in the two modes.

    (a) In compiler mode, Prolog searches only first solution. When thesolution 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 specialmanner. It tries to find the first solution. If this is done, Prolog-machinesaves it and tries to find the second solution and so on. As a result, it isobtained the list of all solutions which is shown on the screen during thedialog.

    5.5 What is a solution?

    Solution found by Prolog-machine represents the set of values assigned tovariables by successful unifications during the search for a solution process.

    34

  • 7/31/2019 Prolog Textbook 1

    35/53

    If backtracking is performed, values assigned by corresponding unification(occurred earlier) are completely erased. They represent non-successive at-tempt in search for a solution process, something like dead end (in thesearch 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 so-lutions.

    The following general rule is acting:

    All variables participating in search for a solution process are alwaysconsidered as local variables in Pure Prolog. Any variable is includedin namespace of only that formula where it appears. While, any coincidedvariables of different formulas are considered as absolutely different variables.

    For instance, suppose that variable X is occurred in query and in someformulas Ai included in the clause section. In such case, Prolog-machinecounts that it has different 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 consid-ered as identically false. If term fail is included in query or in a rule, italways 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 aslogical negation. It can be used in the following form only:

    not(A)

    where A is an arbitrary atomic formula. To say more precisely, not( ) isnot predicate, while only negation operation, specially defined in Prolog.

    Example of a formula with not:

    likes(sam,X):-not(likes(tom,X)),indian(X).

    35

  • 7/31/2019 Prolog Textbook 1

    36/53

    5.8 Built-in predicate cut

    There is some special built-in 0-ary predicate cut which can be written inother form ! as well. While search for a solution process in forward direc-tion, it is considered as true. While it prevents any backtracking operationsover itself. If backtracking is required over ! by the algorithm, search for asolution 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 infix binary predicate is in Prolog. Infix 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 ar-gument P2 may be any arithmetic expression with mathematical functionsdefined in Prolog. Predicate is realizes ordinary assignment operator (wellknown in C++ and Pascal). It computes value of arithmetical expressiongiven in second parameter, and assigns its to the variable given as first pa-rameter.

    Example. ?- X is 2+3*4,write(X). prints out 14.

    5.10 Processing in Prolog of other built-in predicates

    There are some predefined (system) predicates in Prolog programminglanguage, such as write(..), openfile(..) etc. While search for a solu-

    tion process in forward direction, each of them is considered as true. Whilebacktracking operations over such predicates the algorithm of search for asolution simply passes over them, none new possibilities for solutions areconsidered.

    36

  • 7/31/2019 Prolog Textbook 1

    37/53

    6 Lists in Prolog

    Prolog has some special data type called lists. As a matter of fact, listscan be presented in the form of termal data type. Nevertheless, the list type

    is considered separately, and it is considered as some standard possibility ofPure Prolog.

    A list is a finite sequence of any elements taken in brackets [ and ]. Theelements 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 anytermal expressions.

    6.1 Constants and operations over lists

    Empty list is denoted by []. It is considered as special constant elementin Prolog.

    There is the only binary operation over list. If a is an element and L is alist, 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 asnew head element to list L.

    Notice that each list can be presented as some expression over the con-stant [] 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. present-ing lists of fixed lengths are allowed in Prolog. Prolog-machine automaticallytransforms each such record into the form of an expression over operation[ | ] and constant [], and then operates with them.

    6.2 Unification for lists

    Unification with lists is performed exactly as it was described in Section4.2. While unification, empty list [] is considered as constant, while [ | ]is considered as binary operation.

    Examples.

    1. Unification of [X,2|L] with [1|List] is successful and as a resultvariables get the following values: X=1, List=[2|L].

    37

  • 7/31/2019 Prolog Textbook 1

    38/53

    2. Unification of [5,X] and [Y,3] is successful, and variables get thefollowing values: X=3, and Y=5.

    3. Unification of [1,X] and [2,3] is failed.

    4. Unification of [1,X,7] and [Y,3] is failed.

    5. Unification of [1,X,7,Z] and [Y|L] is successful, and variables getthe following values: Y=1, L=[X,7,Z].

    38

  • 7/31/2019 Prolog Textbook 1

    39/53

  • 7/31/2019 Prolog Textbook 1

    40/53

    7.2 Lists as Prolog-termal data

    Lists in Prolog, in fact, do not represent independent data type. Showthat lists are just Prolog-termal expressions of some special form.

    Standard Prolog has one predefined constant denoted by [] (empty list)and one binary functor denoted by a single dot .( , ) This functor has thefollowing meaning: first argument is head, while second argument is tail ofa list. For the sake of demonstration, in this section, we will use alternativenames nil for [], and ht for dot . (ht means head-tail).

    The following series of examples shows various records for lists.

    Prologs list Prolog-termal form Demonstration form

    [] [] nil

    [a] .(a,[]) ht(a,nil)[2,X,"abc"] .(2,.(X,.("abc",[]))) 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 identifiersfor system using. On the other hand, grammar of Prolog language is suchthat these operations can be correctly parsed and distinguished in Prologprograms.

    7.3 Operations with Prolog-termal data type

    Prolog-programs can effectively operate with Prolog-termal expressionsby way of unification operation. There is possibility to write Prologs codethat 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 cov-ering 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 :- T=ans(pos(X,Y)), !, operate_a(X,Y).

    operat :- T=ans(pos(X,Y),Z), Z=you_win, !, operate_b(X,Y).

    operat :- T=ans(pos(X,Y),Z), Z=you_loss, !, operate_c(X,Y).

    operat :- operate_unknown_case.

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

    40

  • 7/31/2019 Prolog Textbook 1

    41/53

    operate_b, operate_c, or operate_unknown_case. Moreover, while unifi-cation T=ans(pos(X,Y),...), variables X and Y get integer values which areavailable in the body of the expression T.

    Especially note, that none extra definitions of possible form of term T

    should be included in the Prolog-program. It is required only that the partof 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 aterm from keyboard, while in binary form it reads a term from given device

    devicewhich can be assigned (and later reassigned) to either file or keyboard.When predicate read(X) is considered as a goal in Prolog program, Pro-

    log waits while complete term followed by a dot symbol and then a blanksymbol is typed on the keyboard. If correct expression is typed, variable Xgets this value. If the record is incorrect (for instance, balancing brackets arewrong) error message is generated by Prolog. Note that other similar predi-cates such as read_term may cause error because none waiting is supportedby these predicates.

    Example. The following short program reads terms typed on keyboardand reflects them on the screen. Each typed term should be ended with adot symbol and then with Enter pressed. Cltr-c causes value end_of_filefor 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=),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 equiva-lent, in a sense, to the set of texts marked with XML, called XML-marked

    41

  • 7/31/2019 Prolog Textbook 1

    42/53

    documents or texts. This fact becomes obvious after we give some demon-strations 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:

    5

    7

    you_win

    Both transformation from Prolog-termal expression to XML-marked textand backwards can be organized in different ways (not uniquely). Neverthe-less, both expression represent the same sense.

    Prolog-termal expressions seem to be more strong because XML-markeddocuments use marks similar to balancing brackets (binary symbols), whileProlog-termal expression can include n-ary symbols for arbitrary finite 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

    arg1

    arg2

    arg3

    42

  • 7/31/2019 Prolog Textbook 1

    43/53

    Similar constructions exist also for Prologs functors of any finite arity. Theexample above shows that n-ary functions can be easily described as XML-marked text. This shows that Prolog-termal data type is indeed equivalentto 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 lan-guage can be either marked with XML or presented as Prolog-termal expres-sion. Note known fact that, the set of languages admitting XML-marking (orProlog-termal presentation) exactly coincides with the set of all context-freelanguages.

    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 sen-tences:

    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 asfollows:

    I

    have

    43

  • 7/31/2019 Prolog Textbook 1

    44/53

    a book

    I

    do

    not

    have

    winter

    44

  • 7/31/2019 Prolog Textbook 1

    45/53

    8 Prolog in conjunction with Qt graphic

    There is natural way to integrate Prolog programming language with Qtlanguage (extending standard C++) providing powerful graphic user inter-

    face. Actually, one can uniformly integrate also other Logic programminglanguages 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, andothers. This system is developed as maximum portable in various operatingsystems. By this reason, Qt is preferable for education process. Although

    exist graphic extensions of Prolog such as XPCE, Visual Prolog, etc., nev-ertheless, 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 different roles.All graphic interface is written in Qt. As for Prolog, it perform mostlycomplicated data transformation, playing role of intelligence center in theproject. In this method, Prolog is not overloaded with routine technicaldetails required in graphic interface.

    The best way to link Qt and Logic Programming language is to cap-ture standard input-output. This possibility exists in console project of anyLogic programming language including Standard Prolog, both Standard andCommon Lisp, base versions of Clips etc.

    45

  • 7/31/2019 Prolog Textbook 1

    46/53

    General scheme of integration Qt+Prolog is shown in Fig. 1 above.

    For the sake of definiteness, Prolog program QUEENS.PL is consideredwhich is compiled in executable file QUEENS.EXE presented in Fig. 1. Thisprogram 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 attackeach other in a single move.

    Special class Shell is an important part of the integration. It inherits Qt-class QProcess. Its role is to organize communication between Qt codes andan executable file compiled from Prolog program. An object PROCESS of classShell is created which is linked to the executable QUEENS.EXE. This objectPROCESS can start QUEENS.EXE, and may terminate it as needed. WhenQUEENS.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

  • 7/31/2019 Prolog Textbook 1

    47/53

    Of course, Qt part of the project recognizes and reflects each of the positionspassed from Prolog in graphic form for user. For this, special graphic fieldis defined in the project. Moreover, in Qt part, special C++ code analyzespassed 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 forstudents. The projects demonstrate statements and examples given in thispaper. 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 ishuman, while another is Prolog-solver. There is a well prepared demon-stration sample, and a hundred of various versions included in task-PDFfor students (as Exercise 10).

    5. compiler.exe console Prolog project, demonstrates transformation

    of Prolog-termal data in different forms.

    47

  • 7/31/2019 Prolog Textbook 1

    48/53

    9 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 ef-fectively parsed by performing unification with templates correspondingto 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 parsersand compilers as well as other programs developing context-free lan-

    guages.In conclusion one can say that, integrated complex Qt+Prolog seems to

    be useful in educational process. First, it requires to know only StandardProlog, Standard C++, and base level of Qt programming system, whichexist in very stable versions and therefore are suitable for educational aims.Programming in Prolog with capable graphic interface forces increasing in-terest of students to this language. Further, very powerful Prolog-termaldata type used in this project is, in fact, equivalent to XML language. Know-ing deep possibilities available for this data type is useful in studying pro-gramming. Finally, Prolog programming language itself is very appropriateto write programs of compilers, parsers, and language interfaces for software.This also makes it useful in educational process.

    48

  • 7/31/2019 Prolog Textbook 1

    49/53

    10 Appendix: Simple built-in predicates

    Notice that a plenty of predicates, operations and special possibilities areavailable 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 objectsXY --- greater 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

  • 7/31/2019 Prolog Textbook 1

    50/53

    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 thefollowing: write("first-line\nsecond-line")

    50

  • 7/31/2019 Prolog Textbook 1

    51/53

    11 References

    1. Textbook: Turbo Prolog 2.0, Materials originally distributed withTurbo Prolog 2.0 package, 1988, 384p.

    2. Electronic Textbook: Visual Prolog Version 5.0 (Languagetutorial), Prolog Development Center, Copenhagen, Denmark, A/S,(c) Copyright 19861997, 479p.

    3. Daniel Diaz. GNU Prolog. A Native Prolog Compiler with ConstraintSolving over Finite Domains. Edition 1.7, for GNU Prolog version1.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 Human-Computer 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, SpringerVerlag, BerlinHeidelbergNew York, 1989, 340p.

    7. I. Bratko, Prolog Programming for artificail intelligence, Sec-ond edition, Wokingham, UK, Addison-Wesley, 1990, 559p.

    8. John Hopcroft, Rajeev Motwani, Jeffry Ullman. Introductionto Automata, Theory, Languages, and Computations. Addison WesleyPublishing Company, 2001, 528 p.

    9. L. Sterling, and E. Shapiro, The Art of Prolog, Cambridge, Mas-sachisets, 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, Sprin-ger Verlag, BerlinHeidelbergNew York, 1986, 437p.

    51

  • 7/31/2019 Prolog Textbook 1

    52/53

    Contents1 Introduction in Formal Logic 1

    1.1 Propositional logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.2 Propositional (elementary logical) variables . . . . . . . . . . . . . . . . . . . . 21.3 Propositional operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.4 Truth tables for logical operations . . . . . . . . . . . . . . . . . . . . . . . . . 2

    1.5 Propositional formulas (recursive definition) . . . . . . . . . . . . . . . . . . . 31.6 Priority order for operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.7 Truth tables for formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.8 Types of formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.9 Horn formulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.10 Alternative denotations for logical operations . . . . . . . . . . . . . . . . . . . 51.11 A lgebraic systems shortly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.12 Cartesian power of a set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.13 Predicates, functions, and constants . . . . . . . . . . . . . . . . . . . . . . . . 71.14 Nulary predicates as propositional variables . . . . . . . . . . . . . . . . . . . . 81.15 Nulary functions as constant symbols . . . . . . . . . . . . . . . . . . . . . . . 91.16 Algebraic systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.17 Predicate logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.18 Signature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.19 Terms and formulas of Predicate logic . . . . . . . . . . . . . . . . . . . . . . . 11

    1.20 Some useful rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.21 Propositional variables in Predicate logic . . . . . . . . . . . . . . . . . . . . . 131.22 Horn formulas in Predicate logic . . . . . . . . . . . . . . . . . . . . . . . . . . 141.23 Formal system Predicate Calculus . . . . . . . . . . . . . . . . . . . . . . . . . 14

    2 Available Prolog Versions 162.1 Main versions and levels of Prolog . . . . . . . . . . . . . . . . . . . . . . . . . 162.2 Other dialects of Prolog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172.3 A few general notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

    3 Grammar of Pure Prolog 193.1 General structure of a Prolog program . . . . . . . . . . . . . . . . . . . . . . . 193.2 Signature symbols in Prolog program . . . . . . . . . . . . . . . . . . . . . . . 203.3 An anonymous variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.4 How Prolog determines signature . . . . . . . . . . . . . . . . . . . . . . . . . . 213.5 The same predicate name for different arities . . . . . . . . . . . . . . . . . . . 223.6 Facts and rules in clause section . . . . . . . . . . . . . . . . . . . . . . . . . . 233.7 Nulary predicates as Boolean variables . . . . . . . . . . . . . . . . . . . . . . 233.8 Two ways to define a constant in Prolog . . . . . . . . . . . . . . . . . . . . . . 233.9 Demonstration of Prolog programs . . . . . . . . . . . . . . . . . . . . . . . . . 24

    4 Unification and Backtracking 264.1 General scheme of unification . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.2 Unification procedure in detail . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.3 Unification in the case of an anonymous variable . . . . . . . . . . . . . . . . . 294.4 Backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    5 Essence of Prolog processing 305.1 Query, goals and subgoals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    5.2 Matches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305.3 Search for a solution process . . . . . . . . . . . . . . . . . . . . . . . . . . . 335.4 Particularities in dialog/compiler modes . . . . . . . . . . . . . . . . . . . . . . 345.5 What is a solution? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345.6 Built-in predicate fail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.7 Built-in predicate not . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.8 Built-in predicate cut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365.9 Built-in predicate is as assignment operator . . . . . . . . . . . . . . . . . . 365.10 Processing in Prolog of other built-in predicates . . . . . . . . . . . . . . . . . 36

    6 Lists in Prolog 376.1 Constants and operations over lists . . . . . . . . . . . . . . . . . . . . . . . . 376.2 Unification for lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    7 Prologs terms as universal data type 39

    7.1 Prolog-termal data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397.2 Lists as Prolog-termal data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407.3 Operations with Prolog-termal data type . . . . . . . . . . . . . . . . . . . . . 407.4 Input terms with predicate read . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    52

  • 7/31/2019 Prolog Textbook 1

    53/53

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

    8 Prolog in conjunction with Qt graphic 458.1 Integration Qt+Prolog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458.2 Available demonstrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

    9 Summary 48

    10 Appendix: Simple built-in predicates 49

    11 References 51