Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CS 403 - Programming Languages Class 19 November 2, 2000.

Similar presentations


Presentation on theme: "1 CS 403 - Programming Languages Class 19 November 2, 2000."— Presentation transcript:

1 1 CS 403 - Programming Languages Class 19 November 2, 2000

2 CS 403, Class 19 Slide # 2 Today’s Agenda Start Chapter 15 Assignment: Read chapter 15 for today Announcement: No programming assignment today.

3 CS 403, Class 19 Slide # 3 Objectives  What is logic, specifically, first order logic  How logic programming is related to first order logic  How Prolog embodies logic programming  Introduction to using Prolog

4 CS 403, Class 19 Slide # 4 Prolog PROgramming in LOGic Algorithm = Logic + Control Logic = relation R(I,O) between input I and output O Control = method of searching for O that satisfies R(I,O), given input I E.g. Find X and Y such that 3*X+2*Y=1 X-Y=4 E.g. find array B such that elements in B are the same as those in A elements of B are in non-descending order

5 CS 403, Class 19 Slide # 5 What is Prolog Prolog is a ‘typeless’ language with a very simple syntax. Prolog is declarative: you describe the relationship between input and output, not how to construct the output from the input (“specify what you want, not how to compute it”) Prolog uses a subset of first-order logic

6 CS 403, Class 19 Slide # 6 Classical First-Order Logic simplest form of logical statements is an atomic formula. e.g. man(tom) woman(mary) married(tom,mary) More complex formulas can be built up using logical connectives: Everyone define these symbols , , , ,  X,  X

7 CS 403, Class 19 Slide # 7 Examples of First Order Logic smart(tom)  dumb(tom) smart(tom)  tall(tom)  dumb(tom)  X married(tom,X)  X loves(tom,X)  X [married(tom,X)  female(X)  human(X)] rich(tom)   smart(tom)  X mother(john,X)  X  Y [mother(john,X)  mother(john,Y)  Y=X] Note: A  B  B   A

8 CS 403, Class 19 Slide # 8 Logic programming is based on formulas called Horn rules. These have the form Examples:  X,Y[A(X)  B(X,Y)  C(Y)]  X[A(X)  B(X)]  X[A(X,d)  B(X,e)] A(c,d)  B(d,e)  X A(X)  X A(X,d) A(c,d) Horn Rules

9 CS 403, Class 19 Slide # 9 Horn Rules (cont.)  Note that atomic formulas are also Horn rules, often called facts.  A set of Horn rules is called a Logic Program.

10 CS 403, Class 19 Slide # 10 Logical Inference with Horn Rules Logic programming is based on a simple idea: From rules and facts, derive more facts. Example 1. Given the facts and rules: 1. A 2. B 3. C 4. E  A  B 5. F  C  E 6. G  E  F From 1, derive E; from 2, derive F; from 3, derive G.

11 CS 403, Class 19 Slide # 11 Logical Inference Example 2: Given these facts: man(plato) man(socrates) and this rule:  X [mortal(X)  man(X)] derive: mortal(plato), mortal(socrates).

12 CS 403, Class 19 Slide # 12 Recursive Inference Example, given (1)  X[mortal(son_of(X))  mortal(X)] (2) mortal(plato) derive: mortal(son_of(plato)) (using X=plato) mortal(son_of(son_of(plato))) (using X=son_of(plato)) mortal(son_of(son_of(son_of(plato)))) (using X=son_of(son_of(plato)))

13 CS 403, Class 19 Slide # 13 Prolog Notation A rule:  X [p(X)  (q(X)  r(X))] is written as p(X)  q(X), r(X). Prolog conventions: variables begin with upper case (A, B, X, Y, Big, Small, ACE) constants begin with lower case (a, b, x, y, plato, aristotle) Query = list of facts with variables, e.g. mortal(X) sorted([5,3,4,9,2], X) sonOf(martha,S), sonOf(george,S) Prolog program = facts+rules+query

14 CS 403, Class 19 Slide # 14 Prolog Syntax .  :-. .  | | | ( )  |,

15 CS 403, Class 19 Slide # 15 Constructors like student and “.” are called functors in Prolog Syntax Integers Atoms: user defined, supplied name starts with lower case: john, student2 Variables begin with upper case: Who, X ‘_’ can be used in place of variable name Structures student(ali, freshman, 194). Lists [x, y, Z ] [ Head | Tail ]  syntactic sugar for. ( Head, Tail ) [ ]

16 CS 403, Class 19 Slide # 16 Prolog Introduction /* list of facts in prolog, stored in an ascii file, ‘family.pl’*/ mother(mary, ann). mother(mary, joe). mother(sue, marY ). father(mike, ann). father(mike, joe). grandparent(sue, ann).

17 CS 403, Class 19 Slide # 17 Prolog Introduction (cont.)  /* reading the facts from a file */  ?- consult ( family).  %family compiled, 0.00 sec, 828 bytes  Comments are either bound by “/*”,”*/” or any characters following the “%”.  Structures are just relationships. There are no inputs or outputs for the variables of the structures.  The swipl documentation of the built-in predicates does indicate how the variables should be used. pred(+var1, -var2, +var3). + indicates input variable - indicates output variable

18 CS 403, Class 19 Slide # 18 /* Prolog the order of the facts and rules is the order it is searched in */ /* Variation from pure logic model */ 2 ?- father( X, Y ). X = mike /* italics represents computer output */ Y = ann ; /* I type ‘;’ to continue searching the data base */ X = mike Y = joe ; no 3 ?- father( X, joe). X = mike ; no

19 CS 403, Class 19 Slide # 19 Rules parent( X, Y ) :– mother( X, Y ). /* If mother( X,Y ) then parent( X,Y ) */ parent( X, Y ) :– father( X, Y ). /* Note: grandparent(sue, ann). redundant */ /* if parent( X,Y ) and parent(Y,Z ) then grandparent( X,Z ). */ Define grandparent grandparent( X, Z ) :– parent( X, Y ),parent(Y, Z ).

20 CS 403, Class 19 Slide # 20 mother(mary, ann). mother(mary, joe). mother(sue, marY ). father(mike, ann). father(mike, joe). parent( X, Y ) :– mother( X, Y ). parent( X, Y ) :– father( X, Y ). ?- parent( X, joe). X = mary yes parent(X,Y) := mother(X,joe). ?- parent(X,joe). X=X,Y=joe mother(mary,ann). /* fails */ mother(mary,joe). /* succeeds */ ?- mother(X,joe). binding

21 CS 403, Class 19 Slide # 21 ? - parent( X, ann), parent( X, joe). X = mary; X = mike yes ?- grandparent(sue, Y ). Y = ann; Y = joe yes

22 CS 403, Class 19 Slide # 22 Tracing exercise /* specification of factorial n! */ factorial(0,1). factorial(N, M):– N1 is N – 1, factorial (N1, M1), M is N*M1. Now you do it

23 CS 403, Class 19 Slide # 23 Solution

24 CS 403, Class 19 Slide # 24 Recursion in Prolog trivial, or boundary cases ‘general’ cases where the solution is constructed from solutions of (simpler) version of the original problem itself. What is the length of a list ? THINK: The length of a list, [ e | Tail ], is 1 + the length of Tail What is the boundary condition? The list [ ] is the boundary. The length of [ ] is 0.

25 CS 403, Class 19 Slide # 25 Recursion Where do we store the value of the length?-- accumulator --  length( [ ], 0 ).  length([H | T], N) :- length(T,Nx), N is Nx + 1 mylength( [ ], 0). mylength( [X | Y], N):–mylength(Y, Nx), N is Nx+1. ? – mylength( [1, 7, 9], X ). X = 3

26 CS 403, Class 19 Slide # 26 Recursion ? - mylength(jim, X ). no ? - mylength(Jim, X ). Jim = [ ] X = 0 mymember( X, [X | _ ] ). mymember( X, [ _ | Z ] ) :– mymember( X, Z ).

27 CS 403, Class 19 Slide # 27 Recursion % equivalently: However swipl will give a warning %Singleton variables : Y W mymember( X, [X | Y] ). mymember( X, [W | Z ] ) :– mymember( X, Z ). 1?–mymember(a, [b, c, 6] ). no 2? – mymember(a, [b, a, 6] ). yes 3? – mymember( X, [b, c, 6] ). X = b; X = c; X = 6; no

28 CS 403, Class 19 Slide # 28 Appending Lists I The Problem: Define a relation append(X,Y,Z) to mean that X appended to Y yields Z The Program: append([], Y, Y). append([H|X], Y, [H|Z]) :- append(X,Y,Z).

29 CS 403, Class 19 Slide # 29 Watch it work: ?- [append]. ?- append([1,2,3,4,5],[a,b,c,d],Z). Z = [1,2,3,4,5,a,b,c,d]?; no ?- append(X,Y,[1,2,3]). X = [] Y = [1,2,3]?; X = [1] Y = [2,3]?; X = [1,2] Y = [3]?; X = [1,2,3] Y = []?; no ?-

30 CS 403, Class 19 Slide # 30 Watch it work: ?- append([1,2,3],Y,Z). Z = [1,2,3|Y]

31 CS 403, Class 19 Slide # 31 Length of Lists I The Problem: Define a relation llength(L,N) to mean that the length of the list L is N. The Program: llength([],0). llength([X|Z],N):- llength(Z,M), N is M + 1.

32 CS 403, Class 19 Slide # 32 Watch it work: ?- [length]. ?- llength([a,b,c,d],M). M=4

33 CS 403, Class 19 Slide # 33 Length of Lists II The Program: llength([],0). llength([X|Z],N) :- N is M + 1, llength(Z,M).

34 CS 403, Class 19 Slide # 34 Watch it work: ?- [length2]. ?- llength([a,b,c,d],M). uncaught exception: error(instantiation_error,(is)/2)

35 CS 403, Class 19 Slide # 35 Control in Prolog I How Prolog tries to solve a query like:,,...., This is the control side of the equation: Algorithm=Logic+Control Step 1: Find Things that solve, if none then fail else goto Step 2 Step 2: Do the things found from the previous step allow more things to be found that solve ? If not then go back to step1 else goto step 3.......

36 CS 403, Class 19 Slide # 36 Control in Prolog I Prolog tries to solve the clauses from left to right If there is a database file around it will use it in a similarly sequential fashion. 1. Goal Order: Solve goals from left to right. 2. Rule Order: Select the first applicable rule, where first refers to their order of appearance in the program/file/database

37 CS 403, Class 19 Slide # 37 Control in Prolog II The actual search algorithm is: 1. start with a query as the current goal. 2. WHILE the current goal is non-empty DO choose the leftmost subgoal ; IF a rule applies to the subgoal THEN select the first applicable rule; form a new current goal; ELSE backtrack; SUCCEED

38 CS 403, Class 19 Slide # 38 Control in Prolog II Note 1: Thus the order of the queries is of paramount importance. Note 2: The general paradigm in Prolog is Guess then Verify: Queries with the fewest solutions should come first, followed by those that filter or verify these few solutions

39 CS 403, Class 19 Slide # 39 Binary Search Trees I An example of user defined data structures. The Problem: Recall that a binary search tree (with integer labels) is either : 1. the empty tree empty,or 2. a node labelled with an integer N, that has a left subtree and a right subtree, each of which is a binary search tree such that the nodes in the left subtree are labelled by integers strictly smaller than N, while those in the right subtree are strictly greater than N.

40 CS 403, Class 19 Slide # 40 Data Types in Prolog The primitive data types in prolog can be combined via structures,to form complex datatypes: ::= (,,...) Example In the case of binary search trees we have: ::= empty | node(,, ) node(15,node(2,node(0,empty,empty), node(10,node(9,node(3,empty,empty), empty), node(12,empty,empty))), node(16,empty,node(19,empty,empty)))

41 CS 403, Class 19 Slide # 41 Binary Search Trees II The Problem: Define a unary predicate isbstree which is true only of those trees that are binary search trees. The Program isbtree(empty). isbtree(node(N,L,R)):- number(N),isbtree(L),isbtree(R), smaller(N,R),bigger(N,L). smaller(N,empty). smaller(N, node(M,L,R)) :- N < M, smaller(N,L), smaller(N,R). bigger(N, empty). bigger(N, node(M,L,R)) :- N > M, bigger(N,L), bigger(N,R).

42 CS 403, Class 19 Slide # 42 Watch it work:  ?- [btree].  ?- isbtree(node(9,node(3,empty,empty),empty)).  true ?  yes

43 CS 403, Class 19 Slide # 43 Binary Search Trees III The Problem: Define a relation which tells whether a particular number is in a binary search tree. mymember(N,T) should be true if the number N is in the tree T. The Program mymember(K,node(K,_,_)). mymember(K,node(N,S,_)) :- K < N,mymember(K,S). mymember(K,node(N,_,T)) :- K > T,mymember(K,T).

44 CS 403, Class 19 Slide # 44 Watch it work: ?- [btree]. ?- [mymember]. ?- member(3, node(10,node(9,node(3,empty,empty),empty), node(12,empty,empty))). true ? yes

45 CS 403, Class 19 Slide # 45 Unification Unification is a more general form of pattern matching. In that pattern variables can appear in both the pattern and the target. The following summarizes how unification works: 1. a variable and any term unify 2. two atomic terms unify only if they are identical 3. two complex terms unify if they have the same functor and their arguments unify.

46 CS 403, Class 19 Slide # 46 Prolog Search Trees Summary  1. Goal Order affects solutions  2. Rule Order affects Solutions  3. Gaps in Goals can creep in  4. More advanced Prolog programming manipulates the searching

47 CS 403, Class 19 Slide # 47 Sublists (Goal Order)  Two definitions of S being a sublist of Z use: myappend([], Y, Y). myappend([H|X], Y, [H|Z]) :- myappend(X,Y,Z). & myprefix(X,Z) :- myappend(X,Y,Z). mysuffix(Y,Z) :- myappend(X,Y,Z). Version 1 sublist1(S,Z) :- myprefix(X,Z), mysuffix(S,X). Version 2 sublist2(S,Z) :- mysuffix(S,X), myprefix(X,Z). Version 3 sublist3(S,Z) :- mysuffix(Y,Z), myprefix(S,Y).

48 CS 403, Class 19 Slide # 48 Watch them work: | ?- [sublist]. consulting....sublist.plyes | ?- sublist1([e], [a,b,c]). no | ?- sublist2([e], [a,b,c]). Fatal Error: global stack overflow …

49 CS 403, Class 19 Slide # 49 Version 1 So what’s happening? If we ask the question: sublist1([e], [a,b,c]). this becomes prefix(X,[a,b,c]), suffix([e],X). and using the guess-query idea we see that the first goal will generate four guesses: [] [a] [a,b] [a,b,c] none of which pass the verify goal, so we fail.

50 CS 403, Class 19 Slide # 50 Version 2 On the other hand, if we ask the question: sublist2([e], [a,b,c]) this becomes suffix([e],X),prefix(X,[a,b,c]). using the guess-query idea note: Goal will generate an infinite number of guesses. [e] [_,e] [_,_,e] [_,_,_,e] [_,_,_,_,e] [_,_,_,_,_,e].... None of which pass the verify goal, so we never terminate


Download ppt "1 CS 403 - Programming Languages Class 19 November 2, 2000."

Similar presentations


Ads by Google