Скачать презентацию Prolog Derived from csc villanova edu dmatusze 8310 summer 2001 index Скачать презентацию Prolog Derived from csc villanova edu dmatusze 8310 summer 2001 index

d4a1c55b2ee26d988d7e25ed50287a1f.ppt

  • Количество слайдов: 76

Prolog Derived from csc. villanova. edu/~dmatusze/8310 summer 2001/index. html/prolog 1. ppt 1 Prolog Derived from csc. villanova. edu/~dmatusze/8310 summer 2001/index. html/prolog 1. ppt 1

SWI-Prolog • SWI-Prolog is a good, standard Prolog for Windows, Mac OS X 10. SWI-Prolog • SWI-Prolog is a good, standard Prolog for Windows, Mac OS X 10. 4 and 10, 5, and Linux • It’s licensed under GPL, therefore freely available • Downloadable from: • http: //www. swi-prolog. org/ 2

Syllogisms • “Prolog” is all about programming in logic. • Aristotle described syllogisms 2300 Syllogisms • “Prolog” is all about programming in logic. • Aristotle described syllogisms 2300 years ago • Sample syllogism: – Socrates is a man. – All men are mortal. – Therefore, Socrates is mortal. • This is logic. Can Prolog do it? 3

Forward and backward reasoning • A syllogism gives two premises, then asks, “What can Forward and backward reasoning • A syllogism gives two premises, then asks, “What can we conclude? ” – This is forward reasoning -- from premises to conclusions – it's inefficient when you have lots of premises • Instead, you ask Prolog specific questions – Prolog uses backward reasoning -- from (potential) conclusions to facts 4

Syllogisms in Prolog Syllogism Prolog Socrates is a man(socrates). All men are mortal(X) : Syllogisms in Prolog Syllogism Prolog Socrates is a man(socrates). All men are mortal(X) : - man(X). Is Socrates mortal? ? - mortal(socrates). 5

Facts, rules, and queries • • Fact: Socrates is a man(socrates). Rule: All men Facts, rules, and queries • • Fact: Socrates is a man(socrates). Rule: All men are mortal(X) : - man(X). Query: Is Socrates mortal? mortal(socrates). Queries have the same form as facts 6

Running Prolog • Create your “database” (program) in any editor • Save it as Running Prolog • Create your “database” (program) in any editor • Save it as text only, with a. pl extension • Here’s the complete program: man(socrates). mortal(X) : - man(X). 7

Running Prolog continued • Prolog is completely interactive. Begin by – Double-clicking on your. Running Prolog continued • Prolog is completely interactive. Begin by – Double-clicking on your. pl file, or – Double-clicking on the Prolog application and consulting your file at the ? - prompt: • ? - consult('C: \My Programs\adv. pl'). • Then, ask your question at the prompt: – ? - mortal(socrates). • Prolog responds: – Yes 8

Prolog is a theorem prover • Prolog’s “Yes” means “I can prove it” -Prolog’s Prolog is a theorem prover • Prolog’s “Yes” means “I can prove it” -Prolog’s “No” means “I can't prove it” – ? - mortal(plato). No • This is the closed world assumption: The Prolog program knows everything it needs to know • Prolog supplies values for variables when it needs to in order to complete a “proof”: – ? - mortal(X). X = socrates 9

Syntax I: Structures • A structure consists of a name and zero or more Syntax I: Structures • A structure consists of a name and zero or more arguments. • Omit the parentheses if there are no arguments • Example structures: – sunshine – man(socrates) – path(garden, south, sundial) 10

Syntax II: Base Clauses • A base clause is just a structure. • A Syntax II: Base Clauses • A base clause is just a structure. • A base clause represents a simple fact. • Example base clauses: – debug_on. – loves(john, mary). – loves(mary, bill). 11

Syntax III: Nonbase Clauses • A nonbase clause is a structure, a “turnstile” : Syntax III: Nonbase Clauses • A nonbase clause is a structure, a “turnstile” : (meaning IF), and a list of structures. • Example nonbase clauses: – mortal(X) : - man(X). – mortal(X) : - woman(X) – happy(X) : - healthy(X), wise(X). • The comma between structures means AND 12

Syntax IV: Predicates • A predicate is a collection of clauses with the same Syntax IV: Predicates • A predicate is a collection of clauses with the same functor (name) and arity (number of arguments). • loves(john, mary). loves(mary, bill). loves(chuck, X) : - female(X), rich(X). 13

Syntax V: Programs • A program is a collection of predicates. • Predicates can Syntax V: Programs • A program is a collection of predicates. • Predicates can be in any order. • Clauses within a predicate are used in the order in which they occur. 14

Syntax VI: Variables and atoms • Variables begin with a capital letter: X, Socrates, Syntax VI: Variables and atoms • Variables begin with a capital letter: X, Socrates, _result • Atoms do not begin with a capital letter: x, socrates • Atoms containing special characters, or beginning with a capital letter, must be enclosed in single quotes: – 'C: \My Documents\examples. pl' 15

Syntax VII: Strings are atoms • In a quoted atom, a single quote must Syntax VII: Strings are atoms • In a quoted atom, a single quote must be doubled or backslashed: – 'Can''t, or won't? ' • Backslashes in file names must also be doubled: – 'C: \My Documents\examples. pl' 16

Common problems • Capitalization is extremely important! • No space is allowed between a Common problems • Capitalization is extremely important! • No space is allowed between a functor and its argument list: man(socrates), not man (socrates). • Double quotes indicate a list of ASCII character values, not a string • Don’t forget the period! (But you can put it on the next line. ) 17

Backtracking • • • loves(chuck, X) : - female(X), rich(X). female(jane). female(mary). rich(mary). ----- Backtracking • • • loves(chuck, X) : - female(X), rich(X). female(jane). female(mary). rich(mary). ----- Suppose we ask: loves(chuck, X). – female(X) = female(jane), X = jane. – rich(jane) fails. – female(X) = female(mary), X = mary. – rich(mary) succeeds. 18

Backtracking and Beads • Each Prolog call is like a “bead” in a string Backtracking and Beads • Each Prolog call is like a “bead” in a string of beads: call fail exit redo • Each structure has four ports: call, exit, redo, fail • Exit ports connect to call ports; fail ports connect to redo ports 19

Calls as nested beads loves(chuck, X) : - female(X), rich(X). loves(chuck, X) call fail Calls as nested beads loves(chuck, X) : - female(X), rich(X). loves(chuck, X) call fail female(X) rich(X) exit redo 20

Additional answers • female(jane). female(mary). female(susan). • ? - female(X). • X = jane Additional answers • female(jane). female(mary). female(susan). • ? - female(X). • X = jane ; • X = mary • Yes female(X) female(jane) female(mary) female(susan) 21

Readings • loves(chuck, X) : - female(X), rich(X). • Declarative reading: Chuck loves X Readings • loves(chuck, X) : - female(X), rich(X). • Declarative reading: Chuck loves X if X is female and rich. • Approximate procedural reading: To find an X that Chuck loves, first find a female X, then check that X is rich. • Declarative readings are almost always preferred. 22

Monotonic logic • Standard logic is monotonic: once you prove something is true, it Monotonic logic • Standard logic is monotonic: once you prove something is true, it is true forever • Logic isn't a good fit to reality • If the wallet is in the purse, and the purse in is the car, we can conclude that the wallet is in the car • But what if we take the purse out of the car? 23

Nonmonotonic logic • Prolog uses nonmonotonic logic • Facts and rules can be changed Nonmonotonic logic • Prolog uses nonmonotonic logic • Facts and rules can be changed at any time – such facts and rules are said to be dynamic • assert(. . . ) adds a fact or rule • retract(. . . ) removes a fact or rule • assert and retract are said to be extralogical predicates 24

Examples of assert and retract • • assert(man(plato)). assert((loves(chuck, X) : - female(X), rich(X))). Examples of assert and retract • • assert(man(plato)). assert((loves(chuck, X) : - female(X), rich(X))). retract(man(plato)). retract((loves(chuck, X) : - female(X), rich(X))). • Notice that we use double parentheses for rules – This is to avoid a minor syntax problem – Suppose we say: assert(foo : - bar, baz). – How many arguments did we give to assert? 25

Limitations of backtracking • In Prolog, backtracking over something generally undoes it • Output Limitations of backtracking • In Prolog, backtracking over something generally undoes it • Output can't be undone by backtracking • Neither can assert and retract be undone by backtracking • Perform any necessary testing before you use write, nl, assert, or retract 26

Modeling “real life” • Real life isn’t monotonic; things change • Prolog is superb Modeling “real life” • Real life isn’t monotonic; things change • Prolog is superb for modeling change • Games are often a model of real (or fantasy!) life • Prolog is just about ideal for adventure games 27

Starting Prolog Welcome to SWI-Prolog (Multi-threaded, 32 bits, Version 5. 6. 59) Copyright (c) Starting Prolog Welcome to SWI-Prolog (Multi-threaded, 32 bits, Version 5. 6. 59) Copyright (c) 1990 -2008 University of Amsterdam. SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. Please visit http: //www. swi-prolog. org for details. For help, use ? - help(Topic). or ? - apropos(Word) 1 ? - consult('C: \prolog\dragon. pl'). % C: prologdragon. pl compiled 0. 00 sec, 12, 468 bytes true. 28

Instructions • ? - start. • Enter commands using standard Prolog syntax. Available commands Instructions • ? - start. • Enter commands using standard Prolog syntax. Available commands are: start. -- to start the game. n. s. e. w. -- to go in that direction. take(Object). -- to pick up an object. drop(Object). -- to put down an object. use(Object). -- to use an object. attack. -- to attack an enemy. look. -- to look around you again. instructions. -- to see this message again. halt. -- to end the game and quit. 29

Starting out • You are in a meadow. To the north is the dark Starting out • You are in a meadow. To the north is the dark mouth of a cave; to the south is a small building. Your assignment, should you decide to accept it, is to recover the famed Bar-Abzad ruby and return it to this meadow. True. 30

Going south • ? - s. • You are in a small building. The Going south • ? - s. • You are in a small building. The exit is to the north. The room is devoid of furniture, and the only feature seems to be a small door to the east. There is a flashlight here. true 31

Taking things, locked doors • ? - take(flashlight). • OK. True. • ? - Taking things, locked doors • ? - take(flashlight). • OK. True. • ? - e. • The door appears to be locked. You can't go that way. True. 32

Some time later. . . • ? - use(key). • The closet is no Some time later. . . • ? - use(key). • The closet is no longer locked. True. • Later still. . . • ? - look. • You are in a big, dark cave. The air is fetid. There is a chest here. 33

Essential facts • Where I am at present: – i_am_at(meadow). • Where other things Essential facts • Where I am at present: – i_am_at(meadow). • Where other things are at: – at(flashlight, building). • What I am holding: – holding(key). • Which facts may be changed: – : - dynamic i_am_at/1, at/2, holding/1. 34

Input and output • Input is unpleasant; we avoid it by giving commands (as Input and output • Input is unpleasant; we avoid it by giving commands (as questions) directly to Prolog – take(flashlight). • write(. . . ) outputs its one argument • nl ends the line (writes a newline) • describe(closet) : write('You are in an old storage closet. '), nl. 35

The map W N S E cave_entrance cave meadow building closet 36 The map W N S E cave_entrance cave meadow building closet 36

Implementing the map • path(cave, w, cave_entrance). path(cave_entrance, e, cave). • path(meadow, s, building). Implementing the map • path(cave, w, cave_entrance). path(cave_entrance, e, cave). • path(meadow, s, building). path(building, n, meadow). • Could have done this instead: – path(cave, w, cave_entrance). path(X, e, Y) : - path(Y, w, X). 37

listing • listing(predicate) is a good way to examine the current state of the listing • listing(predicate) is a good way to examine the current state of the program • ? - listing(at). – at(key, cave_entrance). at(flashlight, building). at(sword, closet). true. 38

North, south, east, west • The commands n, s, e, w all call go. North, south, east, west • The commands n, s, e, w all call go. • n : - go(n). s : - go(s). e : - go(e). w : - go(w). 39

go • go(Direction) : i_am_at(Here), path(Here, Direction, There), retract(i_am_at(Here)), assert(i_am_at(There)), look. • go(_) : go • go(Direction) : i_am_at(Here), path(Here, Direction, There), retract(i_am_at(Here)), assert(i_am_at(There)), look. • go(_) : write('You can''t go that way. '). 40

take • take(X) : i_am_at(Place), at(X, Place), retract(at(X, Place)), assert(holding(X)), write('OK. '), nl. 41 take • take(X) : i_am_at(Place), at(X, Place), retract(at(X, Place)), assert(holding(X)), write('OK. '), nl. 41

You can’t always take(A) : holding(A), write('You're already holding it!'), nl. take(A) : - You can’t always take(A) : holding(A), write('You're already holding it!'), nl. take(A) : - (actually take something, as before). take(A) : write('I don't see it here. '), nl. 42

Making things fail • A predicate will fail if it doesn’t succeed • You Making things fail • A predicate will fail if it doesn’t succeed • You can explicitly use fail • fail works like this: call fail • This often isn't strong enough; it doesn't force the entire predicate to fail 43

cut • The “cut, ” written ! , is a commit point – It cut • The “cut, ” written ! , is a commit point – It commits to the clause in which it occurs, and – everything before it in that clause • Using cut says: Don’t try any other clauses, and don’t backtrack past the cut call ! exit 44

cut-fail • The cut-fail combination: !, fail means really fail • It commits to cut-fail • The cut-fail combination: !, fail means really fail • It commits to this clause, then fails • This means no other clauses of this predicate will be tried, so the predicate as a whole fails 45

A locked door • path(building, e, closet) : locked(closet), write('The door appears to be A locked door • path(building, e, closet) : locked(closet), write('The door appears to be locked. '), nl, !, fail. path(building, e, closet). • If the closet door isn't locked, the first clause fails “normally, ” and the second clause is used • If the closet door is locked, the cut prevents the second clause from ever being reached 46

Dropping objects drop(A) : holding(A), i_am_at(B), retract(holding(A)), assert(at(A, B)), write('OK. '), nl. drop(A) : Dropping objects drop(A) : holding(A), i_am_at(B), retract(holding(A)), assert(at(A, B)), write('OK. '), nl. drop(A) : write('You aren't holding it!'), nl. 47

What else is Prolog good for? • Prolog is primarily an AI (Artificial Intelligence) What else is Prolog good for? • Prolog is primarily an AI (Artificial Intelligence) language • It's second only to LISP in popularity • It's more popular in Britain than in the U. S. • Prolog is also a very enjoyable language in which to program (subjective opinion, obviously!) 48

Prolog II 49 Prolog II 49

The Notion of Unification • • • Unification is when two things “become one” The Notion of Unification • • • Unification is when two things “become one” Unification is kind of like assignment Unification is kind of like equality in algebra Unification is mostly like pattern matching Example: – loves(john, X) can unify with loves(john, mary) – and in the process, X gets unified with mary 50

Unification I • Any value can be unified with itself. – weather(sunny) = weather(sunny) Unification I • Any value can be unified with itself. – weather(sunny) = weather(sunny) • A variable can be unified with another variable. –X=Y • A variable can be unified with (“instantiated to”) any Prolog value. – Topic = weather(sunny) 51

Unification II • Two different structures can be unified if their constituents can be Unification II • Two different structures can be unified if their constituents can be unified. – female(X) = female(jane) – mother(mary, X) = mother(Y, father(Z)) • A variable can be unified with a structure containing that same variable. This is usually a Bad Idea. – X = f(X) 52

Unification III • The explicit unification operator is = • Unification is symmetric: Steve Unification III • The explicit unification operator is = • Unification is symmetric: Steve = father(isaac) means the same as father(isaac) = Steve • Most unification happens implicitly, as a result of parameter transmission. 53

Scope of Names • The scope of a variable is the single clause in Scope of Names • The scope of a variable is the single clause in which it appears. • The scope of the “anonymous” (“don't care”) variable, _, is itself. – loves(_, _) = loves(john, mary) • A variable that only occurs once in a clause is a useless singleton; you should replace it with the anonymous variable 54

Clauses as Cases • A predicate consists of multiple clauses, each of which represents Clauses as Cases • A predicate consists of multiple clauses, each of which represents a “case” grandson(X, Y) : - son(X, Z), son(Z, Y). grandson(X, Y) : - son(X, Z), daughter(Z, Y). abs(X, Y) : - X < 0, Y is -X. abs(X, X) : - X >= 0. 55

Ordering • Clauses are always tried in order • buy(X) : - good(X). buy(X) Ordering • Clauses are always tried in order • buy(X) : - good(X). buy(X) : - cheap(X). cheap(‘Java 2 Complete’). good(‘Thinking in Java’). • What will buy(X) choose first? 56

Ordering II • Try to handle more specific cases (those having more variables instantiated) Ordering II • Try to handle more specific cases (those having more variables instantiated) first. dislikes(john, bill). dislikes(john, X) : - rich(X). dislikes(X, Y) : - loves(X, Z), loves(Z, Y). 57

Recursion Handle the base cases first ancestor(X, Y) : - child(Y, X). (X is Recursion Handle the base cases first ancestor(X, Y) : - child(Y, X). (X is an ancestor of Y is a child of X. ) Recur only with a simpler case ancestor(X, Y) : child(Z, X), ancestor(Z, Y). (X is an ancestor of Y if Z is a child of X and Z is an ancestor of Y). 58

Basic and derived clauses • You can often choose which facts you want to Basic and derived clauses • You can often choose which facts you want to be "basic" and which derived son(isaac, steven). child(X, Y) : - son(X, Y). male(isaac). child(isaac, steven). son(X, Y) : - male(X), child(X, Y). 59

Recursive Loops • Prolog proofs must be tree structured, that is, they may not Recursive Loops • Prolog proofs must be tree structured, that is, they may not contain recursive loops. – child(X, Y) : - son(X, Y). – son(X, Y) : - child(X, Y), male(X). – ? - son(isaac, steven). <-- May loop! • Why? Neither child/2 nor son/2 is basic 60

Lists • • [ ] is the empty list. [x, 2+2, [a, b, c]] Lists • • [ ] is the empty list. [x, 2+2, [a, b, c]] is a list of three elements. The first element in the list is its “head”. The list with the head removed is the “tail”. – The head of [x, 2+2, [a, b, c]] is x – The tail is [2+2, [a, b, c]] 61

Lists • Unification can be performed on lists: – [a, b, c] = [X, Lists • Unification can be performed on lists: – [a, b, c] = [X, Y, Z] results in • results in X = a, Y = b, Z = c – [a, b, c] = [Head | Tail] • results in Head = a, Tail = [b, c] • Nonempty lists can be matched against [Head|Tail]. • Empty lists will not match [Head|Tail]. 62

Matching Heads and Tails • If [a, b, c] = [Head | Tail], then Matching Heads and Tails • If [a, b, c] = [Head | Tail], then a = Head and [b, c] = Tail • If [a, b, c] = [X, Y | Tail], then a = X, b = Y, and [c] = Tail • If [a, b, c] = [X, Y, Z | Tail], then a = X, b = Y, c = Z, and [ ] = Tail • The tail of a list is always itself a list. • [X | Y, Z] isn’t legal. 63

Recursion • Recursion is fully supported • element(1, [X | _ ], X). • Recursion • Recursion is fully supported • element(1, [X | _ ], X). • element(N, [ _ | X], Y) : M is N - 1, element(M, X, Y). • This is the typical way to process lists: do something with the head, recur with the tail. 64

member • member(X, [X | _ ]). • member(X, [ _ | Y]) : member • member(X, [X | _ ]). • member(X, [ _ | Y]) : - member(X, Y). • As usual, base cases go first, then recursive cases. • There is in general no need for a “fail” case, because that’s automatic. – member( _, [ ]) : - fail. 65

Accumulated Information • If you reach a clause, you can assume that the earlier Accumulated Information • If you reach a clause, you can assume that the earlier clauses of the same predicate have failed. • member(X, [X | _ ]). • If you fail this clause, the first element is not the one you want, so member(X, [ _ | Y] : - member(X, Y). 66

Fail Loops • It is possible to build a “fail loop” in Prolog • Fail Loops • It is possible to build a “fail loop” in Prolog • print_elements(List) : member(X, List), write(X), nl, fail. • But recursion is almost always better: print_elements([Head|Tail]) : write(Head), nl, print_elements(Tail). 67

Forcing a predicate to succeed notice_objects_at(Place) : at(X, Place), write('There is a '), write(X), Forcing a predicate to succeed notice_objects_at(Place) : at(X, Place), write('There is a '), write(X), write(' here. '), nl, fail. notice_objects_at(_). 68

Forcing a predicate to fail loves(chuck, X) : really_ugly(X), !, fail. loves(chuck, X) : Forcing a predicate to fail loves(chuck, X) : really_ugly(X), !, fail. loves(chuck, X) : female(X), rich(X). 69

"Wrapping" another predicate • The buzz_off/0 predicate might succeed or fail. This is usually what we want. • But sometimes we want to ignore failure. optional_buzz_off : buzz_off. optional_buzz_off. 70

Asserting Clauses • assert(new_clause). – assert(path(garden, n, toolshed)). – assert(( loves(chuck, X) : - Asserting Clauses • assert(new_clause). – assert(path(garden, n, toolshed)). – assert(( loves(chuck, X) : - female(X) , rich(X) )). • asserta(new_clause). • assertz(new_clause). 71

Removing clauses • retract(clause). – retract(path(garden, n, toolshed)). – retract(path(X, Y, X)). – retract(( Removing clauses • retract(clause). – retract(path(garden, n, toolshed)). – retract(path(X, Y, X)). – retract(( loves(chuck, X) : - female(X) , rich(X) )). • abolish(path, 3). 72

Marking Clauses as “Dynamic” • Standard Prolog allows you to assert and retract clauses Marking Clauses as “Dynamic” • Standard Prolog allows you to assert and retract clauses without any restrictions. • SWI-Prolog and some others require you to mark variable clauses as “dynamic. ” • : - dynamic i_am_at/1, at/2, alive/0. • The “: -” at the beginning says “do it now. ” 73

Solving problems with dynamic • If Prolog already knows a clause, and it's static, Solving problems with dynamic • If Prolog already knows a clause, and it's static, it's too late to mark it dynamic • Prolog must see : - dynamic functor/arity before it sees any clauses of functor/arity. – This includes clauses loaded in from an earlier consult • You can restart SWI-Prolog, or… • …you can use abolish(functor, arity) 74

Arithmetic • The equals sign, =, means “unify. ” • 2+2 does not unify Arithmetic • The equals sign, =, means “unify. ” • 2+2 does not unify with 4. • To force arithmetic to be performed, use “is”: X is 2 + 2, X = 4. • Comparisons =: = =/= > >= < <= also force their operands to be evaluated. • + - * / mod, when evaluated, have their usual meanings. 75

The End Derived from csc. villanova. edu/~dmatusze/8310 summer 2001/index. html/prolog 1. ppt 76 The End Derived from csc. villanova. edu/~dmatusze/8310 summer 2001/index. html/prolog 1. ppt 76