CS 403 Programming Languages Class 19 November 2
CS 403 - Programming Languages Class 19 November 2, 2000 1
Today’s Agenda Start Chapter 15 Assignment: n Read chapter 15 for today Announcement: n No programming assignment today. CS 403, Class 19 2
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 CS 403, Class 19 3
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 CS 403, Class 19 4
What is 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 CS 403, Class 19 5
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: , , X, X Everyone define these symbols CS 403, Class 19 6
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 CS 403, Class 19 7
Horn Rules 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, d) A(c, d) CS 403, Class 19 8
Horn Rules (cont. ) Note that atomic formulas are also Horn rules, often called facts. A set of Horn rules is called a Logic Program. CS 403, Class 19 9
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: n n n 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. CS 403, Class 19 10
Logical Inference Example 2: Given these facts: man(plato) man(socrates) and this rule: X [mortal(X) man(X)] derive: mortal(plato), mortal(socrates). CS 403, Class 19 11
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(plato))) (using X=son_of(plato)) mortal(son_of(son_of(plato)))) (using X=son_of(plato))) CS 403, Class 19 12
Prolog Notation A rule: X [p(X) (q(X) r(X))] is written as p(X) q(X), r(X). Prolog conventions: n n 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. n n n mortal(X) sorted([5, 3, 4, 9, 2], X) son. Of(martha, S), son. Of(george, S) Prolog program = facts+rules+query CS 403, Class 19 13
Prolog Syntax < fact > < term >. < rule > < term > : - < terms >. < query > < terms >. < term > < number > | < atom > | <variable> | < atom > ( < terms > ) < terms > < term > | < term > , < terms > CS 403, Class 19 14
Syntax Integers Atoms: user defined, supplied n name starts with lower case: john, student 2 Variables n n begin with upper case: Who, X ‘_’ can be used in place of variable name Structures n student(ali, freshman, 194). Lists n n n Constructors like student and “. ” are called functors in Prolog [x, y, Z ] [ Head | Tail ] w syntactic sugar for. ( Head, Tail ) [] CS 403, Class 19 15
Prolog Introduction /* list of facts in prolog, stored in an ascii file, ‘family. pl’*/ mother(mary, ann). mother(mary, joe). mother(sue, mar. Y ). father(mike, ann). father(mike, joe). grandparent(sue, ann). CS 403, Class 19 16
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(+var 1, -var 2, +var 3). + indicates input variable - indicates output variable CS 403, Class 19 17
/* 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 CS 403, Class 19 18
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( X , Z ) : – parent( X , Y ), parent(Y, Z ). CS 403, Class 19 19
mother(mary, ann). mother(mary, joe). mother(sue, mar. Y ). father(mike, ann). father(mike, joe). ? - parent(X, joe). X=X, Y=joe parent(X, Y) : = mother(X, joe). binding ? - mother(X, joe). mother(mary, ann). /* fails */ mother(mary, joe). /* succeeds */ parent( X , Y ) : – mother( X , Y ). parent( X , Y ) : – father( X , Y ). ? - parent( X , joe). X = mary yes CS 403, Class 19 20
? - parent( X , ann), parent( X , joe). X = mary; X = mike yes ? - grandparent(sue, Y ). Y = ann; Y = joe yes CS 403, Class 19 21
Tracing exercise /* specification of factorial n! */ factorial(0, 1). factorial(N, M): – N 1 is N – 1, factorial (N 1, M 1), M is N*M 1. Now you do it CS 403, Class 19 22
Solution CS 403, Class 19 23
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? n The list [ ] is the boundary. The length of [ ] is 0. CS 403, Class 19 24
Recursion Where do we store the value of the length? -accumulator -w length( [ ], 0 ). w 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 CS 403, Class 19 25
Recursion ? - mylength(jim, X ). no ? - mylength(Jim, X ). Jim = [ ] X=0 mymember( X , [X | _ ] ). mymember( X , [ _ | Z ] ) : – mymember( X , Z ). CS 403, Class 19 26
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 CS 403, Class 19 27
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). CS 403, Class 19 28
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 ? - CS 403, Class 19 29
Watch it work: ? - append([1, 2, 3], Y, Z). Z = [1, 2, 3|Y] CS 403, Class 19 30
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. CS 403, Class 19 31
Watch it work: ? - [length]. ? - llength([a, b, c, d], M). M=4 CS 403, Class 19 32
Length of Lists II The Program: llength([], 0). llength([X|Z], N) : - N is M + 1, llength(Z, M). CS 403, Class 19 33
Watch it work: ? - [length 2]. ? - llength([a, b, c, d], M). uncaught exception: error(instantiation_error, (is)/2) CS 403, Class 19 34
Control in Prolog I How Prolog tries to solve a query like: <query 1>, <query 2>, . . , <query. N> This is the control side of the equation: Algorithm=Logic+Control Step 1: Find Things that solve <query 1>, if none then fail else goto Step 2: Do the things found from the previous step allow more things to be found that solve <query 2>? If not then go back to step 1 else goto step 3. . . . CS 403, Class 19 35
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 CS 403, Class 19 36
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 CS 403, Class 19 37
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 CS 403, Class 19 38
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. CS 403, Class 19 39
Data Types in Prolog The primitive data types in prolog can be combined via structures, to form complex datatypes: <structure>: : = <functor>(<arg 1>, <arg 2>, . . . ) Example In the case of binary search trees we have: <bstree> : : = empty | node(<number>, <bstree>) node(15, node(2, node(0, empty), node(10, node(9, node(3, empty), node(12, empty))), node(16, empty, node(19, empty))) CS 403, Class 19 40
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). CS 403, Class 19 41
Watch it work: ? - [btree]. ? isbtree(node(9, node(3, empty), empty)). true ? yes CS 403, Class 19 42
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). CS 403, Class 19 43
Watch it work: ? - [btree]. ? - [mymember]. ? - member(3, node(10, node(9, node(3, empty), node(12, empty))). true ? yes CS 403, Class 19 44
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. CS 403, Class 19 45
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 CS 403, Class 19 46
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 sublist 1(S, Z) : - myprefix(X, Z), mysuffix(S, X). Version 2 sublist 2(S, Z) : - mysuffix(S, X), myprefix(X, Z). Version 3 sublist 3(S, Z) : - mysuffix(Y, Z), myprefix(S, Y). CS 403, Class 19 47
Watch them work: | ? - [sublist]. consulting. . sublist. plyes | ? - sublist 1([e], [a, b, c]). no | ? - sublist 2([e], [a, b, c]). Fatal Error: global stack overflow … CS 403, Class 19 48
Version 1 So what’s happening? If we ask the question: sublist 1([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, b] [a, b, c] none of which pass the verify goal, so we fail. CS 403, Class 19 49
Version 2 On the other hand, if we ask the question: sublist 2([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]. . None of which pass the verify goal, so we never terminate CS 403, Class 19 50
- Slides: 50