You are on page 1of 18
Hol \ Secta,) YJ & bevel X2) We Cy,z Ere 104 Mert xX) f= person Cx) =) big animal CX) i= __alephant (x) big.cx} 2) | hosachla Cx) = Pesent CX, ¥) «for ot X-ant¥ yi Xd ’ Foto hand Yih Xba as paper 5) 4. Eon, X Ihas_a Chilol” rf ou XX hasig. childs ih the Dow Y pur that iy _parunie AY Li0 i =? 7 Abe Ary Fh fem alo Cor) A paranr 0% y) > natteas_ C0 YJ] {24 Af at penal ond POkent her KX Yd Mother. - U Sn Vaeks mnolitet CH io fearale 9, pana 5.4.1. The database ‘The database is a set of procedures uniquely identified by their predicate indicator. It contains all the user-defined procedures’ and the system procedures called built-in predicates. A sequence of clause-terms is associated with each user-defined procedure whose order corresponds to the order in which the clauses have been input. The final ordering of the clauses is implementation defined. Ina database all the clauses are well-formed and transformed i.e. all variables X in the position ofa predicate in the body of the clauses have been replaced by call(X) and all the facts also have the form of a rule whose body is true. Thus all the clauses in a database have the form ofa rule. In a database every procedure is either dynamic or static. A procedure is static by default = clauses cannot be modified. A procedure may be declared “dynamic” using directives ina ‘olegtext Al the built-in predicates are static, Every procedure is public or private and cannot be tl the built-in predicates are private. All the dynamic user-defined procedures are public. ane re ness procedures may be public and can be inspected using the built-in predicate . Static user-defined procedures are private by default. 28 Ply 5.4.2 Sources and Sinks rms) from a source or output results to S tO a sink data (called read-te al, or other implementation defined possi Sstbility [A program ean input Prolog c ‘The source/sinks Way be a file, the user's termini i m sor, Each of them 1s associated with a finite or potentially infinite sequen oted “logically” by streams. It is spocifch n ‘das ited by the proces yaracters. The Sources and sinks are den’ nt ground term (a handle) th the stream). of bytes or chi an implementation depender hat gets instantiated on opening the are alias (a name given by the user f0 Steam 5.4.3 Flags A flag is an atom which is associated with a value that is either im| i aton r plementation define srliable by the user. Flags are parameters, specifying for istariple haw the execution rat rN react if called procedure does not exist (flag unknown) or what the maximal intern Value is (flag max integer). 5.4.4 Operator and Character Conversion Tables Two tables are also global parameters: thi - d ; the operator table and the chi version ta t e character convei The character conversion table associates with some characters of the Extended Character Se 7 one. char atoms to which they may be converted by inputting terms. 5.5.1 Ground Queries ‘Quenes. goals. and terms where variables do not occur are called as ground. For « snother{secta_ geeta) is ground. This query is called a ground query because it consist ‘only of wicntifiers as parameters to the predicate. When a ground query is posed we expect 2 answer In response to the query the Prolog system scans the program looking for a rule ‘whack matches the query. When Prolog tries to deduce a query it begins by searching for the ruls with beads which match the predicate of the query. This search is always done from top to bottom ‘so order of definition does matter. A match is found if the Parameters to the query are identical those of the head of a rule. So to determine whether a query is true, the Prolog system must determine whether cach atom in the query is true. 5.5.2 Non-Ground Queries The queries can also have variables as parameters: such queries are called non-ground queries. For example, the query mother(seeta, X) is non-ground. The computation of a 100 ground query G (with variables) finds all possible solutions of G with respect to a program As a result of computation, all possible values of the variables involved in query G are generated and displayed. Vy ATT Te SY prerarming in Prolog ample: Consider a simple Prolog program 1. father(atul, amit), + father(ram, sham), + father(sham, atul), + father(amit, amanat) + father(amit, rohit), ‘Solution: Ground query: 2 : i i BNG 2- father(atul, amit). Non-ground query: ?-father(sham, X). Ans: X = atul 5.5.3 Query Execution at Compilation Time The queries that can be included in a program itself are called as directives, and when Prolog encounters a directive, it immediately triés to satisfy the goals in the directive. A directive is a rule without a head i.e. a term or a Conjunction of terms with a “:-” symbol to its left-hand side as: ++ predicates_to_execute. Ifa directive is to be executed once the program is completely loaded, it must occur at the end of the file. More generally, you may put any query directly into a program file, which will cause it to be executed whenever you consult that file. Say, for instance, your program contains the following line: 7 :- write(’Hello, have a beautiful day!’). Then every time you consult the file, this will cause the goal after (:-) to be executed and will first display the message and then load the prolog program as: Hello, have a beautiful day! my-file.p! compiled, 0.00 sec, 224 bytes. Yes ram for the first clause To execute a goal, Prolog searches forward from the beginning of the prog! t Whose head matches the goal; this matching process is called as unification. The matching assignment is applied to both the goal and a copy of the clause by replacing varial bles with their binding value. fas) Symbolic Logic and, The literals in the body of the instantiated clause (if any) are then executed in turn, from fo night. If at any time the system fails to find a match for a goal, it backtracks, that is, it Tejects i: most recently activated clause, undoing any substitutions made by applying the ASSiznmen engendered by the match to the head of the clause, Next it reconsiders the original goal that Activate the rejected clause, and tries to find another clause whose head also matches the goal. When find, alternative clauses, Prolog always works from the top of the program to the bottom, trying catlg clauses first. Prolog contains three basic control strategies: + Forward movement + Matching/Unification + Backward movement/Backtracking 5.6.1 Forward Movement Choose a rule by searching sequentially in the program from top to bottom whose head matches With the goal with possible unifier. Remember the position ofthe matched rule, Join the rule bs, in front of the sequence of sub goals to be solved. Repeat until either goal is satisfied or is fle 5.6.2 Matching/Unification Unification is the process of matching or finding the Most General Unifier (MGU). Constant matches with the same: constant and a variable matches with any constant and becomes instantiated A variable can also matches with another variable. For example, love(X, sita) and love(X, Y) can be unified with love(ram, sita), with MGU as {X/ram} and {X/ram, Y/sita} respectively. Also the statement love(ram, sita) does not unify with love(sita,-ram), love(X, rahul), love(johni, X) etc 5.6.3 ‘Backward Movement/Backtracking Backtracking in Prolog takes place in two situations, First situation is when a sub goal fails and other is when if the last sub goal succeeds, then to find alternative solutions. Backtracking is of two types: + Shallow Backtracking: It occurs when the last sub goal succeeds. To find alternative solution, the last sub goal is tried to be unified with another rule (if any) from the last place marker. - Deep Backtracking: It occurs as a result of their failure as shallow in which it backtracks 0 Previous sub goal. It removes the bindings generated by the sub goals introduced duc to the current sub goal and then looks for an alternative rule (with the head matching goal, if a) after the place marker for previous sub goals. Consider the following query to explain both types of backtracking more clearly: 2. Gl, ..., Gi-l, Gi, ..., Gn to satisly Suppose at some point we have satisfied Gl... Gi with some common bindings and have vib sub goal Gi, Choose a rule by searching sequentially from top to bottom whose head ara "sl sub goal Gi with some bindings. Ifthe sub goal Gi is satisfied, then proceed further to satisf¥ y \ \ i ‘ ‘ at ee | ) and continu the Process in forward direction till we reach Gn else backtrack to Gi-1, Remove the bindings created carlicr duc to Gi-1 and try to satisfy Gi-1 again by using an alternative rule, if it exists, from last place marker of Gi-1. If sub goal Gi-I is satisfied then move forward to else backtrack to Gi-2. The process of backtracking continues till we reach G1, If G1 fails for all possible dofinitions, then entire query fails. In case, if entire conjunction of sub goals succeed, then the solution is displayed and in order to find alternative solution, the sub goal Gn is tried to be satisfied with alternative definition, if it exist, after last place marker (Shallow backtracking) of Gn. Otherwise it backtracks to previous sub goal Gn-l (Deep backtracking). Repeat the process till all possible solutions are generated. (5.7 ERRORS IN PROLOG | ‘System Error: There may be a system error at any stage of execution. The conditions in which there is a system error and the action taken by a processor after a system error are implementation dependent. The corresponding error term is system-error. Resource Error: There is a resource error at any stage of execution when the processor has insufficient resources to complete execution. The corresponding crror-term is resource_crror (Resource) where Resource is an implementation dependent atom. ‘5.8 IMPROVING PROGRAMS | Programs are normally written once and then are possibly read and modified several times. A major concer of the programmer should be to write clear and legible code. It helps enormously with the maintenance and debugging of programs. Before programming, it is essential to have a good formulation and decomposition of the problem. The program construction should then reflect the logical structure of the solution. A key to the good construction of a program is to name the things properly. Cryptic predicates or variable names, such as snuiprdc, dsea_codde, Xd, Yan, and so on, should be prohibited. It is not rare that one starts with a predicate name and changes it in the course of the development to reflect a better description of the solution. Since Prolog code is compact, the code of a clause should be short to remain casy to understand, especially with recursive programs. If necessary, the programmer should decompose a clause into smaller sub clauses. The following are some general rules that sometimes are difficult to Tespect when speed matters the most. + Group all clauses of a predicate together in program file. + Be careful using same predicate identifier with different number of arguments. + Never put more than one clause per line. * For large rules, put one goal per line as: — grandfather(X,Y) - — male(X), Symbolic Logic ang , * — parent(X. — parent(Z, Y). There are several aspects of efficiency such as execution time and space requireme Another aspect is the time needed by the programmer to develop the program With respect to the execution efficiency; executing a compiled program is generall than interpreting the program. Therefore, if the Prolog system contains both an ii compiler, then the compiler should be used if efficiency is critical, Ufa program suffers from inefficiency then it can often be radically improved by improy ing y, algorithm itself. However, to do this, the procedural aspects of the Program have to be Studied A simple way of improving the execution efficiency is to find a better ordering of Clauses of Procedures, and of goals in the bodies of procedures. Teas for improving the efficiency of a program usually come from a deeper understanding of the problem. A more efficient algorithm can, in Seneral, result from improvements of v0 kind, * Improving search efficiency by avoiding unnecessary backtracking and stopping the exceutizg of useless alternatives as soon as possible. Using more suitable data structures to Tepresent objects in the program, so that the. ‘Operations on objects can be implemented more efficiently. IS OF rca, Iv more ef; interpreter ai This section describes how Prolog clauses (ie. facts, rules, and queries) can be translated into first order logic formulas. The following points can be considered while translating Prolog clauses into for formulas:- : * Prolog predicates correspond to predicate symbols in logic. * Terms inside the predicates correspond to functional terms appearing as arguments of logic Predicates. These terms are made up of constants (Prolog atoms), variables (Prolog variables). and function symbols (Prolog functors). * Allvariables ina Prolog clause are implicitly universally quantified i.e, every variable could be instantiated with any Prolog term. Given this mapping from Prolog predicates to atomic first-order formulas the translation of entire Prolog clauses is straightforward. Recall that (:-) can be read as “if”, i.e. as an implication from right to left; and that the comma separating sub goals in a clause constitutes a conjunction. Whet translating a clause, for every variable X appearing in the clause we have to put Wx in front of the resulting formula. The universal quantification implicitly inherent in Prolog programs has to be made explicit when writing logic formulas. Before summarizing the translation process more formally. Consider the following little program consisting of two facts and two rules. programming in Prolog bigger(elephant, dog). bigger(dog, cat). is_bigger(X, Y) :- bigger(X, Y), is_bigger(X, Y) :- bigger(X, Z), is_bigger(Z, Y). ‘Translating this into a set of first-order logic formulas yields: + {bigger(elephant, dog), + bigger(dog, cat), + Vx Vy (bigger(x, y) — is bigger(x, y)), + Vx Vy Vz (bigger(x, z) A is bigger(z, y) is bigger(x, y)) } Note how the head of a rule is rewritten as the consequent of an implication. Also note that each clause has to be quantified independently. This corresponds to the fact that variables from distinct clauses are independent from each other, even if they've been given the same name, For example the X in the first rule has nothing to do with the X in the second one. In fact, we could ix Raame X to, say, “Lion” throughout the first but not the second rule, this would not affect the behavior of the program. In logic, this is known as the renaming of bound variables. If several clauses form a program, that program corresponds to a set of formulas and each of the clauses corresponds to exactly one of the formulas in that set. Of course, we can also translate single clause. For example, consider the following query ots , bigger(clephant, X), is_bigger(X, cat). It corresponds to the following first-order formula: -.__ Vx (is bigger(elephant, x) “is bigger(x, cat) > 1) To suiimarize, when translating a Prolog program (i.e. a sequence of clauses) into a set of logic ost formulas you have to carry out the following steps: is) + Every Prolog predicate is mapped to an atomic first-order logic formula (syntactically, both are exactly the same: you.can just rewrite them without making arly changes). al + Commas separating sub-goals correspond to conjunctions in logic (i.e. you have to replace every comma between two'predicates by a A in the formula). sit + Prolog rules are mapped to implications, where the rule body is the antecedent and the rule of head the consequent (i. rewrite :- as —» and change the order of head and body) et * Queries are mapped to implications, where the body of the query is the antecedent and the pl consequent is ? (i.e. rewrite :- or 2- as >, which is put after the translation of the body and of followed by L). 0° + Each variable occurring in a clause has to be universally quantified in the formula (i.e. write Vx in front of the whole formula for each variable X). Symbolic Logic ang D GLARATIVE AND PROCEDURAL MEANING OF PROLOG PROGRAtig Consider the following example: prqn The declarative reading of this rule is as: + Pis true if Q and R are true. + From Qand R follows P. The procedural eading specifies how the Prolog answers questions. So, the procedural raj, this rule is as: Ry + To solve problem P, first solve sub-problem Q, then solve sub-problem R. + To satisfy P, first satisfy Q, and then R. ‘When a program does not do whatever expected from the program, this means that your factsorni, are incorrect. But finding out which ones are wrong can be difficult. To isolate and remove then programmer uses a debugger which enables the programmers to trace the step by step goal event and unification. It is very easy to locate an error in a part of the program (or a module) than int: program as a whole, Therefore, a good principle of debugging is to start by testing smaller unis the program, and when these can be trusted, start testing bigger modules or the whole program. Debugging of Prolog programs is done far more efficiently than in most other programnis languages. Prolog implementations usually provide special debugging methods which uss = execution model describing the control flow of a goal. These are facilitated in the way that any pe: of the program can be directly invoked by a proper question to the Prolog system. The basis for debugging is tracing. “Tracing a goal” means that the information regarding: | goal’s satisfaction is displayed during the execution. The built-in predicate “trace” launches & debugger and “notrace” stops it. While tracing is on, you can issue any query, and Prolog wills you through its logical process. This information includes the: Entry information: The predicate name and the values of arguments when the g0t!* invoked. Exit information: In the case of success, the values of arguments that satisfy he 2°) otherwise an indication of failure. Re-entry information: Invocation of the same goal caused by backtracking. race information for all the sub goals of a particular oo 3 y 08 helpful ca Between entry and exit, the ti obtained. So we can trace the execution of our question all the way down to the lowe: until facts are encountered. It’s hard to follow until you see it a few times, but it’s very only for debugging, but also for learning about how Prolog works. ming in Prolog program aii 149 \ | qhe following figure shows the execution model of a Prolog program: qe it 1 cat —_, | |——> Exit PO) | Fail. <—___| -|*—— Redo * Figure 5.3, tris pictured as a box representing the goal predicate with four ports: + Call port: The Call port corresponds to the invocation of the goal ie. it is the place where | the control goes in the first attempt to prove a goal. ie Exit port: If the goal is satisfied, the execution comes out through the Exit port with a possible unification i.e. it is the place where control comes out when the goal succeeds. + Fail port: If the goal fails, the execution exits through the Fail port i.e. it is the place where control comes out when the goal fails. + Redo: Finally, if a subsequent goal fails and Prolog backtracks to try another clause of the predicate, the execution re-enters the box through the Redo i.e. it is the place where control goes in on subsequent attempts to prove a goal. Asan example, let us trace the following program: bk © i ¢ + p(X) = 4X), 1%). + a@). + qt). Ft a. a + £0: . a's You will frequently want to see what Prolog does while itis evaluating your programs. This is often necessary when you are trying to track down bugs in your program. ‘The tracing can be invoked with the “trace” command as: i , / 2- trace. Itwill display the message as: + The debugger will first creep, * yes ! * {trace} “12 The “yes” shown after the “trace command is properly executed. showing everything (trace) / » command is displayed by the Prolog compiler that “trace” i } ™ hy, New we can pive the query to be fraged Mor example, (0 (AGE HE eXeeHtign of following command te piven My hp) ‘Vho Profog will show the rosnll of traee Am «© Call CY pt S16)? creep © Call CH) qh G16) ? creep © Lit CY) gta)? ereep © Call (8) ra)? ervey © Foil (8) (a) ? ereep * Redo (4) q(_ S16) ? ereop © Byet (8) q(b) ? ereep + Call (8) r(b) ? creep it (8) e(b) ? creep a (7) p(b) ? creep: + [te Note that you have to press “Return” at the question marks after the trace output, but “Semicole after the normal results output, Starting at the top of the trace, note that Prolog uses its own inte labels to represent the variables, ‘You can alvo trace the particular query by putting the trace command before the query as cs In this case the tracing stays on for that one query only, Predicates may be individually 19 enabling cach call or exit involving the predicate to be displayed on the terminal with the curt valucs of its arguments, After seporting, an event the program waits for one of a number of actions by the user Thy several useful options to apply (mostly single character commands): + © (Creep) (also carriage return) = take one proof step to the next port, + 9 (Skip) = jump to the next exit port (Succeed or Fail) from this invocal predicate, * a (Abort) ~ drop out of execution and return to the Prolog prompt, +n (Nodebug) ~ switch off tracing and proceed as for normal execution, ‘ace, query. yrs? tion of + (Retry) ~ go back to the call whose invocation number is giver + 7 (Help) ~ print out a fist of available commands. a mal gerd et i preva Prolog ote that some commands (For example: Skip) only put ports) amd 0 will not work at others NP) only make sense at some ports (for example TS, tailed tracing may tu oh a deta mg May tum out to be impractical due to the excessive amount of tracing, tion: therefore, the user o: m inform an specify selecti x it fnootaisTS: Pecify selective tracing. There are two selection ‘| Suppress tracing information beyond a certain level + Trace only some specified subset of predicates, and not all of them. iniarge programs, itis often not feasible to trace all the way through to an error. Often, we have a shar idea of which predicate is going wrong, so we wantto go straight oi even in small programs. odo tis, We Use SPY Points i.e. we can set the debugger to wait nti it encounters a spy point in theprogram, and then it will switch on, Such debugging methods are activated by system-dependent ‘built-in predicates. - + spy(B): Specifies that a predicate P be traced. This is used when we are particularly interested in the named predicate and want to avoid tracing information from other goals (cither above ot below the level of a call of P). Several predicates can be simultaneously active for spying. / 7 + nospy(P): Stops spying P. ‘Tracing beyond a certain depth can be suppressed by special commands during execution. There may be several other debugging commands available, such as returning to a previous point of execution. ‘After such a return we can, for example, repeat the execution at a greater detail of tracing. 5.11.1 Examples of Tracing Evample 1: Consider the following database: + child_of(rohini, karan). + child_of{rohini, arjun). + Toves(N1, N2) :- child_of(N2, NI). Here’s a trace of the above database: _ 2- trace, loves(arjun, rohini). Call: (8) loves(arjun, rohini) ? Call: (9) child_oftrohini, arjun) ? Exit: (9) child_oftrohini, arjun) ? Exit: (8) loves(arjun, rohini) ? Example 2: Consider the following database: + thief{john). * likes(mary, food). Symbolic Logie . ang + likes(mary, wine). + likes(john, X) :- likes(X, wine). + may_steal(X, Y) :- thief(X), likes(X, Y). + J* A person may steal something if the person is a thief and he likes the thing +/ dp, The tracing can be done as: + 2+ trace. * The debugger will first creep — showing everything (trace) yes + {trace} + | ?-may_steal(john, X). * Call: (6) may_steal(john, _G495) ? creep * Call: (7) thief(john) ? creep + Ensit: (7) thief(john) ? creep * Call: (7) likes(Gohn, _G495) ? creep * Call: (8) likes(_G495, wine) ? creep + Exit: (8) likes(mary, wine) ? creep Exit: (7) likes(john, mary) ? creep xit: (6) may_steal(john, mary) ? creep + X=mary; + Redo: (8) likes(_G808, wine) ? creep * Call: (9) likes(wine, wine) ? creep + Fail: (9) likes(wine, wine) ? creep * Fail: (8) likes(_G808, wine) ? creep * Fail: (7) likes(john, _G808) ? creep Fail: (6) may_steal(john, _G808) ? creep * False. Example 3: Consider the following database: * male(harry), * female(rohini), Parent(atul, amit), Parent(rohini, amit), Parent(amit, hary), Parent(amit, sham), programming in Prolog ee + grandmother(GM, C) :- mother(GM, P), parent(P « mother(M,C) :- female(M), parent(Mt, o (P, C). Prolog will then output to the screen the se F goal: ‘quence of steps it carries out in executing the following, + 2-grandmother(rohini, Who), + Call: (6) grandmother(rohini, _G396) ? creep + Call: (7) mother(rohini, _G450) 2 creep + Call: (8) female(rohini) ? creep + Exit: (8) female(rohiini) ? creep + Call: (8) parent(rohini, _G450) ? creep + Exit: (8) parent(rohini, amit) ? creep + Exit: (7) mother(rohini, amit) ? creep + Call: (7) parent(amit, _G396) ? creep + Exit: (7) parent(amit, harry) ? creep + Exit: (6) grandmother(rohini, harry) ? creep + Who = harry + Yes Example 4: Consider the following database: + wrote(rahul, matrix). + wrote(john, lunar): + wrote(roger, recursion). + wrote(harman, maths). wrote(mukul, computer). + wrote(kamal, computer). + book(maths). book(computer). © program(lunar). program(recursion). program(matrix). author(Person) :~ book(Book), wrote(Person, Book), authot_of(Person, Book) :~ book(Book), wrote(Person, Book). We will trace through the operation of the system for the above database. We begin by executing the goal: 2- author_of(mukul, What). Prol7og finds a clause in its database matching clause is: author_of(Person, Book) :- book(Book), wrote(Person, Book), The head of this clause matches the goal under the bindings: Symbol Logic anys Py whose head matches the goal. In this Case, th, » the Oa Person = mukul, Book = What. Under these bindings, the body of the rule becomes: book(What), wrote(mukul, What). Prolog activates the clause taking this conjunction on as its new goal, executing the Conjuny one by one, and working from the left to the right. ms Executing “book(What)” requires finding a clause whose head matches it. But in this case th two such clauses, namely the unit clauses: + book(maths) and * book(computer). rear, When faced with several clauses to choose from, Prolog chooses the textually earliest one that not been considered in satisfying this goal; in this case, none have been considered so the f matching clause “book(maths)” is chosen, which matches the goal “book(What)” under the binding «What = maths”. Under this binding, the second conjunct is “wrote(mulcul, maths)” and thi, decom: the next goal. However, no clause head matches this goal, so the goal fails. Prolog backtracks to its ke choice among altemative clauses. In this case, the choice was between the two unit clauses matching book(What). This time, in satisfying the goal, the next matching clause is chosen, namely: book(computer). The second conjunct then becomes: wrote(mukul, computer). This goal matches the identical unit clause in the database, Thus we have satisfied all of tht conjunets in the antecedent of the “author_of” clause, thereby satisfying the original gol isl Perusing the bindings that were necessary to satisfy the goal, we note that the variable “What” the original goal was bound to computer, which is therefore reported as: What = computer. ‘the The following trace of the above database may clarify the Prolog trace facility. Note especially changing instantiation of the variables during the trace. + 2-trace, * Debug mode switched on, a programming in Prolog + yes 2- author_of(mukul, What), 0 Call : author_of(tmukul, What) 1 Call : book(What) 1 Exit : book(maths) 1 Call : wrote(mukul, maths) (3) 1 Fail : wrote(mukul, maths) (2).1 Redo : book(maths) (2) 1 Exit : book(computer) 1 Call : wrote(mukul, computer) (4) 1 Exit: wrote(mukul, computer) O Exit : author_of{mukul, computer) + What = computer * yes Note that the exit lines leading to the'final proof contain the same information as a proof tree for the goal. This example shows that although te ordering of literals within a clause does not affect the ; logical meaning of the clause as a definition of a relation, it can have far-reaching effects in terms of the control flow of the program. That is, although Prolog can be viewed as a-subset of a logical language, we cannot forget that it is still a programming language, and issues of control are still important.

You might also like