You are on page 1of 19
ASX aA aoen5 Cc Programming in Prolog GiURE OF A PROLOG PROGRAM ‘A Prolog program is @ set of specifications in the first-order predicate calculus describing the shjects and relations in a program domain, The programming in Prolog means describing the world; sing the Prolog programs means asking the questions about the previously described world. Prolog program is a finite sequence of clauses. Informally, we can define Prolog program to be a set of facts and rules. Programming in Prolog is very different from programming in a traditional procedural nguage such as Pascal. In Prolog, you don’t say how the program will work. However, Pp nlog program can be regarded as a relational database that contains facts as well as rules and is, stored as a text file (*.pl). It is very easy to add and remove information from the database, and to pose sophisticated queries. Prolog is not at all hard about the layout of a program. The only requirement is that there must be a “space” or “newline” character after the full-stop at the end of each clause, The following are the various sections of a Prolog program: Comment Section: Program comments should be given in the first place to explain what the program is about and how to use it, and then the details of the other programming are given. The main purpose of comments is to enable the user to use the program, to understand it and possibly to ‘modify it. Comments should describe in the shortest possible form. Explanation of details that are obvious from the program code itself is only a needless burden to the program. Long passages of comments should precede the code they refer to, while short comments should be mixed together fe code itself. Information that should, in general, be included in comments comprises the wing * What the program does? * Howit is used? For example; what goal is to be invoked and what are the expected results. Examples of using the progiam. * What are the top-level predicates? How the main concepts (objects) can be represented? 125 QC OEE ES el y Symbolic Logic ang Proly + Execution time and memory requirements of the program. time and m rel he prog) Ne a gram? What are the limitations of the program ae Are there any special systemdependent features us aegis i What is the meaning of the predicates in the program 7 arguments are “input” and which are “output”, if know! ith ementati ils. Algorithmic and implementation detail a ; ‘The Comment in Prolog are preceded by percentage symbol ‘%' for a single ne and canbe ene within /* and-*/ for- multiple lines, You can write the comment in any p: Program, Fes example: hich /* If we place our comments between these symbols we can put our comments over several lines */ The single line comment can be given as: ‘% We can use this symbol for a single line comment, Everything written in the comment will be ignored by Prolog. The use of the % sign to indicate a.comment is generally safer because the comment is terminated automatically by an end of line The danger is in using the multiline comment in which the programmer might forget to close an opened comment which normally has disastrous consequences. On the positive side, it can be used to.comment out chunks of code during the program development. Domains Section: The domains declarations are used to introduce the data structures ‘elated to the program i.e. we define the legal values for any type that is not defined a. standard type. Predicates Section: All user ‘defined are introduced within the predicates secti PredicateName(argl, arg2,........ ‘Where the “PredicateName” includes the name of i ~ 2 : the predicate, and the argument secti includes the builtin standard domains such as intesee string or i 7 inst reat elude user defined domains introduced within the demain sesticy ome oe Sting oF it may in The predicates can be added and tested se i i it possible i parately in a Pro it poss to incrementally develop any application ee etbea eh rake? Clauses Section: The Clauses section inc] A clause can run over more than one line o terminated by a dot character. ludes all the facts and rules that make up the progran r there may be several on the same line. A claus? programming in Prolog §@BUSTARTING PROLOG ‘The set of facts and rules of a file makes up a Prolog tex! : : 2 . 8 text Or program, Starting the Pi tem usually straight forward, but the precise details will vary from one version co anol es aaa Prolog programming you may follow the following steps: ees 5.2.1 Writing and Saving a Prolog Program In most Se of oe 4 program is created externally to the Prolog system, using a text-editor pI : ie - part of the operating system. Technically, you don’t create a Prolog program, ve a fate ee ie prolog program contains the database having knowledge and ol e world which is called as “logic base”. After writing th gi cave it into a file, with a “.pI” as extension, ee ea §.2.2 Opening the Prolog nce the program is written, we can open the Prolog, which will generally produce a number of lines of headings followed by a line containing (?-) as shown in the following figure: Bateseniages) bug Tibrary(vin_nenu) compiled into win_nenu 0.00 2 librery(svichooks) compiled into poa_svi chooks 0.00 sec. Geldone to SUl-Prolog (itulti-threaded. 32 Bits. Version $10.1) Coppeight (c)_ 1990-2010 University of ansterdan, VU Rasterdam, SOP ibe comes vith ABSOLUTELY NO VARRANTY, This is free software, Jou ae velcone to Fedistribute it under certain conditions Pieske visit http://evu.svi-prolog.org for details | For help. use ?- help(Topic). or ?- anropos(Word) | te Figure 5.4 Symbolic Logic and pry "Og the Prolog system is ready for the user to im the (2-) symbol, we just type in the a ypt which indicates that ; t be terminated by a full stop. a ‘This is the system prom a sequence of one or more goals/queries. We don query followed by () a fall stop i.e, the Prolog 5.2.3 Executing a Prolog Program i ‘evel i database. Submitting a query A query is a request to prove or retrieve information from the query m t the statement(s) implied by the query can be made true Dna Jy for'such a proof is usually referred to as gog) asking Prolog to try to prove that the right variable instantiations are made. The searc’ execution: When we pose @ query to Prolog, we are setting up 4 goal for Prolog to try to satis, Once a query is entered, prolog will check if it’s true, false or having any value, depending upon th: relations given in the database: Jf Prolog is able to find facts and rules that allow it to conclude tha, fied’ if goal cannot be satisfied, we say that it ‘file the goal is true, we say that the goal is ‘satis cesses queries, searching the database to find out whether the queryis The PROLOG interpreter pro. a logical consequence of ‘the database of specifications, as shown in the following figure: Store Query == Retrieve __, Answer > Figure 5.2 fo run and use the informatic we have to load the p ; ion contained i i nfo a ed ina Program we have to load the program in memoy 2- consult(yourfilename). The entire content of i Mis ta tho progritt th aut is then stored in the memory of Prolog. If there are any syntit reported to the user at this stage. The style of the error report vate between implementations : of the 1: fe displayed at the user’s terminal. language, but it is usual that the text of faulty clauses When the program has bi een | e loaded without error messages, the user is prompted 10 {7° int goals or questions related to the d : latabase described i top goes down sequentially to th lescribed in the pro; from edit your program file to cor bottom of the clauses a ram, The Prolog then sm want x ae rect something, you have t ion to find out the result. IFyo" rou can also load several i " e to consult it agaii files called as filel, file2 fl a Ie in Prolog. For example, if we fethe att? , file2, fle3, filed can be loaded ints c, if we write the following co™™ to the memory of the Prolog: ~ y ¢ i} i ( j programming in Prolog 2 consult [fi s file2, filed, filed]. pROLOG offers an abbreviation for such a ela requited file names may be specified in alist: 2 [fillel, .... , filen]. ‘You can see what is consulted by typing the command: 2 lis .c, without using the ‘consult’ clause; only the ing. To exit from Prolog, type: 2- halt. or press CTRL+D Ifthe principal functor of a goal is a built-in predicate the associated action is executed whilst the goal is being satisfied. For example, as far as goal exceution is concerned the following predicate vill simply succeed, but at the same time it will also print the words “Hello World” on the screen: 2. write(’Hello World’) Sometimes there is more than one way of satisfying the current goal. Prolog chooses the first possibilty as determined by the order of clauses in a program If at some point Prolog fails to prove acertain sub goal, the system can go back and try.an alternative way of. ‘executing the previous goal. This process is known.as. backtracking, When the execution is complete the program becomes ready for another directive. However, one may interrupt the normal exccution of a directive by typing CTRL+C. This interrupt signal has the effect of terminating the execution of the command, Prolog will then respond with a prompt. Execution may also be terminated if the program runs out of stack space!'This usually indicates an error in your program. ‘The simple queries have one goal to prove, while the compound queries are a conjunction of two or more goals as: 2- G1, G2, G3, ..., Gn. Prolog proves the whole query by proving that all the goals GI... Gn are true. (SSUDEFINING R NS | The Prolog programming is all about writing knowledge databases (which is the collection of facts and rules), We can start with some simple knowledge databases which are not just the best way of. leaming Prolog, but is the only way. The Prolog system enables a computer to be used as a storchouse of facts and rules, and it provides ways to make inferences, Computer programming in Prolog consists of a. * Declaring some facts about objects and their relationships, * Defining some rules about objects and their relationships, * Asking questions about objects and their relationships. Row: | Symbolic Logic ang 1% " 5.3.1 Knowledge Database 1 (Defining Relations by facts) -1 (KDBI) is simply a collection of facts. As the name suggests, af, | eee oa ee an identifier followed by constant. In other words, the Prolog can express the relationships between objects. The names of the objects are calles." | arguments and the relation identifier is referred to as a predicate or functor. The facts are Used, state the things that are unconditionally true of the domain-of interest. For example, we cay ¢.° that Seeta, Zeenat, and Sonia are women, and that Zeenat plays guitar, using the following fay. | * woman(seeta). * woman(zeenat). + woman(sonia). + playsGuitar(zeenat). Facts should always begin with a lowercase letter and end with a full stop. The facts themselves | consist of any letter or number combination. The identifier as well as constants should be written lowercase letters. You can’t have a blank space between the functor (the relation name, e.g. woma) and the left parenthesis of the constants. If you have stored the above.program inia file called as:“kdb1.pl” you can start the Prolog interpreter to load the file, and ask questions related to that file. Note that the interpreter prompts us with “?-”, meaning that it is waiting for questions or orden. ‘We tell the interpreter to load.our program by entering: i 2 consult [kdb1.pl]. Now we can.use KDB1 by asking queries about the inforniation contains in KDBI. Prolez recognizes and matches a goal and a fact in the program. Ifa match is found, Prolog responds witt “yes” to indicate that the goal has been satisfied. If no match is found, the response is “no” which indicates that the goal has failed to be satisfied, Here are some examples: z We can ask Prolog whether “Secta” is a woman by. posing the query as: 2- woman(seeta). So the response to our question will be “yes”, as the fact has proved based on the known fae Prolog searches the database of clauses in order (first-to-last), so the first clause it matches willl® the first one entered in the database, We did not tell Prolog, as in a procedural language, how reach an answer. We rather declare some facts, and let Prolog to search for an answer. Similarly, we can ask whether “Zeenat” plays guitar or not, by giving the following query: 2- playsGuitar(zeenat). ‘i “veg” | Prolog will again answer “yes”, because this is one of the facts in KDB1. However, SupP°* ask whether “Seeta” plays guitar or not: | 2. playsGuitar(seeta). ming in Prolog Program We will gt the answer as “no”. Why? Well, first of all, this is not a fact in KDB1. Mi i y? : 5 joreover, the KDB1 and contains no other information which might help Prolog for trying to aecce wate Sone? aly 8 gitar or not. So Prolog correctly concludes that playsGuitar(Sceta) does nor follow from the KDBI. Here is one more important example, Suppose that we give the query: ?- playsGuitar(monica). ‘Again Prolog answers “no” Why? Well, this query is about a person (Monica) which is not given as a fact in our database, <0 it concludes that playsGuitar(monica) cannot be deduced from the information in KDB1 Now if we give the query such as: 7 2 listensMusic(seeta). ‘The prolog will answer like this: Error: Undefined Procedure listensMusic This is because we have not yet defined any procedure such as “listensMusic(seeta)” in our Knowledge Database-1. Symbols or names representing objects, (such as “seta” or “sonia”) are called as atoms. Atoms are normally strings of letters, digits, or underscore (_), and begin with a lowercase letter. ‘Anatom tan also be a string beginning with an uppercase or lowercase letter or it may include white spaces, but in that case, it must be enclosed between single quotes. Thus ‘Sonia’ or ‘Dilpreet Kaur’ are legal atoms. Prolog does not care about what ‘Sonia’ or “Dilpreet Kaur’ is, rather it only knows the assertions about them. Also if we have the two facts as: + woman(sonia). + woman(‘Sonia’). The Prolog deals differently with these. This is why we language. More complicated facts consist ofa relation and the multiple items that refer to the fact. These items are called arguments, Facts can have arbitrary number of arguments from zero upwards. A general model is shown below: 7 relation(object1, object2, .... objectn). are called as the arguments. all Prolog as a symbolic programming The objects (objectl, object2, .. ., objectn) involved in the relation For example, consider the following fact: likes(seeta, geeta). Here “likes” is termed a functor or a predicate, which has the arity two (as there are two Parameters), Symbolic Logie and bay, 4 Tinks “seeta” and “geeta”. Note that the sem, ‘The above fact says that a relationship “likes” links ‘seeta” and “g aig 1 jon i.c. loves(geeta, seeta) can mean thy i 2 ’s interpretation 1.¢. eC ofthe statements et tothe programmes "The only thing ee seen aie | ara depres ; zi _ eee ele Prolog only oS cusden and Ghat should always be clear and consistent how you intend to i ini i les) 5.3.2 Knowledge Database 2 (Defining Relations by Rule: is in its abstraction mechanism. In Prolog, the ru " mming language is in its al : The real power of any Pree pstraction. A fact can only specify that a tuple of vale cats : moras oe a a ane is a Prolog statement which gives the conditions o ler w P tuples ene vlicate Avuleis a special type of sentence that states the information that is conditional satisfy a predicate. f interest, Rules are used to generate new information from facts, other rules, i? See Note that we don’t explain to Prolog about how to work with these rules, see ae able bat not ours. We just have to supply a logically complete database, and Prolog That’s its problem, but wa fh e, to answer a given question. will take care of deciding which rules to use and when to use, Every rule is divided into two parts by the symbol (:-), the part on the left hand side of the (-) is called the Head of the rule and the part on the right hand side is called as the Body of the rule, Consider the following database namely KDB2.pl: + listensMusic(seeta). + happy(sonia). + playsGuitar(seeta) :~ listens Music(sceta). + playsGuitar(sonia) :- listensMusic(sonia) + listensMusic(sonia) :- happy(sonia). ‘This database contains two facts, listensMusic(seeta) and happy(sonia). The last three items are the rules, It has a predicate on the left, and a sentence on the right separated by the (:-) symbol and is concluded by a period. For example, if we talk about the first rule: * PlaysGuitar(seeta) :- listensMusic(sceta). It says that: i + Sceta plays guitar ifshe listens to music, Or alternately: “ * ‘SflistensMusic(sceta) is true then The second rule says that: * Sonia plays guitar if she listens to music, And the last rule says that: * Sonia listens to musie ifshe is happy, More generally, the (:-) should be read as if" + If the body of the rule is true, then the PlaysGuitar(seeta) is also true. * it: ; or “is implied by”. So generally the rules say that head of the rule is also true. ahs programming in, Prolog if knowledge base contains a nile: + Head + Body. now's tha . \ ‘The Prolog. knows that body follows from the information in the knowledge base. Any number of gubgoals may be in the body of the rule but there c only sh ge is ot alowed Pron ere should be only one goal in the head. For example, + happy(sonia), powerful(sonia) :- rich(sonia).. Now let’s apply some queries rl 2 i « Nowra a q over our ‘kdb2.pI’ file. We will ask Prolog “whether Secta plays 2- playsGuitar(seeta). Prolog will respond as “yes”. Why? Well, although playsGuitar(seeta) is not a fact ex licitly recorded in KDB2 but the KDB2 does contains the rule: ae? + playsGuitar(seeta) ;- listensMusie(seeta). Moreover, KDB2 also contains the fact listensMusie(seeta). Hence Prolog can use modus ponens to deduce playsGuitar(seeta). When a query is made, Prolog searches the clauses in the order that: + Tf the clause is a fact, Prolog tries to match the query directly to it. + [the clause is a rule, Prolog tries to match the query to the rule’s head. If the head matches, ‘then the result state is defined as follows: _— The query matching the head of the rule is deleted from the list of queries. ___ All the terms in the body of the rule become queries themselves, and are added to the list. Rules can call other rules, Our next example shows that Prolog can chain together the rules. Let us suppose that we ask the following query to Prolog: 2- playsGuitar(sonia). Prolog would respond “yes”. Why? Well, using the following fact and rule respectively: + happy(sonia). «+ listensMusic(sonia) = happy(sonia). So it can deduce the new fact listensMusic(sonia) This new fact is not explicitly recorded in the knowledge base, it is only implicitly present (it is inferred knowledge). However, Prolog can then use it just like an explicitly recorded fact. Thus, together with the rule: + playsGuitar(sonia) ~ listensMusic(sonia). Itcan deduce that playsGuitar(sonia) is uc, which is what we asked it. say that any fact produced by an application of modus ponens can beused ing together the applications ‘of modus ponens in this way; Prolog follows from the rules and facts recorded in the _ Summing up we can as input to further rules. By chainit is able to retrieve the information that logically knowledge base. al mo : Symbolic Logic ang TO " The facts and rules contained ina knowledge base are called as clauses. Thus KDB2 contains clauses having three rules and two facts, Another way of looking at KDB2 is to say that it cans of three predicates (or procedures). ‘The three predicates are: + listensMusic + happy + playsGuitar The “happy” predicate is defined usinga single clause (a fact). The “listensMusic” and “playsGuitg predicates are each defined using two clauses (in both cases, two rules). It is a good idea to thing about Prolog programs in terms of the predicates they contain. In essence, the predicates are th, concey swe find important, and the various clauses we write down concerning them are our attempy, to pin duwn what they mean and how they are inter-related. 5.3.3 Knowledge Database 3 (Conjunction and Disjunction) KDB3, our third knowledge database, consists of five clauses: + happy(monica). + listensMusic(rahul). + playsGuitar(monica) ;- listensMusic(monica), happy(monica). playsGuitar(rahul) :- happy(rahul). + playsGuitar(rahul) =- listensMusic(rahut). There are two facts, namiely happy(monica) and listensMusic(rahul), and other three are the ruls. KDB eae, the same three predicates as KDB2 (namely “happy”, “listensMusic”, and eee all but it defines them differently. In particular, the three rules that define the play predicate introduce some new ideas. First, note the rule: + playsGuitar(monica) :- listensMusic(monica), happy(monica). ‘Tt has tw in i 0 items in its body, or (to use the standard terminology) two goals. What does this mt mean? The it i is ee padi beret =~ i - oma () that separates the goal listensMusic(monic?) Prolog (that is, the comma means AND). So this me nde! cals + Monica plays guitar, if she listens to music and is happy. The entire goal succeeds if both thi é query like this: first and the second subgoal succeed. Thus, if we posed 2- playsGuitar(monica). Prolog would answer as “no”. This is bi a log : A cause whi 3 contaii / it does not explicitly contain the information ison thee apps i So KDB3 only fulfils one of the two pre-conditions needed to est bblish playeGuitar(monica) our query fails. tablish playsee" programming In Protog Next, note that KDB3 contains two rules with exactly the sanic head, namely: « playsGuitar(ralul) = happy(cahul) , , : + playsGuitar(rahul) = lis ‘This is a way of stating that: sMusie(rabul) + Rahul plays guitar, if either he listens to music, or if he is happy. That is. listing multiple rules with the same head is a way of expressing logical disjunction. In other words, it is a way of saying OR, because during the goal execution process Prolog could choose either one of the two rule bodies, when the current goal matches the common rule-head, First of all it will try the first rule, and only execute the second one if there has been a failure or if the user has asked for alternative solutions. So if we pose the following query: 2- playsGuitar(rahul). prolog would answer “yes”, The first rule will not help because KDB3 does not allow Prolog to conclude that happy(rahul), but KDB3 contains listensMusic(Rahul) and this means that the Prolog can apply modus ponens using the following rule: + playsGuitar(rahul) : listensMusie(rahul) 0, it concludes that playsGuitar(rahul) is truc. ‘There is another way of expressing dlsjunetion in Prolog. We could replace the pair of rules given above by the single rule as: + playsGuitar(rahul) ;- happy(rahul); listensMusie(rahul). That is, the semicolon (;) is the Prolog symbol for OR, so this single rule means exactly the same thing as the previous pair of rules. But Prolog programmers usually write multiple rules, as extensive use of semicolon can make Prolog code hard to read. Note that the precedence value of semicolon (:) is higher than that of comma (,). Therefore, ‘when implementing a disjunction inside @ onjunetion you have to structure your rule-body using parentheses. 5.3.4 Knowledge Database 4 (Using Variables in Queries) Here is KDB4, our fourth knowledge database: 5 = woman(secta). a + woman(gecta). 7 + woman(sonia). 7 woman(kawal). woman(lata). woman(rajni). + loves(geeta, seta). AG * loves(seeta, kawal). 4 = Symbolic Logic ang : "oy | + loves(lata, rajni). + loves(rajni, lata), + friends(gecta, seeta, kawal). Now: this is knowledge database in whic there are no rules, only a collection ofa, | from the frst three facts (having one argument each, it is very much clear that “Seeta™ a and “Sonia” are women. ' Now forthe first time we're going to make use of variables. We can ask openey, questions by using the variables in place of constants in a query. To distinguish variable pe constants, Prolog uses tokens that begin with an uppercase letter, for example, X, Xy2 ors underscore “_”. Using a variable in a query is very simple in Prolog. For example, consider the following ager 2- loves(geeta; X). The Prolog will give the result as: + X=seeta. * Yes Here “Yes” means that the Prolog has satisfied the goal. ‘The goals ina conjunctive query can share the variables. Now, remember that comma () mexs AND. This is useful to constrain arguments of different goals to have a same value ee consider tie following question: * Is there any individual X such that Kawal loves X and X is a woman? To express the above question in Prolog, we use the conjunction of two goals loves(kawal, X) i VoratOd), where the variable X is shared between goals. Let’s try a query having the use of shar variable, namely: 2 loves(seeta, X), woman(X), HN the knowledge database you'll see that there are the following two facts: : is a woman (fact 1) and . + Seeta Woves Kawal (fact 5), And in fact, Prolopy database and work ou satisfied. Since there exi of the program axioms, such the answer as: ‘ + X=kawal + Yes . is printed, along with the “yes” that ae eats to information in the knowledg Capable of working this out. That is, it can Search through the knowl i if it matches X with Kawal, then both the conjunets of the query ** ae Shment to the variables in the query that makes it a conseques* nts to variables are also called bindings. So Prolog ret" -- process ns that a solution was found. This p ¢ is the heart of Prolog. coy thee shot ad programming In Prolog iT Here there is only one solution to the problem, but ithore ate severitl diferent vailioy singed the variables, the Prolog execution mechanism will generate allornitive biidings to the yond ae bles. Prolog prints one such solution at a Hine and (hon wail for a onescharieter commmed ie vari jon (°°) fo produce the next solution, or the return Koy 0 lop poneraliny, solutions fox thy a Pet cause Protog to find more answers, any’ and pressing, "Hater wal ou ery: Pressing : : jt to discontinue its search, and prompt for new questions, the search order they are given. Here’s an example query: Noto that Prolog alurtn checking facts in 2 woman(X). rere X is a variable (in fact, any word beginning with an upper-case letter is a Prolog yariable, which is why we had to be careful to use lower-case initial letters in our carlicr examples). Nowa variable isn'ta name, rather isa “placeholder” for information, That is, this query essentially asks Prolog: «Tell me which of the individuals you know about a woman. prolog answers this query by working its way through KDB4, from top to bouton, trying to match (CX) with the information KDB4 contains. Now the first item in the (or unifi) the expression womant Wrowledge base is woman(secta). So, the Prolog matches X to “Seeta”, thus making the query agree perfectly with this first item and reports back to us as follows: Pp X=seeta And it will wait for a keystroke i.e. it not only says that there is information about at least one “yes”, it actually gave us the woman in KDB4, it actually tells us who she is, It didn’t just say variable binding, ot instantiation that led to success. But that’s not the end of the story i.e. there is information about other women in the knowledge database, So we can access this information by typing the semileton after the above result as: X = seeta; Remember that the semicolon (:) means OR, so this query means: + Orif there is any more women? in (it remembers where it got up to So Prolog begins working through the knowledge database again last time and starts from there) and sees that if it matches X with “Geeta”, then the query agrees perfectly with the second entry in the knowledge database. So it responds as: X=geeta It's telling us that there is information about a second woman in KDB4, and (once again) it actually gives us the value that led to success. ‘And of course, if we press the (;) again, Prolog Tetums the answer as: X= sonia ie But what happens if we press (;) for the third time? Prolog responds as “No” which means that ere is no other match i.e. there are no other facts starting with the symbol woman. Seer ORES Pe SSS =e programming 9 POS ae, Here there is only one solution to the problem, but if there are several different values assigned to the variables, the Prolog execution mechanism will generate alternative bindings to the goal prolog prints one such solution ata time and then waits for a one-character command ic the next solution, or the return key to stop generating solutions for the ~ will cause Prolog to find more answers, if any and pressing “Enter” will cause it to discontinue its search, and prompt for new questions. Note that Prolog starts checking facts in fhe search order they are given Here’s an example query: 2- woman(X). Here X isa variable (in fact, any word beginning with an upper-case letter is a Prolog ee Sua ie why wehad tobe careful touse lower-case initial tiers nour cris PS) rete Sable isv'¥ a name, ratberi'sa“placboler” for infomation. Thats, this query eset axiks Prolog: “= Tell me which of the individuals you know about a woman. i query by working its way through KDB, from top to bottom. tring 19 mai i scapes womsn() wit th informaon KDB eons, Now he Sf 0 Knowledge base is woman(seeta). 'So, the Prolog matches X to “Seeta”, thus making the query agrez perfect with this first item and reports back to us as follows: X=seeta De pst Sabir Fc ict coy saysthier exes ompetiom heen Oe “a et et anvaly tls ws who sho js Tt Gio just sry "yes" it actually gave nse i ‘yariable binding, ot instantiation that led to success. 2 Bae are atthe end ofthe story ie. ther is information about other women inthe now eS ; ie ee ess this information by typing the semileton afi, the above FES 5 i X = seeta; ‘Remember that the semicolon (:) means OR, so this query means: + Orif there is any more women? if Fegins working through the knowledge database again (i remembers ers Bu 00 Be ete ed a) wl acs tht WP tatchcs X with “Gasp”, Oe the goery SE ; peretly wath the second entry inthe knowledge database. Sot responds as: E X=geeta i tcing us at there is inrmation about a second woman in KDBA, and (once 2650 © value that led to BF LS ee 7 And of course, if we press the (;) again, Prolog X= sonia : (0) forthe sid time? Prolog responds as “No” which means that = = arene Pi tot Symbolic Logic and Pry log If we do not need to know instead of using any variable we can replace we ¢ = value for that, For example, consider the following query: 2- friends(X, seeta, _), loves(X, _). the values of something, we can use the anonymous variables 5 ¢ can use the symbol “_”, which does not retum aig It will give the result as: + X=geeta + Yes The scope of an anonymous variable is its single occurrence. Generally, we prefer using name ‘er than anonymous variables, although anonymous variables car variables for documentation rath: : ables be slightly more efficient since they do not require that bindings be made. Consider another database that contains the following clauses: + person(nidhi, gupta, female, 28, architect). + person(amit, thakur, male, 62, doctor). + person(atul, mahajan, male, 45, plumber). + person(harish, sharma, male, 23, chemist). + person(sakhshi, sareen, female, 24, programmer). * person (amit, arora, male, 47, solicitor). + -man(A) =- person(A, B, male, C, D). The first six clauses {all facts) comprise the definition of predicate “person”, having the five ‘Eyer ee ee interpretations Le. the forename, surname, sex, age and occupation of ‘ ‘ by the corresponding fact. The last clause is a rule, defined using the “person predicate, which also has a natural interpretation, i: Z y for all A Aisa man if A is a person whose sex is male. The variable A in the head of the clause (representing forename in this case) stands for “forall oa : : and is said tobe universally quantified. In order to show that ‘“atul is a man”, there would then tobe gan aes with the forename as “atul” for all possible surnames, ages and occupation mee y 7 ts sonable. If only the surname of any people named atul is of interest, ths y 8 the other three variables anonymous in a goal, for example: + ?-person(atul, Surnam It will give the result as: name = mahajan Similarly, if only the “Age” of all the : 5 ; P tales int would be very simple to enter the goal: le named “amit” in the database is 0! erost, ?- person(amit, >> programming in Prolog ‘This will give two answers by backtracking as: + Age=62: + Age=47 Note that there is no assumption that all the anonymous variables have the same value (in the above examples they do not). Entering the alternative goal: 2- person(amit, X, X, Age, X). : With variable X instead of underscore, would produce the answer “no”, as there are no clauses with first argument “amit” where the second, third and fifth arguments are identical. 53.5 Knowledge Database 5 (Using Variables in Database) Well. we've introduced variables, but so far we’ve only used them in queries. In fact, variables can also be used in knowledge databases. The most common use of variables in databases is to convey information from one part of a program to another. Here’s a simple example: + loves(geeta, seeta). * loves(kawal, seeta). + loves(lata, rajni). + loves(rajni, lata). + jealous(X. Y) :- loves(X, Z), loves(Y, Z). KDB3 contains four facts about the “loves” relation and one rule, But this rule is by far the most interesting one that coritains three variables (note that X, Y, and Z are all upper-case letters). In effect. it is defining a concept of jealousy. It says that: + An individual X will be jealous of an individual Y if there is some individual Z that X loves. and Y loves that same individual Z too. So jealously isn’t as straightforward as in the real world. The thing to note is that this is a general statement ie. it is not stated in terms of “Seeta”, “Geeta”, or anyone in particular, it’g conditional statement about everybody in our little world. - Suppose we pose the query: 9- jealous(kawal, Y). This query asks that: + Ifyou can find an individual Y such that Kawal is jealous of Y, (Geeta is such an individual). Ifyou check the definition of jealousy, you'll see that “Kawal” must be jealous of “Geeta”, because they both love the same woman, namely “Secta”. Internally it will initiate the value “kawal” to X and then proceed to the following sub goal: loves(X, Z). NO Symbolic Logic ang Th + loves(lata, rajni). + loves(rajni, lata). + friends(geeta, secta, kawal). : Now, this is a knowledge database from the first three facts (having one al and “Sonia” are women. Now for the first time we're going to make use of variables. We can ask open. i uery. To distinguish variables fin questions by using the variables in place of constants in a q! constants, Prolog uses tokens that begin with an uppercase letter, for example, X, Xyz, a underscore “_’ Using a variable in a query is very s in which there are no rules, only a collection of facts gument each), it is very much clear that “Seeta”, “toe imple in Prolog. For example, consider the following que, 2- loves(geeta; X)- ‘The Prolog will give the result as: + X=seeta. + Yes Here “Yes” means that the Prolog has satisfied the goal. The goals in a conjunctive query can share the variables. Now, remember that comma (,) m= "AND. This is useful to constrain arguments of different goals to have a same value, so considers following question: «Is there any individual X such that Kiwal loves X and X is a woman? “To express the above question in Prolog, we use the conjunction of two goals scomun(X), where the variable X is shared between goals. Let's try a query havi yariable, namely: loves(kawal, X)2 ng the use of cid 2- loves(seeta, X), woman(X). Hyon look at the knowledge database you'll see that there are the following two facts: + val is a woman (fact 1) and + Seca loves Kawal (fact 5). 5 capable of working this out. That is, it can search through the sort (if it matches X with Kawal, then both the conjunc of gt assignment to the variables in the query that makes it a 0! ents to variables are also called bindings. So PO" isi, Siacn there Cx Af tee IED COTS, such thee BORA ‘ * & kaw + te coo 9 gree, dong with the “yes” thal ey : F that . found. THis P tif, HBR NO information in the knowledgt s that a solution was ¢ is the heart of Prolog: proaing P° « there is only one solution to the problem, but if there are several different values assigned Here cables, the Prolog execution mechanism will generate alternative bindings to the goal Prolog prints one such solution at a time and then waits for a one-character command i.c. ») to produce the next solution, or the return key to stop generating solutions for the ery, Pressing will cause Prolog to find more answers, if any and pressing “Enter” will cause ji to discontinue its search, and prompt for new questions. Note that Prolog starts checking facts in the search order they are given. Here’s an example query: to the var variables. a semicolon ‘2- woman(X). Here X is a variable (in fact, any word beginning with an upper-case letter is a P: variable, which is why we had to be careful to use lower-case initial letters in our earlier examp Nowa variable isn’t aname, rather it’s a “placeholder” for information. That is, this query esse: asks Prolog: + Tell me which of the individuals you know about a woman. Prolog answers this query by working its way through KDB4, from top to bottom, trying to ma: (or unify) the expression woman(X) with the information KDB4 contains. Now the first item knowledge base is woman(secta). So, the Prolog matches X to “Seeta”, thus making the query agree perfectly with this first item and reports back to us as follows: X = seeta ‘And it will wait for a keystroke i.e. it not only says that there is information about at least one woman in KDB4, it actually tells us who she is, It didn’t just say “yes”, it actually gave us the variable binding, or instantiation that led to success. But that’s not the end of the story i.<. there is information about other women in the knowledge database, So we can access this information by typing the semileton after the above result as: X =seeta; Remember that the semicolon (;) means OR, so this query means: + Orif there is any more women? 7 So Prolog begins working through the knowledge database again (it remembers where it got up to “Geeta”, then the query agrees last time and starts from there) and sees that if it matches X will perfectly with the second entry in the knowledge database. So it responds as: X= geeta It’s telling us that there is information about 2 second woman in KDB4, and (once again) it actually gives us the value that led to success. ‘And of course, if we press the (;) again, Prolog Tetums the answer as: X= sonia But what happens if we press ()) for the third time? Prolog responds as “No” which means that there is no other match i.e. there aro no other facts starting with the symbol woman. Symbolic Logie | tae wha] 1 thing, we can use the anonymous Variables ¢ | If we do not need to know the values of some! eft isc the symbol “_”, which docs not etum ay | My instead of using any variable we ean replace we can value for that, For example, consider the following query: 9. friends(X, seeta, _), loves(X, _)+ Tt will give the result as: + X=geeta + Yes ‘The scope of an anonymous variable is its single occurrence. Generally, we prefer using-name variables for documentation rather than anonymous variables, although anonymous variables cay be slightly more efficient since they do not require that bindings be made. Consider another database that contains the following clauses: + person(nidhi, gupta, female, 28, architect). + person(amit, thakur, male, 62, doctor). ‘+ person(atul, mahajan, male, 45, plumber). + person(harish, sharma, male, 23, chemist). person(sakhshi, sareen, female, 24, programmer). * person (amit, arora, male, 47, solicitor). * man(A) :- person(A, B, male, C, D) . The i fas ius all facts) comprise the definition of predicate “person”, having the five Pe Srey ibe rater: the forename, surname, sex, age and occupation of predicate, which also has a natural terdidatien tee staged aoa caste ae nae, he A ‘e aman ifA is a person whose sex is male. lA in the h and is said tobe sea of the clause (representing forename in this case) stands for “for all A’ tobe person” clanges a Quantified. In order to show that “atul is a man”, there would then need while nore the forename as “atul” for all possible surnames, ages and occupations. can be found by makin sonable, If only the surname of any people named atul is of interest, this i ig the other three variables anonymous in a goal, for example: wean Peat, Summary , a ‘Pre the result as: Similarly, p > would be very sige “Age” of all the snter the goal: ‘name = mahajan le named “amit” in the database is of interest, it ~ 2- person(amit) page

You might also like