CSE 452 Programming Languages Logical Programming Languages Part





























































![List Structures u Other Examples: newlist([X|Y] u This will instantiate X to apple and List Structures u Other Examples: newlist([X|Y] u This will instantiate X to apple and](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-62.jpg)
![List Structures u Append: | ? - append(([bob, jo], [jake, darcie], X). produces the List Structures u Append: | ? - append(([bob, jo], [jake, darcie], X). produces the](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-63.jpg)
![List Structures u Writing your own append function: | ? - myappend([], [banana, eggs, List Structures u Writing your own append function: | ? - myappend([], [banana, eggs,](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-64.jpg)
![List Structures u Writing your own append function: myappend([ ], List). myappend([Head 1|Tail 1], List Structures u Writing your own append function: myappend([ ], List). myappend([Head 1|Tail 1],](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-65.jpg)
![List Structures u Write your own reverse function myreverse([], []). myreverse([Head|Tail], List) : myreverse(Tail, List Structures u Write your own reverse function myreverse([], []). myreverse([Head|Tail], List) : myreverse(Tail,](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-66.jpg)
![List Structures u Write your own member function: mymember(Element, [Element|_]). mymember(Element, [_|List]) : member(Element, List Structures u Write your own member function: mymember(Element, [Element|_]). mymember(Element, [_|List]) : member(Element,](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-67.jpg)
![Size | ? - size([a, b, c], N). N = 3 ? yes u Size | ? - size([a, b, c], N). N = 3 ? yes u](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-68.jpg)























![Delete an Element from a List u Base step: l delete. Elem(_, []). %% Delete an Element from a List u Base step: l delete. Elem(_, []). %%](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-92.jpg)

![Combining Lists combine([], List). combine(List, [], List). combine([H|T], [H 2|T 2], [H, H 2|Res]) Combining Lists combine([], List). combine(List, [], List). combine([H|T], [H 2|T 2], [H, H 2|Res])](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-94.jpg)

![Sublist u use it in different ways: sublist([c, d, e], [a, b, c, d, Sublist u use it in different ways: sublist([c, d, e], [a, b, c, d,](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-96.jpg)


![Quick Sort u Base step: l quick. Sort([], []). u Recursive step: l quick. Quick Sort u Base step: l quick. Sort([], []). u Recursive step: l quick.](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-99.jpg)
![Partition u Base step: l partition([ ], P, [ ]). u Recursive step: l Partition u Base step: l partition([ ], P, [ ]). u Recursive step: l](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-100.jpg)
![Quick Sort (Summary) quick. Sort([ ], [ ]). quick. Sort([P | T], Y) : Quick Sort (Summary) quick. Sort([ ], [ ]). quick. Sort([P | T], Y) :](https://slidetodoc.com/presentation_image_h2/3f935ceadd14dacb93886e9aff27865e/image-101.jpg)
- Slides: 101
CSE 452: Programming Languages Logical Programming Languages Part 1
Combine Three PPTs u Programming l l l Languages-Cheng (Fall 2004) http: //www. cse. msu. edu/~cse 452/Fall 2004/Lectures/14 -prolog-part 1. ppt http: //www. cse. msu. edu/~cse 452/Fall 2004/Lectures/14 -prolog-part 2. ppt http: //www. cse. msu. edu/~cse 452/Fall 2004/Lectures/14 -prolog-part 3. ppt Organization of Programming Languages-Cheng (Fall 2004) 2
Outline u Another programming paradigm: l Logic Programming u Prolog l We’ll be using GNU prolog (http: //www. gnu. org/software/gprolog. ht ml) Organization of Programming Languages-Cheng (Fall 2004) 3
Another Paradigm QUESTION: "What is a computer program? " ANSWER: "It is an executable representation of some algorithm designed to solve some real world problem. " u Kowalski (CACM, 1979): There are two key elements to a computer program l Logic – what we want the program to achieve l Control – how we are going to achieve it ALGORITHM = LOGIC + CONTROL u Difference between imperative and declarative programming Organization of Programming Languages-Cheng (Fall 2004) 4
Example: Computing Factorial Imperative (Ada) implementation Declarative (PROLOG) implementation with CS_IO ; use CS_IO ; procedure FACTORIAL is N: integer; T: integer: = 1; begin put("Input "); get(N); for K in 2. . N loop T: = T*K; end loop; put("Factorial "); put(N); put("is "); put(T); newline; end FACTORIAL; u For imperative language programmer needs to concentrate on both the logic and control factorial(0, 1): !. factorial(N 1, T 2): N 2 is N 1 -1, factorial(N 2, T 1), T 2 is N 1*T 1. u For declarative language, we define the logic (the desired goal or result) but not the control (how we achieve the desired goal) Organization of Programming Languages-Cheng (Fall 2004) 5
Declarative Languages u Declarative languages make extensive use of relationships between objects u There are two principal styles of defining relationships: 1. Functional Programming u u 2. Relationships are expressed using functions. (define (square n) (* n n)) The square function expresses the relationship between the input n and the output value n*n Logic programming u u Relationships are declared using expressions known as clauses. square(N, M): M is N*N. Clauses can be used to express both facts and rules Organization of Programming Languages-Cheng (Fall 2004) 6
What is logic? u Encyclopedia Brittanica: l Logic is the study of propositions and their use in argumentation u Encarta Encyclopedia: l Logic is the science dealing with the principles of valid reasoning and argument u Factasia Logic: l Logic is the study of necessary truths and of systematic methods for expressing and demonstrating such truths Organization of Programming Languages-Cheng (Fall 2004) 7
Logic Programming u Logic programming l l u Logic programs are declarative rather than procedural l u expresses programs in the form of symbolic logic uses a logical inferencing process for reasoning Programs do not state exactly how a result is to be computed but rather describe the form of the result It is assumed that the computer can determine how the result is to be obtained One needs to provide the computer with the relevant information and a method of inference for computing desirable results Programming languages based on symbolic logic are called logic programming languages l Prolog is the most widely used logic programming language Organization of Programming Languages-Cheng (Fall 2004) 8
Terminology u Proposition l a logical statement that may be true or false u Symbolic logic is used for three purposes: l express propositions l express the relationships between propositions l describe how new propositions may be inferred from others u Two primary forms of symbolic logic l Propositional calculus l Predicate calculus u Predicate calculus is the form of symbolic logic used for logic programming Organization of Programming Languages-Cheng (Fall 2004) 9
Propositions u Objects in logic programming propositions are l Constants u symbols that represent an object u Example: man, jake, like bob, and steak l Variables u symbols that can represent different objects at different times u Atomic propositions are the simplest propositions and consist of compound terms Organization of Programming Languages-Cheng (Fall 2004) 10
Atomic Propositions u u Compound term has two parts l functor: symbol that names the relation l an ordered list of parameters Examples: man (jake) like (bob, steak) l Compound term with single parameter called a 1 -tuple; Compound term with two params is called a 2 -tuple, etc. These propositions have no intrinsic semantics l father (john, jake) could mean several things Propositions are stated in two modes l fact: one in which the proposition is defined to be true l query: one in which the truth of the proposition is to be determined Organization of Programming Languages-Cheng (Fall 2004) 11
Compound Propositions u Compound propositions have two or more atomic propositions connected by logical operators Name negation conjunction disjunction equivalence implication Symbol Example Meaning a not a a b a and b a b a or b a b a is eqv to b a b a implies b a b b implies a (in prolog a b is written as a : - b) Organization of Programming Languages-Cheng (Fall 2004) 12
Compound Propositions Compound proposition examples: a b c a b d equivalent to (a ( b)) d Precedence of logical connectors: highest precedence , , next , lowest precedence Organization of Programming Languages-Cheng (Fall 2004) 13
Compound Proposition u Implication: p q l Meaning: u if p then q up implies q up is the premise or antecedent u q is the conclusion or consequent u Can write p q in disjunctive normal form p OR q u Truth table shows equivalence Organization of Programming Languages-Cheng (Fall 2004) 14
p q Equivalent to p OR q Organization of Programming Languages-Cheng (Fall 2004) 15
Propositions with Quantifiers Variables may appear in propositions - only when introduced by symbols called quantifiers Name universal existential Example X. P Meaning For all X, P is true There exists a value of X such that P is true Note: the period separates the variable from the proposition Organization of Programming Languages-Cheng (Fall 2004) 16
Propositions with Quantifiers u Examples of propositions with quantifiers l X. (woman(X) human(X)) For any value of X, if X is a woman, then X is human X. (mother(mary, X) male (X)) There exists a value of X, such that mary is the mother of X and X is a male l Note: quantifiers have a higher precedence than any of the logical operators Organization of Programming Languages-Cheng (Fall 2004) 17
First Order Predicate Calculus Provides a method of expressing collections of propositions l Collection of propositions can be used to determine whether any interesting or useful facts can be inferred from them 0 is a natural number. 2 is a natural number. For all X, if X is a natural number, then so is successor of X. -1 is a natural number u Predicate calculus: natural (0) natural (2) X. natural (X) natural (successor (X)) natural (-1) u Organization of Programming Languages-Cheng (Fall 2004) 18
First-Order Predicate Calculus A horse is a mammal A human is a mammal Mammals have four legs and no arms, or two legs and two arms A horse has no arms A human has no legs mammal (horse) mammal (human) X. mammal (X) legs (X, 4) arms (X, 0) legs (X, 2) arms (X, 2) arms (horse, 0) legs (human, 0) Organization of Programming Languages-Cheng (Fall 2004) 19
Clausal Form u Redundancy is a problem with predicate calculus l there are many different ways of stating propositions that have the same meaning u l u Example: p q p OR q (p AND q) not a problem for logicians but for computerized system, redundancy is a problem Clausal form is one standard form of propositions used for simplification and has the syntax: B 1 B 2 . . . Bn A 1 A 2 . . . Am Meaning: If all As are true, then at least one B is true Organization of Programming Languages-Cheng (Fall 2004) 20
Clausal Form u Characteristics l Existential quantifiers are not required l Universal quantifiers are implicit in the use of variable in the atomic propositions l Only the conjunction and disjunction operators are required l Disjunction appears on the left side of the clausal form and conjunction on the right side l The left side is called the consequent l The right side is called the antecedent Organization of Programming Languages-Cheng (Fall 2004) 21
Clausal Form Examples likes (bob, trout) likes (bob, fish) fish (trout) Meaning: if bob likes fish and a trout is a fish, then bob likes trout father(louis, al) father(louis, violet) father(al, bob) mother(violet, bob) grandfather(louis, bob) Meaning: if al is bob’s father and violet is bob’s mother and louis is bob’s grandfather, then louis is either al’s father or violet’s father Organization of Programming Languages-Cheng (Fall 2004) 22
Theorems u One of the most significant breakthroughs in automatic theorem-proving was the discovery of the resolution principle by Robinson in 1965 u Resolution is an inference rule that allows inferred propositions to be computed from given propositions l Resolution was devised to be applied to propositions in clausal form Organization of Programming Languages-Cheng (Fall 2004) 23
Resolution u The concept of resolution is the following: Given two propositions: P 1 P 2 Q 1 Q 2 Suppose P 1 is identical to Q 2 and we rename them as T. Then T P 2 Q 1 T Resolution: Since P 2 implies T and T implies Q 1, it is logically obvious that P 2 implies Q 1 P 2 Organization of Programming Languages-Cheng (Fall 2004) 24
Resolution Example u u Consider the two propositions: older (joanne, jake) mother (joanne, jake) wiser (joanne, jake) older (joanne, jake) Mechanics of Resolution 1. Terms on the left hand side are ANDed together 2. Terms on the right hand side are ANDed together older (joanne, jake) wiser (joanne, jake) mother (joanne, jake) older (joanne, jake) 3. Any term that appears on both sides of the new proposition is removed from both sides wiser (joanne, jake) mother (joanne, jake) Organization of Programming Languages-Cheng (Fall 2004) 25
Resolution Expanded Example u Given father(bob, jake) mother(bob, jake) parent (bob, jake) grandfather(bob, fred) father(bob, jake) father(jake, fred) u The resolution process cancels the common term on both the left and right sides mother(bob, jake) grandfather(bob, fred) parent (bob, jake) father(jake, fred) Organization of Programming Languages-Cheng (Fall 2004) 26
Resolution for Variables u Presence of variables in propositions requires resolution to find values for those variables that allow the matching process to succeed u Unification l The process of determining useful values for variables in propositions to find values for variables that allow the resolution process to succeed. u Instantiation l The temporary assigning of values to variables to allow unification Organization of Programming Languages-Cheng (Fall 2004) 27
Example u Add facts -- what is known -parent(sue, tom). parent(bob, kate). parent(tom, laura). parent(tom. mark). parent(mark, anne). u sue bob tom laura Query: kate mark anne ? - parent(tom, X). X = laura ; X = mark ; Organization of Programming Languages-Cheng (Fall 2004) 28
Resolution for Variables u Inconsistency detection l An important property of resolution is its ability to detect any inconsistency in a given set of propositions l This property allows resolution to be used to prove theorems u Theorem proving l Use negation of theorem as a new proposition l Theorem is negated so that resolution can be used to prove theorem by finding an inconsistency u This is the basis for proof by contradiction Organization of Programming Languages-Cheng (Fall 2004) 29
Example u Facts: A. B A. u Given the facts, prove that B is true l Query: B (add new proposition) l Resolution: A B A u. B u Contradicts with B u So, conclude that B is false u Therefore, B is true u Organization of Programming Languages-Cheng (Fall 2004) 30
Horn Clauses u Recall that a clausal form has the following form: B 1 B 2 . . . Bn A 1 A 2 . . . Am u When propositions are used for resolution, only a restricted kind of clausal form can be used Horn clauses l special kind of clausal form to simplify resolution l two forms: u single atomic proposition on the left side, or u an empty left side u l l left side of Horn clause is called the head Horn clauses with left sides are called headed Horn clauses Organization of Programming Languages-Cheng (Fall 2004) 31
Horn Clauses u Headed Horn clauses are used to state relationships: likes(bob, trout) likes (bob, fish) fish(trout) u Headless Horn clauses are used to state facts: father(bob, jake) u Most propositions may be stated as Horn clauses Organization of Programming Languages-Cheng (Fall 2004) 32
Semantics u Semantics of logic programming languages are called declarative semantics l meaning of propositions can be determined from the statements themselves u Unlike imperative languages where semantics of a simple assignment statement requires examination of l local declarations, knowledge of scoping rules of the language, and possibly, examination of programs in other files to determine the types of variables Organization of Programming Languages-Cheng (Fall 2004) 33
Origins of Prolog u Colmerauer and Roussle (University of Aix-Marseille) and Kowalski (University of Edinburgh) developed the fundamental design of Prolog u Collaboration between both universities continued until mid -70 s when independent efforts kicked off resulting in two syntactically different dialects of Prolog u With Japan’s announcement of a project called Fifth Generation Computing Systems in 1981, came their choice of Prolog to develop intelligent machines l This results in strong sudden interest in logic programming and AI in U. S. and Europe Organization of Programming Languages-Cheng (Fall 2004) 34
Prolog - Basic Elements - Terms u u A Prolog term is a constant, a variable, or a structure A constant is either an atom or an integer l Atoms are the symbolic values of Prolog u u u Either a string of letters, digits, and underscores that begins with a lowercase letter or a string of any printable ASCII characters delimited by apostrophes Variable l Any string of letters, digits, and underscores that begins with an uppercase letter l not bound to types by declarations l binding of a value (and type) to a variable is called an instantiation l Instantiations last only through completion of goal Structures represent the atomic proposition of predicate calculus l form is functor (parameter list) u u Functor can be any atom and is used to identify the structure Parameter list can be any list of atoms, variables, or other structures Organization of Programming Languages-Cheng (Fall 2004) 35
Prolog – Fact Statements u Fact statements are used to construct hypotheses from which new information may be inferred u Fact statements are headless Horn clauses assumed to be true u Examples: l male(bill). l female(mary). l male(jake). l father(bill, jake). l mother(mary, jake) Organization of Programming Languages-Cheng (Fall 2004) 36
Prolog - Rule Statements u Rule statements are headed Horn clauses for constructing the database u The RHS is the antecedent(if), and the LHS is the consequent(then) u Consequent is a single term because it is a Horn clause u Conjunctions may contain multiple terms that are separated by logical ANDs or commas, e. g. female(shelley), child (shelley). Organization of Programming Languages-Cheng (Fall 2004) 37
Prolog - Rule Statements u General form of the Prolog headed Horn clause consequence_1 : - antecedent_expression u Example: ancestor(mary, shelley) : - mother(mary, shelley). u Variables can be used to generalize meanings of statements parent(X, Y) : - mother (X, Y). parent(X, Y) : - father(X, Y). grandparent(X, Z) : - parent(X, Y), parent (Y, Z). sibling(X, Y) : - mother(M, X), mother(M, Y), father(F, X), father(F, Y). l These statements give rules of implication among some variables, or universal objects (universal objects are X, Y, Z, M, and F) Organization of Programming Languages-Cheng (Fall 2004) 38
Prolog - Goal Statements u Facts and Rules are used to prove or disprove a theorem that is in the form of a proposition (called goal or query) u Syntactic form of Prolog goal statement is identical to headless Horn clauses: e. g. man (fred). to which the system will respond yes or no u Conjunctive propositions and propositions with variables are also legal goals. For example, l father (X, mike). l When variables are present, the system identifies the instantiations of the variables that make the goal true Organization of Programming Languages-Cheng (Fall 2004) 39
Prolog - Basic Elements u Because goal and some nongoal statements have the same form (headless Horn clauses), it is imperative to distinguish between the two u Interactive Prolog implementations do this by simply having two modes, indicated by different prompts: one for entering goals and one for entering fact and rule statements u Gnu Prolog uses ? - for goals Organization of Programming Languages-Cheng (Fall 2004) 40
Horn Clauses in Prolog A : - B 1, … , Bn. Head Body End of clause marker u “ if ” Rule l The head and the body are nonempty. l The body is the conditional part. l The head is the conclusion. u Fact l The body is empty, and is written as: A. Organization of Programming Languages-Cheng (Fall 2004) 41
Inferencing Process of Prolog u Goals (queries) may be compound propositions; each of facts (structures) is called a subgoal u Father(X, Y), Likes(X, steak). u The inferencing process must find a chain of inference rules/facts in the database that connect the goal to one or more facts in the database l If Q is the goal, then either u. Q must be found as fact in the database, or u the inferencing process must find a sequence of propositions that give that result Organization of Programming Languages-Cheng (Fall 2004) 42
Inferencing Process of Prolog u Matching l the process of proving(or satisfying) a subgoal by a proposition-matching process u Consider the goal or query: man(bob). If the database includes the fact man(bob), the proof is trivial If the database contains the following fact and inference father (bob). man (X) : - father (X) Prolog would need to find these and infer the truth. This requires unification to instantiate X temporarily to bob Organization of Programming Languages-Cheng (Fall 2004) 43
Inferencing Process of Prolog u Consider the goal: man(X). l Prolog must match the goal against the propositions in the database. l The first proposition that it finds that has the form of the goal, with an object as its parameter, will cause X to be instantiated with that object’s value and this result displayed l If there is no proposition with the form of the goal, the system indicates with a no that the goal can’t be satisfied Organization of Programming Languages-Cheng (Fall 2004) 44
Inferencing Process of Prolog u Solution Search Approaches l Depth-first u finds a complete sequence of propositions-a prooffor the first subgoal before working on the others l Breadth-first u works on all subgoals of a given goal in parallel l Backtracking u when the system finds a subgoal it cannot prove, it reconsiders the previous one to attempt to find an alternative solution and then continue the searchmultiple solutions to a subgoal result from different instantiations of its variables Organization of Programming Languages-Cheng (Fall 2004) 45
Inferencing Process – Backtracking u u u Suppose we have the following compound goal: l male (X), parent (X, shelley) l Is there an instantiation of X, such that X is a male and X is a parent of shelley? The search l Prolog finds the first fact in the database with male as its functor; it then instantiates X to the parameter of the found fact, say john l Then it attempts to prove that parent(john, shelley) is true l If it fails, it backtracks to the first subgoal, male(X) and attempts to satisfy it with another alternative to X More efficient processing possible Organization of Programming Languages-Cheng (Fall 2004) 46
CSE 452: Programming Languages Logical Programming Languages Part 2 Organization of Programming Languages-Cheng (Fall 2004) 47
Prolog Statements u u Prolog statements consist of facts, rules, and queries. Example of facts (written as headless Horn clauses) male(tony). male(greg). female(nikki). female(karen). u Example of rules (written as headed Horn clauses) sister(X, Y) : - parent(Z, X), parent(Z, Y), female(X), X = Y. u Facts and Rules are stored in a file with extension. pl Organization of Programming Languages-Cheng (Fall 2004) 48
Loading the Knowledge Base u Suppose the facts and rules are stored in a file called c: classesprologgender. pl u To load the file: | ? - ['C: /classes/prolog/gender']. or | ? - consult('C: /classes/prolog/gender'). Organization of Programming Languages-Cheng (Fall 2004) 49
Prolog Statements u Goal/Query statements l Also in the form of headless Horn clauses | ? - male(tony). yes | ? - female(X). X = nikki ? ; X = karen yes Organization of Programming Languages-Cheng (Fall 2004) 50
Query/Goal Statement u A query can just be an assertion of a fact l Prolog will try to establish whether that fact can be shown to be true – 1 u Alternatively, a query can contain variables l Prolog will try to find values for the variables that make the query true l Variables are written with initial uppercase letters. l Prolog will print the variable values one by one. After each one, type “; ” to see the next value (solution), u “RETURN” to accept the last value (solution), or u “a” to print all values u Organization of Programming Languages-Cheng (Fall 2004) 51
Inference Process u Given a goal/query, how does Prolog match the goal against the propositions in the database? u In general, there are two approaches: l Forward chaining (bottom-up resolution) u l Backward chaining (top-down resolution) u u System begin with the facts and rules of the database and attempt to find a sequence of matches that lead to the goal System begin with the goal and attempts to find a sequence of matching propositions that lead to some set of original facts in the database Prolog implementation uses backward chaining Organization of Programming Languages-Cheng (Fall 2004) 52
Inference Process (Example) u Example: l Given the following facts and rules: father(bob). man(X) : - father(X). l Given the following goal/query: man(bob). u Forward chaining: l Start with the first proposition: father(bob). l Goal is inferred by matching father(bob) to right side of the second rule u This leads to the goal man(bob). Organization of Programming Languages-Cheng (Fall 2004) 53
Inference Process (Example) u Example: l Given the following facts and rules: father(bob). man(X) : - father(X). l u Given the following goal/query: man(bob). Backward chaining: l Start with the goal: man(bob). l Match the goal to the left-hand side of second proposition u l This would instantiate X to bob Match the right side of the second proposition (father(bob)) to the first proposition Organization of Programming Languages-Cheng (Fall 2004) 54
Inferencing Process of Prolog u What if there are more than one rule that matches a proposition? Which rule should be used next? father(bob). man(X) : - married(Y, Z), son(X, Y). man(X) : - father(X, Y). man(X) : - brother(X, Y). u Solution Search Approaches l Depth-first u l Breadth-first u l finds a complete sequence of propositions-a proof-for the first subgoal before working on the others works on all subgoals of a given goal in parallel Backtracking u when the system finds a subgoal it cannot prove, it reconsiders the previous one to attempt to find an alternative solution and then continue the search- multiple solutions to a subgoal result from different instantiations of its variables Organization of Programming Languages-Cheng (Fall 2004) 55
Simple Arithmetic u Prolog supports integer variables and integer arithmetic l + (7, 5). produces an answer equals to 12 l A is 5. l How about this statement: Sum is Sum + Number u Since Sum is not instantiated, the reference to it on the RHS is undefined and the clause fails Organization of Programming Languages-Cheng (Fall 2004) 56
Simple Arithmetic Continued u Given the following facts: speed( ford, 100). speed(chevy, 105). speed(dodge, 95). time(ford, 20). time(chevy, 21). time(dodge, 24). u u We can calculate distance with this rule: distance(X, Y) : - speed(X, Speed), time(X, Time), Y is Speed * Time Query: | ? - distance(chevy, Chevy_Distance). will instantiate Chevy_Distance to 105*21 = 2205 Organization of Programming Languages-Cheng (Fall 2004) 57
Tracing the Process u u Prolog has a built-in structure named trace that displays instantiations of values to variables at each step during the attempt to satisfy a given goal l trace is used to understand debug Prolog pgms Tracing model l describes Prolog execution in terms of 4 events Call, which occurs at beginning of an attempt to satisfy a goal u Exit, which occurs when a goal has been satisfied u Redo, which occurs when backtrack causes an attempt to resatisfy a goal u Fail, which occurs when a goal fails u u In Gnu prolog: l trace l Notrace % This will switch on the trace mode % This will switch off the trace mode Organization of Programming Languages-Cheng (Fall 2004) 58
Tracing the Process u u Consider the following example database and goal: likes(jake, chocolate). likes(jake, apricots). likes(darcie, licorice). likes(darcie, apricots). ? -likes(jake, X), likes(darcie, X). the goal/query Trace Process: (1) Call: likes(jakes, _0)? (1) Exit: likes(jakes, chocolate) (2) Call: likes(darcie, chocolate)? (2) Fail: likes(darcie, chocolate) (1) Redo: likes(jake, _0)? (1) Exit: likes(jake, apricots) (2) Call: likes(darcie, apricots)? (2) Exit: likes(darcie, apricots) X = apricots Organization of Programming Languages-Cheng (Fall 2004) % This is 59
List Structures u Prolog uses the syntax of ML and Haskell to specify lists l List elements are separated by commas, and the entire list is delimited by square brackets l Example: [apple, prune, grape, kumquat] l Example: [ ] means empty list u Like Haskell, Prolog uses the special notation u[ X | Y ] to indicate head X and tail Y u head and tail correspond CAR and CDR in LISP Organization of Programming Languages-Cheng (Fall 2004) 60
List Structures u Example: l Consider the following facts and rules: newlist([apple, apricot, pear, banana]). first(X) : - newlist([X|Y]). u In query mode, first(X). l statement instantiates X with apple Organization of Programming Languages-Cheng (Fall 2004) 61
List Structures u Other Examples: newlist([X|Y] u This will instantiate X to apple and Y to [apricot, pear, banana] newlist([apple, appricot|X]). u This will instantiate X to [pear, banana] Organization of Programming Languages-Cheng (Fall 2004) 62
List Structures u Append: | ? - append(([bob, jo], [jake, darcie], X). produces the output X = [bob, jo, jake, darcie] u Reverse: | ? - reverse([bob, jo, jake, darcie], X). produces the output X = [darcie, jake, jo, bob] u member: | ? - member( bob, [darcie, jo, jim, bob, alice]). The system responds with the answer Yes Organization of Programming Languages-Cheng (Fall 2004) 63
List Structures u Writing your own append function: | ? - myappend([], [banana, eggs, milk], List). List = [banana, eggs, milk] | ? - myappend([], List, [banana, eggs, milk]). List = [banana, eggs, milk] | ? - myappend(List 1, List 2, [banana, eggs, milk]). List 1 = [ ] List 2 = [banana, eggs, milk] ? ; List 1 = [banana] List 2 = [eggs, milk] ? ; List 1 = [banana, eggs] List 2 = [milk] ? ; List 1 = [banana, eggs, milk] List 2 = [ ] ? ; Organization of Programming Languages-Cheng (Fall 2004) 64
List Structures u Writing your own append function: myappend([ ], List). myappend([Head 1|Tail 1], List 2, [Head 1|List 3] ) : - myappend(Tail 1, List 2, List 3). l l The first proposition specifies when the empty list is appended to any other list, that other list is the result The second proposition specifies the characteristics of the new list u Appending the list [Head 1|Tail 1] to List 2 produces the list [Head 1|List 3] only if List 3 is obtained by appending Tail 1 and List 2 Organization of Programming Languages-Cheng (Fall 2004) 65
List Structures u Write your own reverse function myreverse([], []). myreverse([Head|Tail], List) : myreverse(Tail, Result), append(Result, [Head], List). Organization of Programming Languages-Cheng (Fall 2004) 66
List Structures u Write your own member function: mymember(Element, [Element|_]). mymember(Element, [_|List]) : member(Element, List). Organization of Programming Languages-Cheng (Fall 2004) 67
Size | ? - size([a, b, c], N). N = 3 ? yes u Note: There is a predefined function called length which is the same as size([ ], 0). size([H | T], N) : size(T, N 1), N is N 1+1. Organization of Programming Languages-Cheng (Fall 2004) 68
Towers of Hanoi left middle right u The object is to move the disks, one at a time, from the left peg to the right peg. u You are allowed to use the middle peg. u At no stage are you allowed to place a bigger disk on top of a smaller one. Organization of Programming Languages-Cheng (Fall 2004) 69
Towers of Hanoi left l middle right Move top disk from left to right Organization of Programming Languages-Cheng (Fall 2004) 70
Towers of Hanoi left l l middle right Move top disk from left to middle Organization of Programming Languages-Cheng (Fall 2004) 71
Towers of Hanoi left l l l middle right Move top disk from left to middle Move top disk from right to middle Organization of Programming Languages-Cheng (Fall 2004) 72
Towers of Hanoi left l l middle right Move top disk from left to middle Move top disk from right to middle Move top disk from left to right Organization of Programming Languages-Cheng (Fall 2004) 73
Towers of Hanoi left l l l middle right Move top disk from left to middle Move top disk from right to middle Move top disk from left to right Move top disk from middle to left Organization of Programming Languages-Cheng (Fall 2004) 74
Towers of Hanoi left middle Move top disk from left to right l Move top disk from left to middle l Move top disk from right to middle l Move top disk from left to right l Move top disk from middle to left l Move top disk from middle to right Organization of Programming Languages-Cheng (Fall 2004) right l 75
Towers of Hanoi left l l l l middle right Move top disk from left to middle Move top disk from right to middle Move top disk from left to right Move top disk from middle to left Move top disk from middle to right Move top disk from left to right Organization of Programming Languages-Cheng (Fall 2004) 76
Recursive Solution u Suppose we have N disk on the source pole. u The idea is that if we can move the top N-1 disks onto the middle pole, then we can simply move the largest disk at the bottom onto the destination pole. u By applying the same technique that we use to move the top N-1 disks, we can move the N-1 disks onto the dest pole. Organization of Programming Languages-Cheng (Fall 2004) 77
Recursive Solution Original Step 1 Step 2 Step 3 Organization of Programming Languages-Cheng (Fall 2004) 78
Solution move(1, X, Y, Z) : write(’ Move top disk from ’), write(X), write(’ to ’), write(Y), nl. move(N, X, Y, Z) : N > 1, M is N-1, move(M, X, Z, Y), move(1, X, Y, Z), move(M, Z, Y, X). | ? - move(3, left, right, middle). Organization of Programming Languages-Cheng (Fall 2004) 79
Solution | ? - move(3, left, right, middle). Move top disk from left to right Move top disk from left to middle Move top disk from right to middle Move top disk from left to right Move top disk from middle to left Move top disk from middle to right Move top disk from left to right true ? Organization of Programming Languages-Cheng (Fall 2004) 80
Quick Sort (Exercise) p Partition <p p >= p Sort Organization of Programming Languages-Cheng (Fall 2004) Sort 81
Resolution Order Control u Prolog always matches in the same order: l starting at the beginning and at the left end of a given goal u User can affect efficiency of resolution by ordering the propositions to optimize a particular application l If certain rules are more likely to succeed than others during an execution, placing those rules first makes the program more efficient Organization of Programming Languages-Cheng (Fall 2004) 82
Control of Backtracking u The cut operator (!) is used to control backtracking u The (!) is actually a goal which always succeeds immediately, but it cannot be re-satisfied through backtracking u For example, the goal l A, B, !, C, D. l would follow a left to right unification process up to C. If A and B succeed but C fails, we know it is a waste of time to backtrack to resatisfy A or B, so the whole goal fails if we use ! in the place immediately before C Organization of Programming Languages-Cheng (Fall 2004) 83
Problems with Control u The ability to tamper with control flow in a Prolog program is a deficiency because it is detrimental to one of the advantages of logic programming: programs do not specify how to find solutions u Using the ability for flow control, clutters the simplicity of logic programs with details of order control to produce solutions u Frequently used for the sake of efficiency Organization of Programming Languages-Cheng (Fall 2004) 84
Negation u Consider the example parent(bill, jake). parent(bill, shelley). sibling(X, Y) : - parent(M, X), parent(M, Y). ? -sibling(X, Y). Prolog’s result is X = jake Y = jake Organization of Programming Languages-Cheng (Fall 2004) 85
Negation u Consider the example parent(bill, jake). parent(bill, shelley). sibling(X, Y) : - parent(M, X), parent(M, Y), X =Y. ? -sibling(X, Y). Prolog’s result is X = jake Y = shelley Organization of Programming Languages-Cheng (Fall 2004) 86
Negation not a Logical Not u Negation means resolution cannot satisfy the subgoal u Logical Not cannot be a part of Prolog primarily because of the form of the Horn clause B : - A 1 A 2 . . . Am If all the A propositions are true, it can be concluded that B is true. But regardless of the truth or falseness of any or all of the As, it cannot be concluded that B is false. Prolog can prove that a given goal is true, but it cannot prove that a given goal is false. Organization of Programming Languages-Cheng (Fall 2004) 87
Expert Systems u Expert Systems are designed to emulate human expertise. They consist of a database of facts, an inferencing process, some heuristics about the domain, and some friendly human interface u Prolog provides the facilities of using resolution for query processing, adding facts and rules to provide the learning capability, and using trace to inform the user of the reasoning behind a given result Organization of Programming Languages-Cheng (Fall 2004) 88
CSE 452: Programming Languages Logical Programming Languages Part 3 Organization of Programming Languages-Cheng (Fall 2004) 89
Prolog Example u Delete an element from a list l delete. Elem /3 ( /3 means there are 3 arguments) l Example: u delete. Elem(4, l X = [2, 3, 5]. u delete. Elem(6, l [2, 3, 4, 5], X) X = [2, 3, 4, 5]. Organization of Programming Languages-Cheng (Fall 2004) 90
Delete an Element from a List u Functor: delete. Elem u Arguments l Input: u An element u List of elements l Output: u Result list Organization of Programming Languages-Cheng (Fall 2004) 91
Delete an Element from a List u Base step: l delete. Elem(_, []). %% underscore means any symbol l delete. Elem(P, [P|Tail], Tail). u Recursive step: l delete. Elem(P, [H|Tail], [H|Res]) : - P = H, delete. Elem(P, Tail, Res). Organization of Programming Languages-Cheng (Fall 2004) 92
Combining Lists u Write a predicate combine/3 that takes three lists as arguments and combines the elements of the first two lists into the third as follows: ? - combine([a, b, c], [1, 2, 3], X). X = [a, 1, b, 2, c, 3] ? - combine([foo, bar, yip, yup], [glub, glab, glib, glob], Result). Result = [foo, glub, bar, glab, yip, glib, yup, glob] Organization of Programming Languages-Cheng (Fall 2004) 93
Combining Lists combine([], List). combine(List, [], List). combine([H|T], [H 2|T 2], [H, H 2|Res]) : combine(T, T 2, Res). Organization of Programming Languages-Cheng (Fall 2004) 94
Sublist u Sublist/2 is true if the first argument is a sublist of the second argument. For example: sublist([c, d, e], [a, b, c, d, e, f]) is true sublist([c, , e], [a, b, c, d, e, f]) is false sublist(S, L): append(L 1, L 2, L), append(S, L 3, L 2). Organization of Programming Languages-Cheng (Fall 2004) 95
Sublist u use it in different ways: sublist([c, d, e], [a, b, c, d, e, f]). sublist([c, , e], [a, b, c, d, e, f]). sublist(S, [a, b, c]). l uses backtracking to find all possible sublists. Organization of Programming Languages-Cheng (Fall 2004) 96
Quick Sort p Partition <p p >= p Sort Organization of Programming Languages-Cheng (Fall 2004) Sort 97
Quick Sort u u What are the functors? l quick. Sort l Partition How many arguments? l quick. Sort Input: Unsorted list u Output: Sorted list u l Partition u Input: l l u pivot List of numbers (besides the pivot) to be partitioned Output: l l Left list (list of numbers less than pivot) Right list (list of numbers greater than or equal to pivot) Organization of Programming Languages-Cheng (Fall 2004) 98
Quick Sort u Base step: l quick. Sort([], []). u Recursive step: l quick. Sort([P | T], Result) : partition(T, P, L, B), quick. Sort(L, Sort. Low), quick. Sort(B, Sort. Big), append(Sort. Low, [P | Sort. Big], Result). Organization of Programming Languages-Cheng (Fall 2004) 99
Partition u Base step: l partition([ ], P, [ ]). u Recursive step: l partition([H | T], P, [H | L], B) : - H < P, partition(T, P, L, B). l partition([H | T], P, L, [H | B]) : - H >= P, partition(T, P, L, B). Organization of Programming Languages-Cheng (Fall 2004) 10
Quick Sort (Summary) quick. Sort([ ], [ ]). quick. Sort([P | T], Y) : - partition(T, P, L, B), quick. Sort(L, Sort. Low), quick. Sort(B, Sort. Big), append(Sort. Low, [P | Sort. Big], Y). partition([ ], P, [ ]). partition([H | T], P, [H | L], B) : - H < P, partition(T, P, L, B). partition([H | T], P, L, [H | B]) : - H >= P, partition(T, P, L, B). Organization of Programming Languages-Cheng (Fall 2004) 10





































































































