1 / 63

LOGIC PROGRAMMING (WEEK 3)

LOGIC PROGRAMMING (WEEK 3). Eleni E. Mangina Department of Computer Science University College Dublin. General mod ule information Books Introduction - Declarati ve programming The Prolog Language. Lecture 7. Books. The recommended book is: Programming in Prolog

derry
Télécharger la présentation

LOGIC PROGRAMMING (WEEK 3)

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. LOGIC PROGRAMMING(WEEK 3) Eleni E. Mangina Department of Computer Science University College Dublin • General module information • Books • Introduction • - Declarative programming • The Prolog Language DEPT. OF COMPUTER SCIENCE UCD

  2. Lecture 7 DEPT. OF COMPUTER SCIENCE UCD

  3. Books • The recommended book is: Programming in Prolog 4th Edition W. Clocksin & C.S. Mellish • Another book: The Art of Prolog 2nd edition L. Sterling & E. Shapiro DEPT. OF COMPUTER SCIENCE UCD

  4. Introduction to Prolog • Programming languages are of two kinds: - procedural (BASIC, ForTran, C++, Pascal) - declarative (Lisp, Prolog, ML) • In procedural programming, we tell the computer how to solve a problem • In declarative programming, we tell the computer what problem we want solved • (However, in Prolog, we often forced to give clues as to the solution method) • Other AI languages: LISP, C/C++, CLIPS DEPT. OF COMPUTER SCIENCE UCD

  5. Some facts about Prolog (For those who know other languages) • • No global variables. • • No assignment statement. • • No real iterative constructs. • • No conditional (if/then) statement. • • Recursion very central. DEPT. OF COMPUTER SCIENCE UCD

  6. Basic elements of Prolog • We give a database of facts and rules: - some are always true - some are dependent of others • To run a program we ask questions about the facts DEPT. OF COMPUTER SCIENCE UCD

  7. The central ideas of Prolog • SUCCESS/FAILURE: any computation can “succeed” or“fail”, and this is also used as a “test” mechanism. • MATCHING: any two data items can be compared forsimilarity, and values can be bound to variables in order toallow a match to succeed. • SEARCHING: the whole activity of the Prolog system isto search through various options to find a combinationthat succeeds. • BACKTRACKING: when the system fails during itssearch, it returns to previous choices to see if making adifferent choice would allow success. DEPT. OF COMPUTER SCIENCE UCD

  8. Prolog in English • Example: John is the father of Jim Jane is the mother of Jim Jack is the father of John Person 1 is a parent of Person 2 if Person 1 is the father of Person 2 or Person 1 is the mother of Person 2. Person 1 is a grandparent of Person 2 if some Person 3 is a parent of Person 2 and Person 1 is a parent of Person 3. Who is Jim’s father? Is Jane the mother of Fred? Is Jane the mother of Jim? Does Jack have a grandchild? DEPT. OF COMPUTER SCIENCE UCD

  9. Prolog in Prolog father(john,jim). mother(jane,jim). father(jack,john) parent(Person1,Person2):- father(Person1,Person2). parent(Person1, Person2):- mother(Person1, Person2) grandparent (Person1, Person2):- parent(Person3, Person2), parent(Person1, Person3). ?- father( Who, jim). ?- mother( jane, fred). ?- mother( jane, jim). ?- grandparent( jack, _). DEPT. OF COMPUTER SCIENCE UCD

  10. Using Prolog (1) • First write your program • Then, type it into a Unix file, with a .pl extension • Then type sicstus • Then, “consult” your file (omitting the .pl): [yourfilename] • Then, you can ask your questions • Sometimes, you can get multiple answers, by typing ‘;’ • If you edit your program file (eg. to correct something), be sure to consult it again afterwards! DEPT. OF COMPUTER SCIENCE UCD

  11. Using Prolog (2) • To exit from Prolog, type halt. • or Control/D • The Prolog comment characters: • Single line comments: % This is a comment This is not a comment, but an error • Multiple line comments /* This is a multi-line comment which must be closed with a */ DEPT. OF COMPUTER SCIENCE UCD

  12. Simple interaction with Prolog On a Unix workstation, type: sicstus this should give: SICStus 3 #5: Fri Jul 4 12:29:00 BST 1997 | ?- Then you can type a simple command: write(’hello’). which will give the response: hello yes Or a sequence of commands, separated by COMMAS: write(’hello’), nl, write(’friend’). giving: hello friend yes To exit from Prolog, type halt. or Control/D DEPT. OF COMPUTER SCIENCE UCD

  13. Definining and loading programs Start up Sicstus Prolog. • ‘consult’ your file (omitting the .pl): consult(myprog). There is an abbreviated form, using square brackets: [myprog]. • If you edit your program file (e.g. to correct something), be sure to “consult” it again afterwards! DEPT. OF COMPUTER SCIENCE UCD

  14. Defining a program A procedure (or predicate) consists of one or more clauses. Here is a simple clause: salute :- write(’Hi,’), tab(2), write(’pal!’). This defines a procedure whose head is salute and whose body is write(’Hi,’), tab(2), write(’pal!’). If we put this in a file, then consult that file, then : ?- salute. Hi, pal! yes DEPT. OF COMPUTER SCIENCE UCD

  15. Choices Definitions can have several clauses: greet(hamish):- write(’How are you doing, pal?’). greet(amelia):- write(’How awfully nice to see you!’). greet(mike):- write(’Hi there’). If this definition is consulted into Prolog, then: ?- greet(amelia). How awfully nice to see you! yes The goal is matched against the heads of the clauses, in order. The first matching clause is selected. The body of that clause is performed. DEPT. OF COMPUTER SCIENCE UCD

  16. Failure ?- greet(ebenezer). no If no clauses match the goal, the goal fails. When the goal typed in at top-level fails, the Prolog user-interface prints no. THIS IS DIFFERENT FROM AN ERROR. For example, trying to use an undefined predicate is an error: ?- say(’hello’). {EXISTENCE ERROR: say(hello): procedure user:say/1 does not exist} DEPT. OF COMPUTER SCIENCE UCD

  17. Variables in definitions An argument to a predicate can be variable: greet(Name):- write(’Hullo, ’), write(Name). With this defintion, we get: ?- greet(alphonse). Hullo, alphonse yes The matching of the goal with the head of the clause causes the variable Name to be bound to the value alphonse. This “binding” is then used when the body of the clause is being performed. DEPT. OF COMPUTER SCIENCE UCD

  18. Clauses in order greet(hamish):- write(’How are you doing, pal?’). greet(amelia):- write(’How awfully nice to see you!’). greet(Name):- write(’Hullo, ’), write(Name). Then: ?- greet(hamish). How are you doing, pal? yes ?- greet(daisy). Hullo, daisy yes ?- greet(amelia). How awfully nice to see you! yes Clauses are tried in order from the top. The one with thevariable will match any argument. DEPT. OF COMPUTER SCIENCE UCD

  19. Variables in goals A goal can also have variable arguments. Suppose we have consulted a file with all the clauses of greet shown so far. ?- greet(Person). How are you doing, pal? Person = hamish ? The (successful) matching of the goal with the head of the first clause causes the variable Person to be bound to the value hamish. The Prolog interface reports this “binding”. DEPT. OF COMPUTER SCIENCE UCD

  20. Summary so far • A Prolog program may succeed or fail. • Prolog programs consist of predicate definitions • Predicate definitions consist of clauses • Clauses consist of a head and and (so far) a body • A clause head has a predicate name and sometimes somearguments. • A goal is a predicate name and sometimes some • arguments. • A goal matches against clause heads in order. • If no clause matches, that goal fails. • Successful matching may cause variables to be bound tovalues. • If a variable in the top-level goal becomes bound, theuser-interface reports this. DEPT. OF COMPUTER SCIENCE UCD

  21. Lecture 8 DEPT. OF COMPUTER SCIENCE UCD

  22. Anatomy • Prolog programs consist of predicate definitions like parent • Predicate definitions consist of clauses parent(P1,P2) :- mother (P1, P2). • Clauses consist of a head e.g. parent(P1,P2) And sometimes a body e.g. mother(P1,P2) • A clause head has a predicate name and sometimes arguments (P1, P2) • The body is a collection of literals, which match clause heads DEPT. OF COMPUTER SCIENCE UCD

  23. What makes a good Prolog program? • In order of decreasing importance • Correctness and careful design • clarity and comments • speed (at least for our purposes in this course) Because we understand the logical meaning of logic programs we can reply on the computer to transform elegant but inefficient programs into ugly (but invisible) efficient ones DEPT. OF COMPUTER SCIENCE UCD

  24. What makes a bad Prolog program? • In no particular order: • Hacking undesigned code at the terminal • Using obscure or meaningless variable and predicate names • Not commenting code • abusing the procedural aspects of Prolog to produce logically meaningless code DEPT. OF COMPUTER SCIENCE UCD

  25. More about Prolog clause syntax (1) • Recall that a Prolog program is made up of predicates …. And a predicate is made up of clauses • A clause has a head and maybe a body • The head of a clause always takes one of two forms: predname predname( argument1, argument2, … ) • If the predicate is always true, there is no body, and we finish with a full-stop (period). DEPT. OF COMPUTER SCIENCE UCD

  26. More about Prolog clause syntax (2) • If the predicate is conditional, we connect it to a body of subgoals with the if operator, :- • Each subgoal is a Prolog literal … which is either • like a head, as before; or • A negated head, written \+ predname \+ predname (argument1, …) • Note the space after the \+ operator • We will return to \+ later DEPT. OF COMPUTER SCIENCE UCD

  27. More about Prolog clause syntax (3) • We can combine literals in Prolog clauses with the operators • , (comma) meaning “and” – conjuction • ; (semicolon) meaning “or” - disjunction You should never nee dto use ; in a program because you can express disjunction via multiple clauses. It makes Prolog compilation less effective DEPT. OF COMPUTER SCIENCE UCD

  28. More about Prolog clause syntax (4) • There is also  (minus, greater than) supposedly meaning “implies” • We can complex expressions using brackets ( l1(a1,a2); l2(a3)), l3(a1) l1(a1,a2); l2(a3)), l3(a1) l1(a1,a2); l2(a3), l3(a1) ) You should never need to use  and it is best avoided because it does not mean the same as “logical implies” DEPT. OF COMPUTER SCIENCE UCD

  29. More about Prolog goal syntax • Prolog goal syntax is the same as the syntax of the clause body • Literals are combined with “and”, “or”, “not” and “implies” • We run a Prolog program by asking a question or more precisely, stating a goal p(x):-q(x) |?- q(x) DEPT. OF COMPUTER SCIENCE UCD

  30. Proof strategy • Prolog solves questions by attempting to prove them • Suppose we have consulted the ancestor program and we ask the question: ancestor(alan,dave). • ancestor is defined as: ancestor(A,B) :- parent (A,B). ancestor(A,B) :- parent (A,C), ancestor (C,B) DEPT. OF COMPUTER SCIENCE UCD

  31. Proof strategy (2) • To prove this, prolog starts at the top of the database and tried to find a predicate called ancestor • Then it looks at each clause in turn, and tries to unify its head with the goal • Once unification is complete, attempt to prove the literals in the body, in order of appearance This is the prolog built-in proof strategy. However, it is possible to override it – we will cover this later DEPT. OF COMPUTER SCIENCE UCD

  32. Unification • Unification works by comparing the structure of literals: • First compare the predicate name; • Then, for each argument; • If the gioal argument is a variable, then make itthe same as the program argument, and unification succeeds; • Otherwise, if the program argument is a variable, then make it the same as the goal argument, and unification succeeds; • Otherwise, if both arguments are the same, unification succeeds; • Otherwise, unification fails We will cover unification in more detail later DEPT. OF COMPUTER SCIENCE UCD

  33. Proof Strategy (3) Prove: ancestor(alan,dave) Find: ancestor clause 1 Unify: A = alan, B = dave Prove: parent(alan, dave) FAIL Try again: Find: ancestor clause 2 Unify: A = alan, B = dave Prove: parent(alan, C) Find: parent clause 1 Unify: C = clive SUCCEED Next goal: Prove: ancestor(clive, dave) Find: ancestor clause 1 Unify: A = clive, B = dave Prove: parent(clive, dave) SUCCEED Answer: yes. DEPT. OF COMPUTER SCIENCE UCD

  34. Summary so far • Using the Prolog system • Programming style • Prolog clause syntax • Predicates • Clauses • Heads & bodies • Variables • Full-stops (periods) • Logical operators: , ;  \+ • Brackets DEPT. OF COMPUTER SCIENCE UCD

  35. So far.. • A Prolog program may succeed or fail. • Prolog programs consist of predicate definitions • Predicate definitions consist of clauses • Clauses consist of a head and and (so far) a body • A clause head has a predicate name and sometimes somearguments. • A goal is a predicate name and sometimes somearguments. • A goal matches against clause heads in order. • If no clause matches, that goal fails. • Successful matching may cause variables to be bound tovalues. • If a variable in the top-level goal becomes bound, theuser-interface reports this. DEPT. OF COMPUTER SCIENCE UCD

  36. Tests “Success” can act as “true”, “failure” as “false”: | ?- 5 < 7. yes | ?- 7 < 5. no So the comma acts like a (left-to-right) “AND” : | ?- 3 < 7, 2 < 4, 10 < 12. yes | ?- 3 < 7, 4 < 2, 10 < 12. no DEPT. OF COMPUTER SCIENCE UCD

  37. Tests in clauses This allows more precise selection of a clause: bigger(N, M):-N < M, write(’Bigger number is ’), write(M). bigger(N, M) :-M < N, write(’Bigger number is ’), write(N). bigger(N, M) :-write(’Numbers are the same’). If a test fails, then the system backtracks, and tries to choosea later clause. No need for an equality test in 3rd clause here – system triesthis one only when other two have failed, and hence N and Mmust be equal. DEPT. OF COMPUTER SCIENCE UCD

  38. Passing results DON’T return values by printing messages. Return values by causing suitable variables to become bound. larger(N, M, M):-N < M. larger(N, M, N) :-M < N. larger(N, M, M). e.g. : | ?- larger(8,3,Result). Result = 8 yes | ?- larger(6,6,Value). Value = 6 yes | ?- larger(2,5,Value). Value = 5 yes DEPT. OF COMPUTER SCIENCE UCD

  39. Variable binding larger ( 8 , 3 , Result ) larger ( N, M, M ) :- N < M, ..... M bound to 3, and M bound to Result, so Result bound to 3. Clause body fails. Bindings discarded. Next clause tried: larger ( 8 , 3 , Result ) larger ( N, M, N ):- M < N, ..... Since N bound to 8, and N bound to Result, Result bound to 3. Clause body succeeds. Result binding is retained and displayed. DEPT. OF COMPUTER SCIENCE UCD

  40. More on variable matching • a variable can be bound to another variable (sharing) • a shared set can contain any number of variables • if variable A is bound to variable B, then variable B isbound to variable A • shared variables cannot be bound to different non-variablevalues • when one of a shared set of variables is bound to a value,all the variables in that shared set are bound to the samevalue DEPT. OF COMPUTER SCIENCE UCD

  41. Lecture 9 DEPT. OF COMPUTER SCIENCE UCD

  42. Unit clauses A clause may have an empty body – no goals, and omit the “:-” symbol. greet(nasty). % Clause in your program Everything works as before: | ?- greet(nasty). yes | ?- greet(Who). Who = nasty? yes These are unit clauses. DEPT. OF COMPUTER SCIENCE UCD

  43. Unit clauses as facts %% A simple set of clauses describing %% some family relationships man(paul). man(david). man(peter). woman(louise). woman(helen). woman(mandy). wifeof(paul, louise). wifeof(peter, helen). sonof(paul, peter). daughterof(peter, mandy). Use constant symbols to represent objects, and predicates forproperties (e.g. woman) or relationships (e.g. sonof). DEPT. OF COMPUTER SCIENCE UCD

  44. Querying this “database” | ?- man(peter). yes | ?- man(louise). no | ?- woman(Someone). Someone = louise; Someone = helen; Someone = mandy; no DEPT. OF COMPUTER SCIENCE UCD

  45. | ?- wifeof(paul, Hiswife). Hiswife = louise yes | ?- wifeof(Herhusband, louise). Herhusband = paul yes | ?- daughterof(Father, mandy). Father = peter yes | ?- sonof(Father, Son). Father = paul Son = peter yes DEPT. OF COMPUTER SCIENCE UCD

  46. Facts and Rules together Alongside facts (unit clauses) we can have full clauses: husbandof(Woman, Man):- wifeof(Man, Woman). “For a goal involving husbandof, try a goal using wifeof, with the arguments in the other order.” | ?- husbandof(helen, peter). yes We could also have: parentof(Person1, Person2):- daughterof(Person1, Person2). parentof(Person1, Person2):- sonof(Person1, Person2). DEPT. OF COMPUTER SCIENCE UCD

  47. | ?- parentof(peter, Child). Child = mandy yes | ?- parentof(louise, peter). no | ?- parentof(Parent, peter). Parent = paul yes | ?- parentof(Parent, Child). Child = mandy Parent = peter yes DEPT. OF COMPUTER SCIENCE UCD

  48. More on backtracking Suppose we add: grandparent(OldPerson, YoungerPerson):- parentof(OldPerson, Another), parentof(Another, YoungerPerson). and try the goal: | ?- grandparent(Oldone, Youngone). DEPT. OF COMPUTER SCIENCE UCD

  49. Looks for a parentof relation. First clause says try daughterof. SUCCESS with daughterof(peter, mandy) So Another = mandy. Looks for parentof(mandy, YoungerPerson). First clause says try daughterof. None with mandy. FAILURE. Second clause suggests sonof. None with mandy. FAILURE. So second parentof goal FAILS. Try first parentof goal again. Second clause suggests sonof. SUCCESS with sonof(paul, peter) So OldPerson = paul, Another = peter. Looks for parent(peter, YoungerPerson). First clause says try daughterof. SUCCESS with daughterof(peter, mandy) So YoungerPerson) = mandy Both parentof goals successful. So grandparent goal successful (with bindings Oldone = paul, Youngone = mandy). DEPT. OF COMPUTER SCIENCE UCD

  50. Tracing “spy” shows you what is going on inside your program. | ?- spy(larger). {The debugger will first leap -- showing spypoints {Spypoint placed on user:larger/3} yes {debug} | ?- larger(8,9, Output). + 1 1 Call: larger(8,9,_195) ? 2 2 Call: 8<9 ? 2 2 Exit: 8<9 ? + 1 1 Exit: larger(8,9,9) ? Output = 9 ? yes {debug} DEPT. OF COMPUTER SCIENCE UCD

More Related