Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 452: Programming Languages

Similar presentations


Presentation on theme: "CSE 452: Programming Languages"— Presentation transcript:

1 CSE 452: Programming Languages
Logical Programming Languages Part 1

2 Combine Three PPTs Programming Languages-Cheng (Fall 2004)

3 Outline Another programming paradigm: Logic Programming Prolog
We’ll be using GNU prolog (

4 ALGORITHM = LOGIC + CONTROL
Another Paradigm QUESTION: "What is a computer program?" ANSWER: "It is an executable representation of some algorithm designed to solve some real world problem." Kowalski (CACM, 1979): There are two key elements to a computer program Logic – what we want the program to achieve Control – how we are going to achieve it ALGORITHM = LOGIC + CONTROL Difference between imperative and declarative programming

5 Example: Computing Factorial
Imperative (Ada) 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; For imperative language programmer needs to concentrate on both the logic and control Declarative (PROLOG) implementation factorial(0,1):- !. factorial(N1,T2):- N2 is N1-1, factorial(N2,T1), T2 is N1*T1. For declarative language, we define the logic (the desired goal or result) but not the control (how we achieve the desired goal)

6 Declarative Languages
Declarative languages make extensive use of relationships between objects There are two principal styles of defining relationships: Functional Programming 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 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

7 What is logic? Encyclopedia Brittanica:
Logic is the study of propositions and their use in argumentation Encarta Encyclopedia: Logic is the science dealing with the principles of valid reasoning and argument Factasia Logic: Logic is the study of necessary truths and of systematic methods for expressing and demonstrating such truths

8 Logic Programming Logic programming
expresses programs in the form of symbolic logic uses a logical inferencing process for reasoning Logic programs are declarative rather than procedural 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 Prolog is the most widely used logic programming language

9 Terminology Proposition a logical statement that may be true or false
Symbolic logic is used for three purposes: express propositions express the relationships between propositions describe how new propositions may be inferred from others Two primary forms of symbolic logic Propositional calculus Predicate calculus Predicate calculus is the form of symbolic logic used for logic programming

10 Propositions Objects in logic programming propositions are Constants
symbols that represent an object Example: man, jake, like bob, and steak Variables symbols that can represent different objects at different times Atomic propositions are the simplest propositions and consist of compound terms

11 Atomic Propositions Compound term has two parts
functor: symbol that names the relation an ordered list of parameters Examples: man (jake) like (bob, steak) 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 father (john, jake) could mean several things Propositions are stated in two modes fact: one in which the proposition is defined to be true query: one in which the truth of the proposition is to be determined

12 Compound Propositions
Compound propositions have two or more atomic propositions connected by logical operators Name Symbol Example Meaning negation   a not a conjunction  a  b a and b disjunction  a  b a or b equivalence  a  b a is eqv to b implication  a  b a implies b  a  b b implies a (in prolog a  b is written as a :- b)

13 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

14 Compound Proposition Implication: p  q Meaning:
if p then q p implies q p is the premise or antecedent q is the conclusion or consequent Can write p  q in disjunctive normal form Øp OR q Truth table shows equivalence

15 p  q Equivalent to Øp OR q

16 Propositions with Quantifiers
Variables may appear in propositions - only when introduced by symbols called quantifiers Name Example Meaning universal X.P For all X, P is true existential X.P There exists a value of X such that P is true Note: the period separates the variable from the proposition

17 Propositions with Quantifiers
Examples of propositions with quantifiers 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 Note: quantifiers have a higher precedence than any of the logical operators

18 First Order Predicate Calculus
Provides a method of expressing collections of propositions 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 Predicate calculus: natural (0) natural (2) X.natural (X)  natural (successor (X)) natural (-1)

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

20 Clausal Form Redundancy is a problem with predicate calculus
there are many different ways of stating propositions that have the same meaning 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: B1  B2  ...  Bn  A1  A2  ...  Am Meaning: If all As are true, then at least one B is true

21 Clausal Form Characteristics Existential quantifiers are not required
Universal quantifiers are implicit in the use of variable in the atomic propositions Only the conjunction and disjunction operators are required Disjunction appears on the left side of the clausal form and conjunction on the right side The left side is called the consequent The right side is called the antecedent

22 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

23 Predicate Calculus - Proving Theorems
One of the most significant breakthroughs in automatic theorem-proving was the discovery of the resolution principle by Robinson in 1965 Resolution is an inference rule that allows inferred propositions to be computed from given propositions Resolution was devised to be applied to propositions in clausal form

24 Resolution The concept of resolution is the following:
Given two propositions: P1  P2 Q1  Q2 Suppose P1 is identical to Q2 and we rename them as T. Then T  P2 Q1  T Resolution: Since P2 implies T and T implies Q1, it is logically obvious that P2 implies Q1 Q1  P2

25 Resolution Example Consider the two propositions:
older (joanne, jake)  mother (joanne, jake) wiser (joanne, jake)  older (joanne, jake) Mechanics of Resolution Terms on the left hand side are ANDed together Terms on the right hand side are ANDed together older (joanne, jake)  wiser (joanne, jake)  mother (joanne, jake)  older (joanne, jake) Any term that appears on both sides of the new proposition is removed from both sides wiser (joanne, jake)  mother (joanne, jake)

26 Resolution Expanded Example
Given father(bob, jake)  mother(bob,jake)  parent (bob,jake) grandfather(bob,fred)  father(bob,jake)  father(jake,fred) 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)

27 Resolution for Variables
Presence of variables in propositions requires resolution to find values for those variables that allow the matching process to succeed Unification The process of determining useful values for variables in propositions to find values for variables that allow the resolution process to succeed. Instantiation The temporary assigning of values to variables to allow unification

28 Example Add facts -- what is known -- parent(sue,tom).
parent(bob,tom). parent(bob,kate). parent(tom,laura). parent(tom.mark). parent(mark,anne). Query: ?- parent(tom,X). X = laura ; X = mark ; sue bob tom kate laura mark anne

29 Resolution for Variables
Inconsistency detection An important property of resolution is its ability to detect any inconsistency in a given set of propositions This property allows resolution to be used to prove theorems Theorem proving Use negation of the theorem as a new proposition Theorem is negated so that resolution can be used to prove the theorem by finding an inconsistency This is the basis for proof by contradiction

30 Example Facts: A. B  A. Given the facts, prove that B is true
Query: Ø B (add new proposition) Resolution: A  B  A B Contradicts with Ø B So, conclude that Ø B is false Therefore, B is true

31 Horn Clauses Recall that a clausal form has the following form:
B1  B2  ...  Bn  A1  A2  ...  Am When propositions are used for resolution, only a restricted kind of clausal form can be used Horn clauses special kind of clausal form to simplify resolution two forms: single atomic proposition on the left side, or an empty left side left side of Horn clause is called the head Horn clauses with left sides are called headed Horn clauses

32 Horn Clauses Headed Horn clauses are used to state relationships:
likes(bob, trout)  likes (bob, fish)  fish(trout) Headless Horn clauses are used to state facts: father(bob,jake) Most propositions may be stated as Horn clauses

33 Semantics Semantics of logic programming languages are called declarative semantics meaning of propositions can be determined from the statements themselves Unlike imperative languages where semantics of a simple assignment statement requires examination of local declarations, knowledge of scoping rules of the language, and possibly, examination of programs in other files to determine the types of variables

34 Origins of Prolog Colmerauer and Roussle (University of Aix-Marseille) and Kowalski (University of Edinburgh) developed the fundamental design of Prolog Collaboration between both universities continued until mid-70s when independent efforts kicked off resulting in two syntactically different dialects of Prolog With Japan’s announcement of a project called Fifth Generation Computing Systems in 1981, came their choice of Prolog to develop intelligent machines This results in strong sudden interest in logic programming and AI in U.S. and Europe

35 Prolog - Basic Elements - Terms
A Prolog term is a constant, a variable, or a structure A constant is either an atom or an integer Atoms are the symbolic values of Prolog 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 Any string of letters, digits, and underscores that begins with an uppercase letter not bound to types by declarations binding of a value (and type) to a variable is called an instantiation Instantiations last only through completion of goal Structures represent the atomic proposition of predicate calculus form is functor (parameter list) Functor can be any atom and is used to identify the structure Parameter list can be any list of atoms, variables, or other structures

36 Prolog – Fact Statements
Fact statements are used to construct hypotheses from which new information may be inferred Fact statements are headless Horn clauses assumed to be true Examples: male(bill). female(mary). male(jake). father(bill, jake). mother(mary, jake)

37 Prolog - Rule Statements
Rule statements are headed Horn clauses for constructing the database The RHS is the antecedent(if), and the LHS is the consequent(then) Consequent is a single term because it is a Horn clause Conjunctions may contain multiple terms that are separated by logical ANDs or commas, e.g. female(shelley), child (shelley).

38 Prolog - Rule Statements
General form of the Prolog headed Horn clause consequence_1 :- antecedent_expression Example: ancestor(mary, shelley) :- mother(mary, shelley). 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). These statements give rules of implication among some variables, or universal objects (universal objects are X, Y, Z, M, and F)

39 Prolog - Goal Statements
Facts and Rules are used to prove or disprove a theorem that is in the form of a proposition (called goal or query) 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 Conjunctive propositions and propositions with variables are also legal goals. For example, father (X, mike). When variables are present, the system identifies the instantiations of the variables that make the goal true

40 Prolog - Basic Elements
Because goal and some nongoal statements have the same form (headless Horn clauses), it is imperative to distinguish between the two 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 Gnu Prolog uses ?- for goals

41 Horn Clauses in Prolog A :- B1, … , Bn. Body Head End of clause marker
“ if ” Rule The head and the body are nonempty. The body is the conditional part. The head is the conclusion. Fact The body is empty, and is written as: A.

42 Inferencing Process of Prolog
Goals (queries) may be compound propositions; each of facts (structures) is called a subgoal Father(X, Y), Likes(X, steak). 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 If Q is the goal, then either Q must be found as fact in the database, or the inferencing process must find a sequence of propositions that give that result

43 Inferencing Process of Prolog
Matching the process of proving(or satisfying) a subgoal by a proposition-matching process 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

44 Inferencing Process of Prolog
Consider the goal: man(X). Prolog must match the goal against the propositions in the database. 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 If there is no proposition with the form of the goal, the system indicates with a no that the goal can’t be satisfied

45 Inferencing Process of Prolog
Solution Search Approaches Depth-first finds a complete sequence of propositions-a proof-for the first subgoal before working on the others Breadth-first works on all subgoals of a given goal in parallel Backtracking 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

46 Inferencing Process – Backtracking
Suppose we have the following compound goal: male (X), parent (X, shelley) Is there an instantiation of X, such that X is a male and X is a parent of shelley? The search 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 Then it attempts to prove that parent(john, shelley) is true 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

47 CSE 452: Programming Languages
Logical Programming Languages Part 2

48 Prolog Statements Prolog statements consist of facts, rules, and queries. Example of facts (written as headless Horn clauses) male(tony). male(greg). female(nikki). female(karen). Example of rules (written as headed Horn clauses) sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \= Y. Facts and Rules are stored in a file with extension .pl

49 Loading the Knowledge Base
Suppose the facts and rules are stored in a file called c:\classes\prolog\gender.pl To load the file: | ?- ['C:/classes/prolog/gender']. or | ?- consult('C:/classes/prolog/gender').

50 Prolog Statements Goal/Query statements
Also in the form of headless Horn clauses | ?- male(tony). yes | ?- female(X). X = nikki ? ; X = karen

51 Query/Goal Statement A query can just be an assertion of a fact
Prolog will try to establish whether that fact can be shown to be true 1 Alternatively, a query can contain variables Prolog will try to find values for the variables that make the query true Variables are written with initial uppercase letters. Prolog will print the variable values one by one. After each one, type “;” to see the next value (solution), “RETURN” to accept the last value (solution), or “a” to print all values

52 Inference Process Given a goal/query, how does Prolog match the goal against the propositions in the database? In general, there are two approaches: Forward chaining (bottom-up resolution) System begin with the facts and rules of the database and attempt to find a sequence of matches that lead to the goal Backward chaining (top-down resolution) 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

53 Inference Process (Example)
Given the following facts and rules: father(bob). man(X) :- father(X). Given the following goal/query: man(bob). Forward chaining: Start with the first proposition: father(bob). Goal is inferred by matching father(bob) to right side of the second rule This leads to the goal man(bob).

54 Inference Process (Example)
Given the following facts and rules: father(bob). man(X) :- father(X). Given the following goal/query: man(bob). Backward chaining: Start with the goal: man(bob). Match the goal to the left-hand side of second proposition This would instantiate X to bob Match the right side of the second proposition (father(bob)) to the first proposition

55 Inferencing Process of Prolog
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). Solution Search Approaches Depth-first finds a complete sequence of propositions-a proof-for the first subgoal before working on the others Breadth-first works on all subgoals of a given goal in parallel Backtracking 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

56 Simple Arithmetic Prolog supports integer variables and integer arithmetic + (7, 5). produces an answer equals to 12 A is 5. How about this statement: Sum is Sum + Number Since Sum is not instantiated, the reference to it on the RHS is undefined and the clause fails

57 Simple Arithmetic Continued
Given the following facts: speed( ford, 100). speed(chevy, 105). speed(dodge, 95). time(ford, 20). time(chevy, 21). time(dodge, 24). 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

58 Tracing the Process 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 trace is used to understand and debug Prolog pgms Tracing model describes Prolog execution in terms of 4 events Call, which occurs at beginning of an attempt to satisfy a goal Exit, which occurs when a goal has been satisfied Redo, which occurs when backtrack causes an attempt to resatisfy a goal Fail, which occurs when a goal fails In Gnu prolog: trace % This will switch on the trace mode Notrace % This will switch off the trace mode

59 Tracing the Process 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). % This is 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

60 List Structures Prolog uses the syntax of ML and Haskell to specify lists List elements are separated by commas, and the entire list is delimited by square brackets Example: [apple, prune, grape, kumquat] Example: [ ] means empty list Like Haskell, Prolog uses the special notation [ X | Y ] to indicate head X and tail Y head and tail correspond CAR and CDR in LISP

61 List Structures Example: Consider the following facts and rules:
newlist([apple,apricot,pear,banana]). first(X) :- newlist([X|Y]). In query mode, first(X). statement instantiates X with apple

62 List Structures Other Examples: newlist([X|Y]
This will instantiate X to apple and Y to [apricot,pear,banana] newlist([apple,appricot|X]). This will instantiate X to [pear,banana]

63 List Structures Append: | ?- append(([bob, jo], [jake, darcie], X).
produces the output X = [bob, jo, jake, darcie] Reverse: | ?- reverse([bob, jo, jake, darcie], X). produces the output X = [darcie, jake, jo, bob] member: | ?- member( bob, [darcie, jo, jim, bob, alice]). The system responds with the answer Yes

64 List Structures Writing your own append function:
| ?- myappend([],[banana,eggs,milk],List). List = [banana,eggs,milk] | ?- myappend([],List,[banana,eggs,milk]). | ?- myappend(List1,List2,[banana,eggs,milk]). List1 = [ ] List2 = [banana,eggs,milk] ? ; List1 = [banana] List2 = [eggs,milk] ? ; List1 = [banana,eggs] List2 = [milk] ? ; List1 = [banana,eggs,milk] List2 = [ ] ? ;

65 List Structures Writing your own append function:
myappend([ ],List,List). myappend([Head1|Tail1],List2,[Head1|List3]) :- myappend(Tail1,List2,List3). 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 Appending the list [Head1|Tail1] to List2 produces the list [Head1|List3] only if List3 is obtained by appending Tail1 and List2

66 List Structures Write your own reverse function myreverse([],[]).
myreverse([Head|Tail],List) :- myreverse(Tail,Result), append(Result,[Head],List).

67 List Structures Write your own member function:
mymember(Element,[Element|_]). mymember(Element,[_|List]) :- member(Element,List).

68 Size | ?- size([a,b,c], N). N = 3 ? yes
Note: There is a predefined function called length which is the same as size size([ ], 0). size([H | T], N) :- size(T, N1), N is N1+1.

69 Towers of Hanoi middle right left The object is to move the disks, one at a time, from the left peg to the right peg. You are allowed to use the middle peg. At no stage are you allowed to place a bigger disk on top of a smaller one.

70 Towers of Hanoi middle right left Move top disk from left to right

71 Towers of Hanoi middle right left Move top disk from left to right
Move top disk from left to middle

72 Towers of Hanoi middle right left Move top disk from left to right
Move top disk from left to middle Move top disk from right to middle

73 Towers of Hanoi middle right left Move top disk from left to right
Move top disk from left to middle Move top disk from right to middle

74 Towers of Hanoi middle right left 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 middle to left

75 Towers of Hanoi middle right left 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 middle to left Move top disk from middle to right

76 Towers of Hanoi middle right left 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 middle to left Move top disk from middle to right

77 Recursive Solution Suppose we have N disk on the source pole.
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. 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.

78 Recursive Solution Step 1 Original Step 2 Step 3

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

80 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 middle to left Move top disk from middle to right true ?

81 Quick Sort (Exercise) p Partition < p p >= p Sort Sort

82 Resolution Order Control
Prolog always matches in the same order: starting at the beginning and at the left end of a given goal User can affect efficiency of resolution by ordering the propositions to optimize a particular application If certain rules are more likely to succeed than others during an execution, placing those rules first makes the program more efficient

83 Control of Backtracking
The cut operator (!) is used to control backtracking The (!) is actually a goal which always succeeds immediately, but it cannot be re-satisfied through backtracking For example, the goal A, B, !, C, D. 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

84 Problems with Control 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 Using the ability for flow control, clutters the simplicity of logic programs with details of order control to produce solutions Frequently used for the sake of efficiency

85 Negation 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

86 Negation 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

87 Negation not a Logical Not
Negation means resolution cannot satisfy the subgoal Logical Not cannot be a part of Prolog primarily because of the form of the Horn clause B :- A1  A2  ...  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.

88 Expert Systems 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 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

89 CSE 452: Programming Languages
Logical Programming Languages Part 3

90 Prolog Example Delete an element from a list
deleteElem /3 ( /3 means there are 3 arguments) Example: deleteElem(4, [2,3,4,5], X) X = [2,3,5]. deleteElem(6, [2,3,4,5],X) X = [2,3,4,5].

91 Delete an Element from a List
Functor: deleteElem Arguments Input: An element List of elements Output: Result list

92 Delete an Element from a List
Base step: deleteElem(_, [], []) %% underscore means any symbol deleteElem(P,[P|Tail],Tail). Recursive step: deleteElem(P,[H|Tail],[H|Res]) :- P \= H, deleteElem(P,Tail,Res).

93 Combining Lists 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]

94 Combining Lists combine([],List,List). combine(List,[],List).
combine([H|T],[H2|T2],[H,H2|Res]) :- combine(T,T2,Res).

95 Sublist 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(L1,L2,L), append(S,L3,L2). sublist.pro

96 Sublist 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]). uses backtracking to find all possible sublists.

97 Quick Sort p Partition < p p >= p Sort Sort

98 Quick Sort What are the functors? quickSort Partition
How many arguments? Input: Unsorted list Output: Sorted list Input: pivot List of numbers (besides the pivot) to be partitioned Output: Left list (list of numbers less than pivot) Right list (list of numbers greater than or equal to pivot)

99 Quick Sort Base step: quickSort([], []). Recursive step:
quickSort([P | T], Result) :- partition(T, P, L, B), quickSort(L, SortLow), quickSort(B, SortBig), append(SortLow, [P | SortBig], Result).

100 Partition Base step: partition([ ], P, [ ], [ ]). Recursive step:
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).

101 Quick Sort (Summary) quickSort([ ], [ ]).
quickSort([P | T], Y) :- partition(T, P, L, B), quickSort(L, SortLow), quickSort(B, SortBig), append(SortLow, [P | SortBig], 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).


Download ppt "CSE 452: Programming Languages"

Similar presentations


Ads by Google