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

Slides:



Advertisements
Similar presentations
Artificial Intelligence: Natural Language and Prolog
Advertisements

CS4026 Formal Models of Computation Part II The Logic Model Lecture 1 – Programming in Logic.
First Order Logic Logic is a mathematical attempt to formalize the way we think. First-order predicate calculus was created in an attempt to mechanize.
Chapter 11 :: Logic Languages
Computational Models The exam. Models of computation. –The Turing machine. –The Von Neumann machine. –The calculus. –The predicate calculus. Turing.
Prolog for Dummies Ulf Nilsson Dept of Computer and Information Science Linköping University.
1. An Overview of Prolog.
Prolog The language of logic. History Kowalski: late 60’s Logician who showed logical proof can support computation. Colmerauer: early 70’s Developed.
Declarative Programming Lists in PROLOG Autumn 2014.
Introduction to PROLOG ME 409 Lab - 1. Introduction to PROLOG.
11/10/04 AIPP Lecture 6: Built-in Predicates1 Combining Lists & Built-in Predicates Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture.
Prolog The language of logic. History Kowalski: late 60’s Logician who showed logical proof can support computation. Colmerauer: early 70’s Developed.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
1 Logic Programming. 2 A little bit of Prolog Objects and relations between objects Facts and rules. Upper case are variables. parent(pam, bob).parent(tom,bob).
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
About prolog  History  Symbolic Programming Language  Logic Programming Language  Declarative Programming Language.
CS 330 Programming Languages 12 / 02 / 2008 Instructor: Michael Eckmann.
Chapter 12 - Logic Programming
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Constraint Logic Programming Ryan Kinworthy. Overview Introduction Logic Programming LP as a constraint programming language Constraint Logic Programming.
© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 9: A closer look at terms Theory –Introduce the == predicate –Take a closer look at term structure.
CSE (c) S. Tanimoto, 2005 Logic Programming 1 Logic Programming Outline: Motivation Examples: The Grandmother relation Formulation in Prolog Logic,
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 15 Logic Programming Q: How many legs does.
Prolog Programming Lecture Module 13. Objective ● What is Prolog? ● Prolog program ● Syntax of Prolog ● Prolog Control Strategy ● Execution of Prolog.
DEDUCTIVE DATABASE.
CS 403: Programming Languages Lecture 17 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Formal Models of Computation Part II The Logic Model
CS 321 Programming Languages and Compilers Prolog part 2.
CS 403: Programming Languages Lecture 19 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
1 Lecture 6 Logic Programming introduction to Prolog, facts, rules Ras Bodik Shaon Barman Thibaud Hottelier Hack Your Language! CS164: Introduction to.
30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists1 Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim.
Prolog Programming. 2 DATA STRUCTURES IN PROLOG PROGRAMMING TECHNIQUES CONTROL IN PROLOG CUTS.
Introduction To PROLOG World view of imperative languages. World view of relational languages. A PROLOG program. Running a PROLOG program. A PROLOG.
Chapter 9: Functional Programming in a Typed Language.
1 Prolog and Logic Languages Aaron Bloomfield CS 415 Fall 2005.
Programming Languages Tucker and Noonan – 2e Chapter 15 – Part 1 Logic Programming “Q: How many legs does a dog have if you call its tail a leg? A: Four.
CS4026 Formal Models of Computation Part II The Logic Model Lecture 2 – Prolog: History and Introduction.
CS 603: Programming Languages Lecture 25 Spring 2004 Department of Computer Science University of Alabama Joel Jones.
Logic Programming Languages Session 13 Course : T Programming Language Concept Year : February 2011.
Logic Programming and Prolog Goal: use formalism of first-order logic Output described by logical formula (theorem) Input described by set of formulae.
Ch. 13 Ch. 131 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (notes?) Dr. Carter Tiernan.
Introduction to Prolog. Outline What is Prolog? Prolog basics Prolog Demo Syntax: –Atoms and Variables –Complex Terms –Facts & Queries –Rules Examples.
© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 9: A closer look at terms Theory –Introduce the == predicate –Take a closer look at term structure.
CS 337 Programming Languages Logic Programming I (Logic, Intro to Prolog)
© Kenneth C. Louden, Chapter 12 - Logic Programming Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
Programming Languages Third Edition Chapter 4 Logic Programming.
CS 403: Programming Languages Lecture 18 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Programming Language Concepts Lecture 17 Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Logic Programming.
ISBN Chapter 16 Logic Programming Languages.
ICOM 4036: PROGRAMMING LANGUAGES Lecture 5 Logic Programming 1/23/2016.
Artificial Intelligence CS370D
In The Name Of Allah Lab 03 1Tahani Aldweesh. objectives Searching for the solution’s. Declaration. Query. Comments. Prolog Concepts. Unification. Disjunction.
For Friday No reading Prolog Handout 2. Homework.
Prolog 3 Tests and Backtracking 1. Arithmetic Operators Operators for arithmetic and value comparisons are built-in to Prolog = always accessible / don’t.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
Introduction to Prolog Asst. Prof. Dr. Senem Kumova Metin Revised lecture notes of “Concepts of Programmig Languages, Robert W. Sebesta, Ch. 16”
Prolog Fundamentals. 2 Review Last Lecture A Prolog program consists of a database of facts and rules, and queries (questions). –Fact:.... –Rule:... :-....
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Section 16.5, 16.6 plus other references
Prolog Programming.
Prolog a declarative language
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
Prolog fundamentals Module 14.2 COP4020 – Programming Language Concepts Dr. Manuel E. Bermudez.
Prolog a declarative language
Prolog a declarative language
Prolog a declarative language
Chapter 12 :: Logic Languages
Programming Techniques
Programming Languages 2nd edition Tucker and Noonan
Presentation transcript:

1 CS Programming Languages Class 19 November 2, 2000

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

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

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

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

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

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

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

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.

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.

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

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

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

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

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 ) [ ]

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

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

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

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

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

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

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

CS 403, Class 19 Slide # 23 Solution

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.

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

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

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

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

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

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

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.

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

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

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

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

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

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

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

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.

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

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

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

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

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

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.

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

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

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 …

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.

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