Presentation is loading. Please wait.

Presentation is loading. Please wait.

Derived from csc.villanova.edu/~dmatusze/8310summer2001/index.html/prolog1.ppt1 Prolog.

Similar presentations


Presentation on theme: "Derived from csc.villanova.edu/~dmatusze/8310summer2001/index.html/prolog1.ppt1 Prolog."— Presentation transcript:

1 Derived from csc.villanova.edu/~dmatusze/8310summer2001/index.html/prolog1.ppt1 Prolog

2 2 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/

3 3 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?

4 4 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

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

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

7 7 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).

8 8 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

9 9 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

10 10 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)

11 11 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).

12 12 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), wealthy(X), wise(X). The comma between structures means AND

13 13 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).

14 14 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.

15 15 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'

16 16 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'

17 17 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.)

18 18 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.

19 19 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

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

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

22 22 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.

23 23 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?

24 24 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

25 25 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 ?

26 26 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

27 27 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

28 28 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:\prolog\dragon.pl compiled 0.00 sec, 12,468 bytes true.

29 29 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.

30 30 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.

31 31 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

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

33 33 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.

34 34 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.

35 35 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.

36 36 The map cave_entrancecave meadow buildingcloset N W E S

37 37 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).

38 38 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.

39 39 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).

40 40 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.').

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

42 42 You can’t always take 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.

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

44 44 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 ! callexit

45 45 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

46 46 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

47 47 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.

48 48 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!)

49 49 Prolog II

50 50 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

51 51 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)

52 52 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)

53 53 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.

54 54 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

55 55 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.

56 56 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?

57 57 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).

58 58 Recursion ancestor(X, Y) :- child(Y, X). (X is an ancestor of Y if Y is a child of X.) 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). Handle the base cases first Recur only with a simpler case

59 59 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).

60 60 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

61 61 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]]

62 62 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].

63 63 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.

64 64 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.

65 65 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.

66 66 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).

67 67 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).

68 68 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(_).

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

70 70 "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.

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

72 72 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).

73 73 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.”

74 74 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)

75 75 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.

76 Derived from csc.villanova.edu/~dmatusze/8310summer2001/index.html/prolog1.ppt76 The End


Download ppt "Derived from csc.villanova.edu/~dmatusze/8310summer2001/index.html/prolog1.ppt1 Prolog."

Similar presentations


Ads by Google