html5-img
1 / 142

Topic 4b - An Overview of Prolog

Topic 4b - An Overview of Prolog. A Successful Automated Reasoning System Prolog is one of the most successful attempts at producing a language for automated reasoning. Predicate Calculus provides the structure for representing knowledge in the language of logic. An Overview of Prolog

berne
Télécharger la présentation

Topic 4b - An Overview of Prolog

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Topic 4b - An Overview of Prolog • A Successful Automated Reasoning System • Prolog is one of the most successful attempts at producing a language for automated reasoning. • Predicate Calculus provides the structure for representing knowledge in the language of logic. • An Overview of Prolog • designed to give a practical implementation of the language of Predicate Calculus • a mechanism for entering a database of knowledge in terms of • facts and • relationships between these facts (i.e. rules) • serves as a database/query system • the query becomes the goal or theorems which Prolog tries to prove • History • 1972, Philippe Rousell and Alan Colmerauer of the ‘Group d’Intelligence Artificielle’ at the University of Marseille • First interpreter written in Algol-W in 1972, then in FORTRAN in 1973, then in Pascal in 1976.

  2. Prolog References Prolog Programming for Artificial Intelligence Ivan Bratko 1986, Addison-Wesley Luger Chapters 6 , 13 Programming in Prolog W.F. Clocksin and C.S. Mellish 1987, Springer-Verlag A Prolog Primer Jean B. Rogers 1986, Addison-Wesley The Art of Prolog Sterling and Shapiro 1986, MIT Press

  3. Some Features of Prolog • resolution theorem-proving (or unification) • rewrites and stores database in the form of Horn Clauses (See next slide - Omit at KG) • depth-first strategy in searching for a pattern-match • is more declarative than procedural • Is Prolog a True Logic Programming Language? No! • A language must have extra features to those of a purely logical nature: • a stack scheduling policy • communication predicates (I/O) • control features (cut, repeat, ...) • dynamic database modification (assert, retract,....) • However, Prolog is still very close to a pure logic programming language.

  4. Horn Clauses (Omit at KG) • Logic programming is commonly done using predicate calculus expressions called "Horn clauses" (named after Alfred Horn, who first studied them). • Horn clauses are clauses that satisfy a particular restriction: • at most one of the literals in the clause is unnegated. • Thus, the following are Horn clauses (assuming that P, Q, Pi, P2,..., Pk represent propositions each consisting of a predicate and the required number of terms): not PÚQ not P1Ú not P2Ú... Ú not Pk V Q not P1Ú not P2Ú... Ú not Pk P • These can be rewritten: P => QP1Ù P2 Ù... Ù Pk => Q P1Ù P2 Ù... Ù Pk => F P • The third of these expressions employs F to indicate falseness or the null clause.

  5. Horn Clauses - Contd.(Omit at KG) • These are often written in a "goal-oriented" format in which the implied literal (the goal) is on the left and ',' is used for the AND operator: Q <= P Q <= P1, P2, …, Pk <= P1, P2, …, Pk P <= • The third and fourth examples above show cases in which the goal arrow has nothing to its left (in the former case) and nothing to its right (in the latter case). • The null clause is a Horn clause, and can be written <= • Horn clauses in the goal-oriented format are used to program in Prolog.

  6. Useful in Solving the Problem of Non-monotonic Reasoning • In monotonic logic, the axioms are invariant, even though new information may indicate that certain axioms must be false. • Non-monotonic reasoning provides for updating the set of axioms to reflect the best available information (using assert and retract).

  7. What topics are we covering? • Introduction to Prolog • Facts • Queries • Variables • Rules • Finding solutions • What will we be able to do? • understanding of fact database • able to explain Prolog code • able to trace evaluation of a goal • able to define simple Prolog relations

  8. How Does Prolog Relate to Other Languages? • Wirth: Programs = algorithms + data structures • Kowalski: • Algorithms = logic + control i.e. what we are trying + how we go about to achieve achieving it i.e. declarative V's procedural semantics semantics

  9. Where to find Prolog at FIT • SWI Prolog in FIT Labs

  10. Using SWI-Prolog • We will use a version of Prolog which runs under Linux, Windows xx. You should visit the FIT’s OLT or the following URL, download the appropriate version and get it running on your own PC. The ftp sites are indicated at this URL: http://www.swi.psy.uva.nl/usr/jan/SWI-Prolog.html • use pfe orNotepad as default editor • ignore comments in tutorials re :-state(token........... This does not apply to SWI Prolog. • Note the extensive manual available at the SWI site

  11. Using SWI Prolog (Contd) • Editing or Creating a file from within SWI Prolog: ?- edit(myprog). This edits myprog.pl and then automatically reconsults the file. • To exit, use ?- halt. • A ‘consulting’ error gives an error message and an ‘error menu’ the meanings of which can be easily discovered. • help ?- help. -> a brief ‘help’ file ?- help(get). -> help on the command ‘get’ • Tracing • trace. opens a trace window to enable tracing of the evaluation of the goal (query) • notrace. • Use 't' to turn on trace during SWI execution. • Use 'c' to turn on creep.

  12. Using SWI Prolog (Contd) • When consulting files in subdirectories using SWI Prolog, you need to take care using slashes. A single forward slash or TWO back slashes will be accepted. See examples below: 1 ?- ['a:/a']. a:/a compiled, 4.72 sec, 2,152 bytes Yes 2 ?- ['a:\a']. [WARNING: No such file: user : a:] No 3 ?- ['a:\\a']. a:\a compiled, 4.72 sec, 2,152 bytes. Yes

  13. Using SWI Prolog (Contd) • SWI runs in a window that behaves a little differently from other Windows applications. • In particular, you will need to capture output into a file to print and submit for your assignment. One way of doing this is a follows: • You can drag the mouse over a SWI screen. Only the first line is highlighted but in fact all lines covered by the mouse are now able to be copied. • Then type 'CTRL C'. Now open the window you wish to copy to. Click the mouse to position the copy position. Type 'CTRL V'. The text will appear on one line as 'Enters' are translated to graphics characters. Simple replacing of the graphics characters by 'Enters' will create the text properly. • You need to do this carefully to ensure that the text is exactly what I will see when I run your program from the disc you supply with your assignment.

  14. Using SWI Prolog (Contd) • When you load Prolog code using the SWI compiler, you may generally ignore any warnings that refer to 'Singleton Variables'. • Most other compilers do not give this warning. • If you wish you may get rid of this problem and some others by putting the following at the beginning of every SWI program: :- style_check(-atom). :- style_check(-singleton). :- dynamic(asked/2).

  15. Getting Started (SWI Prolog assumed) • 1. (Rarely used) You may enter clauses interactively from the keyboard : c: [user]. i.e. read clauses from the keyboard is_integer (0). etc. a set of Prolog clauses (facts and rules) etc. ^Z. to exit entry phase and return to query mode. • 2. (Commonly used) You may use any DOS editor (such as Notepad, pfe, etc) to form a file of Prolog clauses ( ‘pro1.pl’ in SWI Prolog). • 3. To ‘consult’ this file from within Prolog, use [‘pro1.pl’]. This is a shorthand version of consult('pro1.pl').

  16. In most versions of Prolog, you may omit the ‘ s if the filename does not contain an extension. This then becomes [pro1]. This is also a shorthand notation for the full form consult(pro1). • If you need to edit this file and wish the new definitions of clauses to overwrite the old ones, you need to use: reconsult(pro). • Summary of 4 ways of consulting Prolog clauses into the database 1. [user]. i.e. consult clauses directly from the keyboard or 2. [pro1]. 3 ways of consulting from a file. 3. consult(pro1). or 4. consult(‘pro1.xxx’).

  17. Reading programs: consult, reconsult • We can communicate our programs to the Prolog system by means of two built-in predicates: • consult and • reconsult. • We tell Prolog to read a program from a file F with the goal: ?- consult( F). • The effect will be that all clauses in F are read and will be used by Prolog when answering further questions from the user. • If another file is consulted at some later time during the same session, clauses from this new file are simply added at the end of the current set of clauses. • [X] is a special notation for consult(X). • [file1, file2, file3] is also possible. • The built-in predicate reconsult is similar to consult. A goal ?- reconsult( F). will have the same effect as consult( F) with one exception: • If there are clauses in F about a relation that has been previously defined, the old definition will be superseded by the new clauses about this relation in F. • The difference between consult and reconsult is that • consult always adds new clauses while • reconsult redefines previously defined relations. reconsult( F) will, however, not affect any relation about which there is no clause in F.

  18. Aspects of Declarative Languages • Control separate • the Prolog system does the matching, backtracking, etc • Control can be upgraded (e.g. parallelism) without affecting the source code. • Control can extract information in a variety of ways (i.e. not limited to the outcome of one particular procedure) (e.g. append, etc.) • less to write since no need to worry about control.

  19. Prolog * A goal-directed language - Note * A logic programming language • i.e. all predicates are evaluated to True or False * A declarative language • i.e. you say what you want (see next slide for more details) * A relational language * A symbolic language (Therefore useful for AI applications) • i.e. suitable for manipulating symbols, cf Lisp * A Fourth/(Fifth) generation language * A query-based (conversational) language * A simple syntax * A dynamic environment • assert new facts and rules • retract new facts and rules • Solutions found (almost) ‘automatically’ (i.e. the ‘how’ is done for you)

  20. Applications of Prolog (Mostly in the area of Artificial Intelligence) Expert Systems (and shells) Natural Language Understanding Language Translation Symbolic manipulation systems (e.g. equation solvers, theorem provers, program derivation) Prototyping Databases in Prolog Dynamic relational databases Control and monitoring of industrial processes VLSI CAD Tools (e.g. editor - implementation is order of magnitude smaller than in imperative languages such as C) Analysis of VLSI designs at register transfer level (hardware design tool)

  21. Applications of Prolog (Contd) Portable Parallelising Pascal Compiler Natural Language Explanations from Plans Machine learning Stream Data Analysis (e.g. of stock market reports) "Assembly language" for Fifth Generation Language

  22. Prolog Overview • Prolog Programming features: 1. declaration of some FACTS about objects and their relationships; 2. declaration of some RULES about objects and their relationships; • Note: at this stage ‘programming’ stops and ‘querying’ starts and 3. asking QUESTIONS about objects and their relationships. • As facts and rules are defined Prolog stores them in a database. Then you can (conversationally) ask Prolog questions about the knowledge in the database. • data types are CONSTANTS, VARIABLES, or STRUCTURES (see later) • 1 and 2 above constitute a Prolog Program • 3 is the process of querying the Prolog system once clauses have been consulted. • More Simply: Prolog Programs ~ statements about the world Prolog queries ~ theorems we would like to have proved i.e. we tell the Prolog system what is true and ask it to test hypotheses.

  23. Defining FACTS - See Bratko Chapter 1.1 • Example of a Fact: predicate arguments a predication likes( john, mary). relationship objects (Note: relationships and constant objects must begin with a lower case letter.) • Syntax: - objects separated by commas ',' - fact terminated by full-stop '.' - objects of relationships within parentheses '(...)'

  24. FACTS - (Contd) • Semantics(i.e. Meaning) : We may decide that the fact has the semantics "John likes Mary" or indeed "Mary likes John", but we must decide on one and stick to it. The names have no meaning to Prolog - they are just symbols to be manipulated. So make sure you explain via comments the semantics of a relation at the start of its definition!

  25. FACTS - (Contd) constant constant female(jane). Jane is a female. structures father(john, mary). John is Mary's father. gives(john, book, mary). John gives the book to Mary. gives(john, has(cover, green)) Be careful as to what objects the symbols refer. For example, gold - valuable(gold). This is a slightly different interpretation of a fact. Is it a particular piece of gold or is it the element? (or indeed the colour)? The ambiguities must be resolved by the programmer's mind and he should be consistent.

  26. FACTS - (Contd) • [As the programmer's mind is volatile and non-transparent it is a good idea for the programmer to actually write down what interpretation is placed upon the symbols and relations.]

  27. A ‘database’ Interpretation of Prolog • predicate + arguments == record e.g. book(tanenbaum,a,computer_networks, prentice_hall,1981,.....). or more clearly: book( tanenbaum,a, computer_networks, prentice_hall, 1981, . . ... ). • A collection of facts is called a database in Prolog.

  28. QUESTIONS (or Queries or Goals) ?- owns (mary, book). • Note that some versions of Prolog insist on a ‘?’ to terminate a query. One possible meaning: Does Mary own a book? Prolog searches through the database looking for a ‘pattern match’ with: owns (mary, book) or something equivalent to it or that it can infer is true. Two facts match if the predicate and the arguments are the same (as in e.g. above). When a match is found in answer to a question, Prolog answers "yes", otherwise "no". "yes" means that it was provable by the facts and rules in the database. "no" means that it was NOT provable by the facts. Prolog knows nothing directly about the real world - only about what is in its database.

  29. Database: likes(joe, fish). likes(joe, mary). likes(mary, book). likes(john, book). • Questions: ?- likes(joe, money). ==> no ?- likes(mary, joe). ==> no ?- likes(mary, book). ==> yes ?- likes(john, france). ==> no ?- likes(fred, mary). ==> no • Constants We have been using constant objects • e.g. joe, gold, mary, book, ... • They remain completely unchanged through the life of the database. • They are constant symbols and represent objects in the outside world.

  30. VARIABLES The questions: Does John like books ? Does John like Mary ? are fairly restricted sorts of questions. A more interesting question is: What does John like ? a variable Here we are asking for everything that John likes. We will use a variable to represent something that John likes. Syntax of Variables: Must start with a capital letter. Note the following: Instantiated variables- variables with a value assigned to them, i.e. we have a particularinstance of something that the variable represents Uninstantiated variables- variables with no value known

  31. Variables have dynamic scope. This means that they are given one value (when it is found) which it keeps for the duration of that execution within any 1 rule. Once a solution is found then its value is reported and another solution is searched for (if requested). This new search is a new execution and the variable starts out with no value (i.e. uninstantiated). If a search for a solution fails then another search (and another execution)will look for a valid value for the variable. Given these facts: likes( john, flowers). likes( john, mary). likes( john, golf). likes( paul, mary). and the Goal: ?- likes(john, X). which involves an uninstantiated variable - X, the meaning is: set X to something John likes, i.e. instantiate X to something. Here, Prolog will return in order: X = flowers; X = mary; ……...

  32. i.e., make the question True by giving X a suitable value. ?- likes(john, X). X = flowers; X = mary; X = golf (CR) No ?- ?- likes(X, mary). X = john; ........... X = paul Think of Prolog as having a marker in the database marking its current match(es).

  33. Conjunction of Sub-Goals Goals may be compound goals consisting of a number of sub-goals connected by ‘,’ (the logical AND). In this case, all of the sub- goals need to succeed for the overall goal to succeed. For example, ?- likes(john, mary), likes(mary, john). Syntax: comma (,) means and (conjunction) Meaning ==> Does John like Mary and Mary like John? i.e. Do John and Mary like each other ? ?- likes(mary, X), likes(john, X). Meaning ==> Find something liked by both Mary and John. Prolog tries to match each goal in turn. Each goal has its place marker. Prolog attempts a complete match even if it means retrying the first goal until the database is exhausted.

  34. The AND Built-In Predicate ‘,’ • Note that ‘,’ is really a predicate. Internally, the implementation of likes(mary, X), likes(john, X). INFIX Notation is ‘,’(likes(mary, X), likes(john, X)). PREFIX Notation In the first case, ‘,’ is acting as an ‘infix’ operator. In the second case, ‘,’ is acting as a ‘prefix’ predicate - AND. Other ‘,’s are acting as argument separators. • A Note on Operator Notations • INFIX a + b • PREFIX -a • POSTFIX a!

  35. Finding Solutions for Conjoined Goals • Database: likes(mary, food). likes(mary, wine). likes(john, wine). likes(john, mary). Prolog processing for ?- likes(mary, X), likes(john, X). proceeds as follows: - X uninstantiated, search starts for first sub-goal - Marker 1 is set and X is instantiated to ‘food’ everywhere in question (i.e. inbothplaces) - The the second sub-goal becomes likes(john, food). This is sought and the search fails. - ‘backtrack’ to find another value of X which may succeed. - X becomes uninstantiated again and marker 1 proceeds from its current position seeking another match for likes(mary, X)

  36. likes(mary, wine) is found, which satisfies the first goal, so X instantiated to wine. • Marker 2 starts from the beginning and finds likes(john, wine). • Since X instantiated to wine satisfies both goals then the overall goal succeeds and X = wine is reported to the user. • Prolog then goes on to find any further solutions (relational rather than functional).

  37. Another Example of Compound Goals(For you to read) • Assume the database: 1- eats(rhonda, apples). 2- eats(henry,honey). 3- eats(rhonda,icecream). 4- eats(peter,passion_fruit_parfaits). 5- eats(henry,icecream). 6- eats(peter,honey). ?- eats(henry,X),eats(rhonda,X). sub-goal a sub-goal b GoalClauseResultInstantiation/Action a 1 fail 2 success if X = honey,(a) marker at 2 b 1..6 fail backtrack and uninstantiate X, b is now eats(rhonda,honey) a 3,4 fail 5 success if X = icecream, (a) marker at 5 b 1,2 fail 3 success (b) marker at 3

  38. The OR Predicate ‘;’ • ‘; ‘ is the OR predicate, • i.e. it gives the disjunction of 2 or more sub-goals e.g. likes(X,tennis);likes(X,golf). (B) (C) ‘or’ Thus, the overall goal is true if (B) is true OR (C) is true.

  39. RULES • Rules allow greater flexibility in declaring knowledge. Whereas facts are true in all cases, rules define "facts" that depend upon the truth of other facts. That is, the head of a rule may not always be true - it will depend upon whether its subgoals succeed or not. • rule (Definition): A relationship between a "fact" and a list of sub-goals which must be satisfied for that "fact" to be true • a general statement about objects and their relationships. Syntax: z :- a, b, c, ……….. i.e. If a and b and c and …, then z or a and b and c and … z ('implies z') ‘z (is true) if a and b and c and ………… (are all true)’ <conclusion or <requirements or consequence or :- antecedents or head> body> The conclusion of the rule will be true if the requirements are satisfied. The head consists of exactly one predicate, and the body consists of one or more predicates joined with ‘and’ (,) or ‘or’ (;).

  40. Undefined sub-goal predicates • If SWI Prolog tries to satisfy a sub-goal involving a predicate that does not exist in the database • (either because it was never defined or • because it was retracted during execution) then during execution SWI issues a 'Warning', halts execution and goes into 'trace' mode. Most other versions ignore this and fail. • This in some programs using SWI, you need to insert a dummy clause in case this happens.

  41. Example: Suppose that John likes everybody. We could say: likes(john, mary). likes(john, paul). : : But it would be better to try to say: “John likes any object if it is a person.” In prolog, we do this via lokes(john, X) :- person(X). • Other examples of rules (in English): John buys wine if it is cheaper than beer. X is a bird if: X is an animal, and X has feathers. X is a sister of Y if: X is female, and X and Y have the same parents. The variable (e.g. X or Y) has to be instantiated to the same object throughout the whole rule.

  42. Translating English-like rules into Prolog John likes anyone who likes wine. John likes something if that something likes wine. John likes X if X likes wine. if In Prolog: likes(john, X) :- likes(X, wine). More examples: ‘and’ likes(john, X) :- likes(X, wine), likes(X, food).

  43. Rules Using the Disjunctive ';' • ‘; ‘ is the OR predicate, i.e. it gives the disjunction of 2 or more sub-goals e.g. likes(john,X) :- likes(X,tennis) ; likes(X,golf). (A) (B) (C) ‘if ‘ ‘or’ Thus, (A) is true if (B) is true OR (C) is true. • It is used less frequently than the ‘,’ as two rules with the same LHS achieve the same effect. Thus, the above is equivalent to likes(john,X) :- likes(X, tennis). likes(john,X) :- likes(X, golf). • Another example: likes(john, X) :- female(X); likes(X, wine).

  44. Finding Solutions for Goals Involving Rules but with No Variables • An example of simple backtracking. • Suppose the database contains the following: boy(john). boy(marmaduke). boy(bertram). boy(charles). girl(griselda). girl(ermintrude). girl(brunhilde). possible_pair(X,Y) :- boy(X), girl(Y). • And the query is: ?-possible_pair(X,Y). • The response would be: X=john, Y= griselda; X=john, Y= ermintrude; X=john, Y= brunhilde; X=mamaduke, Y= griselda; X=mamaduke, Y= ermintrude; X=mamaduke, Y= brunhilde; X=bertram, Y= griselda; X=bertram, Y= ermintrude; X=bertram, Y= brunhilde; X=charles, Y= griselda; X=charles, Y= ermintrude; X=charles, Y= brunhilde; No.

  45. S S F S S F S S S S F S F S S YES! Backtracking with Sub-Goals in Rules Illustrated • fred :- a, b, c, d, e, f, g. The solution would be formed from instantiations formed from the indicated successes.

  46. Finding Solutions for Goals Involving Rules with Variables Database: Facts: male(albert). male(edward). female(alice). female(victoria). parents(edward, victoria, albert). parents(alice, victoria, albert). Rule: sister-of(X, Y) :- female(X), parents(X, M, F), parents(Y, M, F), not (X = Y). Or, using more meaningful names: sister-of(Sister, Sibling) :- female(Sister), parents(Sister, Mother, Father), parents(Sibling, Mother, Father), not(Sister, Sibling).

  47. Prolog processing for ?- sister-of(alice, edward). proceeds as follows: Step 1 Rule sister-of located and X instantiated to alice and Y set to edward from the goal. Step 2 The first sub-goal, female(alice), is found in the database of facts so succeeds. Step 3 Search to match the second sub-goal, parents(alice, M, F). This is found as a fact so succeeds. Variable M is instantiated to victoria, and variable F is instantiated to albert. Step 4 Prolog now tries to satisfy the third sub- goal so searches for parents(edward, victoria, albert) (as Y, M and F have all been instantiated). This fact is found so the sub-goal succeeds.

  48. Since all sub-goals have now succeeded then the overall goal, sister-of, succeeds (i.e. has been determined to be true) - so Prolog answers yes.

  49. Prolog processing for ?- sister-of( alice, X ). proceeds as follows: Step 1 Rule ‘sister-of’ located and X (of ‘sister-of’ rule) instantiated to alice and Y (from the rule in the program) is set to variable X from the goal. Note that X(goal) and Y variables are both uninstantiated. Step 2 The sub-goal, ‘female(alice)’, succeeds as before. Step 3 Variable M is instantiated to ‘victoria’, and variable F is instantiated to albert - as before. Step 4 Y is unknown, so search for parents(Y, victoria, albert) The fact ‘parents(edward, victoria, albert)’ matches this, so Y is instantiated with ‘edward’.

  50. Step 5 Since all sub-goals have now succeeded then the overall goal, sister-of, succeeds with X being instantiated to edward . Prolog2 answers: X = edward. More(Y/N)? Y SWI achieves the same effect via X = edward; Now Prolog tries to find another solution to sister- of. Steps proceed as from Step 4, with Y uninstantiated again. This time through, Step 4 will match with parents(alice, victoria, albert), so Y (and then X) will be instantiated to alice. Prolog answers: X = alice

More Related