Lecture 11: Feb. 10, 2016

Similar documents
Operators (2A) Young Won Lim 10/5/13

Operators (2A) Young Won Lim 10/2/13

Derived from PROgramming in LOGic (1972) Prolog and LISP - two most popular AI languages. Prolog programs based on predicate logic using Horn clauses

Part I Logic programming paradigm

Topic B: Backtracking and Lists

Lecture 4: January 12, 2015

Chapter 16. Logic Programming. Topics. Unification. Resolution. Prolog s Search Strategy. Prolog s Search Strategy

Recursion, Structures, and Lists

Logic Programming. Efficiency Issues. Temur Kutsia

Tests, Backtracking, and Recursion

Prolog (cont d) Remark. Using multiple clauses. Intelligent Systems and HCI D7023E

This lecture covers: Prolog s execution strategy explained more precisely. Revision of the elementary Prolog data types

Solutions to the Second Midterm Exam

QUTE: A PROLOG/LISP TYPE LANGUAGE FOR LOGIC PROGRAMMING

Arithmetic Terms are Symbolic

Lecture Overview Prolog 1. Introduction Interaction Terms 2. Clauses and predicates Clauses Predicates Variables 3.

Reading 8 : Recursion

CMSC 330: Organization of Programming Languages

Prolog Programming. Lecture Module 8

Operational Semantics

Implementação de Linguagens 2016/2017

INTRODUCTION TO PROLOG

Prolog Introduction. Gunnar Gotshalks PI-1

Programming Paradigms

Lecture 9: A closer look at terms

Prolog. Intro to Logic Programming

CS 360: Programming Languages Lecture 10: Logic Programming with Prolog

CSE 452: Programming Languages. Prolog Statements. Loading the Knowledge Base. Logical Programming Languages Part 2

Introduction to Programming in C Department of Computer Science and Engineering\ Lecture No. #02 Introduction: GCD

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or

CSEN403 Concepts of Programming Languages. Topics: Logic Programming Paradigm: PROLOG Search Tree Recursion Arithmetic

PROgramming in LOGic PROLOG Recursion, Lists & Predicates

Fundamentals of Prolog

PROLOG. First simple Prolog Program. Basic elements of Prolog. Clause. NSSICT/CH/Nov., 2012.

The Idea Underlying Logic Programming. CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Logic Programming

CAP 5602 Summer, Lesson 4: Loops. The topics 1. the cut and some of its uses 2. the while loop 3. the do until loop

Lecture 9. Exercises. Theory. Solutions to exercises LPN 8.1 & 8.2. Patrick Blackburn, Johan Bos & Kristina Striegnitz

COP4020 Programming Languages. Logical programming with Prolog Prof. Xin Yuan

The object level in Prolog. Meta-level predicates and operators. Contents. The flow of computation. The meta level in Prolog

Recursive definition of sets and structural induction

Logic Languages. Hwansoo Han

Lecture Notes An Introduction to Prolog Programming

Logic Programming Languages

3 Lists. List Operations (I)

The current topic: Prolog. Announcements. Meaning of a Prolog rule. Prolog syntax. Reminder: The deadline for Lab 2 re-mark requests is Friday.

simplicity hides complexity flow of control, negation, cut, 2 nd order programming, tail recursion procedural and declarative semantics and & or

Problem Solving and Search

CS200: Recursion and induction (recap from cs161)

S E C T I O N O V E R V I E W

First-Order Logic (FOL)

And Parallelism. Parallelism in Prolog. OR Parallelism

More Planning and Prolog Operators

ELEMENTARY NUMBER THEORY AND METHODS OF PROOF

Introduction to predicate calculus

Using Prolog as a CAS

An Annotated Language

Programming Paradigms

Infinite Derivations as Failures

More Non-logical Features of Prolog

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion

Names and Functions. Chapter 2

Building a system for symbolic differentiation

Linked Lists, Stacks, and Queues

Lecture 7: January 15, 2014

Research Report AI A Numerical Equation Solver in Prolog Michael A. Covington Artificial Intelligence Programs The University of Georgia

Backtrack control. Chapter 5

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

Chapter 16. Logic Programming Languages ISBN

815338A Principles of Programming Languages. Exercise 7 answers

Lecture 6: Faces, Facets

DEEPIKA KAMBOJ UNIT 2. What is Stack?

Logic Programming. Let us have airline flight information of the form: 1. Application Domains: 2. Definitions

Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1

P Is Not Equal to NP. ScholarlyCommons. University of Pennsylvania. Jon Freeman University of Pennsylvania. October 1989

Building a system for symbolic differentiation

Prolog Cut: Summary. CSC324 Logic & Relational Programming Illustrated in Prolog. Prolog Cut: Summary. Non-deterministic Programming

Prolog Assessed Exercise

1.3. Conditional expressions To express case distinctions like

Lecture 4: Backtracking and Cut 1. Lecture 4: Backtracking and Cut. Ahmed Sallam

Math 302 Introduction to Proofs via Number Theory. Robert Jewett (with small modifications by B. Ćurgus)

Chapter 16. Logic Programming Languages

Recursion Chapter 3.5

Lecture 14: March 9, 2015

IS BINARY ENCODING APPROPRIATE FOR THE PROBLEM-LANGUAGE RELATIONSHIP?

COMP2411 Lecture 20: Logic Programming Examples. (This material not in the book)

Euclid's Algorithm. MA/CSSE 473 Day 06. Student Questions Odd Pie Fight Euclid's algorithm (if there is time) extended Euclid's algorithm

1 Elementary number theory

Complexity, Induction, and Recurrence Relations. CSE 373 Help Session 4/7/2016

Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions

Incompatibility Dimensions and Integration of Atomic Commit Protocols

Lectures 20, 21: Axiomatic Semantics

Notes for Chapter 12 Logic Programming. The AI War Basic Concepts of Logic Programming Prolog Review questions

6.001 Notes: Section 6.1

IN112 Mathematical Logic

CAP 5602 Summer, Lesson 5: Lists. The topics 1. updating a counter 2. the list structure 3. some useful built-in predicates for lists


Lecture 9: Datalog with Negation

IN112 Mathematical Logic

Program Calculus Calculational Programming

6.001 Notes: Section 4.1

Transcription:

CS323: AI (Hands on with Prolog) Spring 2016 Lecturer: K.R. Chowdhary Lecture 11: Feb. 10, 2016 : Professor of CS (VF) Disclaimer: These notes have not been subjected to the usual scrutiny reserved for formal publications. They may be distributed outside this class only with the permission of the Instructor. 11.1 Some Built-in Predicates The built-ins can be used in a similar way as user-defined predicates. The important difference between the two is that a built-in predicate is not allowed to appear as the principal function in a fact or in the head of a rule. This must be so, because using them in such a position would effectively mean changing their definition. Equality. We write X = Y. Such a goal succeeds, if the terms X and Y can be matched. Output. Besides Prolog s replies to queries, if you wish your program to have further output, you can use the write predicate. The argument can be any valid Prolog term. In the case of a variable argument, its value will be printed. Execution of the predicate causes the system to skip a line, as in the following cases.?- write(hello World!), nl. Hello World!?- X = elephant, write(x), nl. elephant X = elephant read(n). write( the number is ), write(n), nl. the number is 5 N = 5 Matchings. Following are the examples for matchings. If two expressions matches, the output is otherwise it is No. The query, to prolog shows that the two expressions cannot be matched.?- p(x, 2, 2) = p(1, Y, X). No Sometimes there is more than one way of satisfying the current goal. Prolog chooses the first possibility (as determined by the order of clauses in a program), but the fact that there exists alternatives, is recorded. If at some point, Prolog fails to prove a certain subgoal, the system can go back and try an alternative 11-1

11-2 Lecture 11: Feb. 10, 2016 left behind in the of executing of the goal. This process is known as backtracking. The following example demonstrates backtracking. 11.2 Recursive Programming Using recursive programs, we can provide recursive definition of functions. We know that the factorial n! of a natural number n is defined as the product of all natural numbers from 1 to n. Here s a more formal, recursive definition (also known as an inductive definition), and the code in prolog. Example 11.1 Factorial Program. Recall the definition of factorial in equations (??) and (??) in section (??). 0! = 1, (base case) n! = (n1)! n, for n 1 (Recursion rule) %finding factorial. fact(0, 1). % base case fact(n, R) :- N >= 1, % recursion step N1 is N - 1, fact(n1, R1), R is R1 * N. For a recursive program to test the membership of an element in a set, if the element is not as head of the list, then it is in the tail. The process is recursively called. The membership algorithm is built-in feature of prolog, as well as it can be user-defined. A recursive algorithm for GCD (greatest common divisor) based on Euclid s Algorithm can be constructed as follows. Example 11.2 Program for Greatest Common Divisor (GCD). %gcd gcd(x, X, X). gcd(x, Y, Z) :- X > Y, D is X - Y, gcd(d, Y, Z). gcd(x, Y, Z) :- X < Y, D is Y - X, gcd(x, D, Z). Example 11.3 Towers of Hanoi Problem. Given three stacks A (source), B (destination), and I (intermediate), the towers of Hanoi problem is to move N number of disks from stack A to B using I as temporary stack. The disks are originally on stack A such

Lecture 11: Feb. 10, 2016 11-3 A I B Figure 11.1: Towers of Hanoi Problem. that larger diameter disks are below the smaller diameter disks, and no two disks have equal diameters. The movement is to be done following the rules of this game, which states that only one disk is to be moved at a time, and at no time the bigger diameter disk shall come over a smaller diameter disk (figure 11.1). move(a,b):- nl, write( move top from ), write(a), write( to ), write(b). transfer(1,a,b,i) :- move(a,b). transfer(n, A, B, I):- N > 1, M is N -1, transfer(m, A, I, B), move(a, B), transfer(m, I, B, A). The algorithm uses the strategy: move n 1 disks from A to I, then move a single disk from A to B, finally move n 1 disks from I to B. For n 1, it recursively calls the algorithm. The predicate nl stands for new-line. 11.3 List Manipulation Prolog represents the lists contained in square brackets with the elements being separated by commas. Here is an example: [elephant, horse, donkey, dog] Elements of lists could be any valid Prolog terms, i.e. atoms, numbers, variables, or compound terms. A term may also be other list. The empty list is denoted by []. The following is another example for a (slightly more complex) list: [elephant, [], X, parent(x, tom), [a, b, c], f(22)] Internally, lists are represented as compound terms using the function. (dot). The empty list [] is an atom and elements are added one by one. The list [a,b,c], for example, corresponds to the following term:.(a,.(b,.(c, [])))

11-4 Lecture 11: Feb. 10, 2016 We discussed in section (??) about lists. A list is a recursive definition, consisting of a head and a tail. The tail also comprises of head and rest of the elements as tail, and so on, until the tail is empty list. Example 11.4 Membership Program. % membership built-in?-member(2, [a, b, c, 2, 4, 900]).. % membership program ismember(x, [X R]). % matches with 1st element ismember(x, [Y R]) :- ismember(x, R). % try for next % element The built-in program append, appends two lists.?append([1, 2, 3], [a, b, c], X). % This is buit-in X=[1, 2, 3, a, b, c] Example 11.5 Appending of lists. append([],l,l). append([x L1], L2,[X L3]): append(l1, L2, L3). For a query, we write,? append([1, 2], [3, 4], Z) Z = [1, 2, 3, 4]?- 11.4 Arithmetic Expressions Prolog is not designed to handle arithmetics efficiently. Hence, it handles expressions and assignment operations in some different way.?3 + 5 = 8. No?X is 3 + 5. X = 8 The terms 3+5 and 8 do not match as the former is a compound term, whereas the latter is a number. The following are arithmetical relational predicates:

Lecture 11: Feb. 10, 2016 11-5 X > Y X < Y X >= Y X =< Y X \= Y X = Y The last two predicates express inequality and equality, respectively. 11.5 Backtracking, Cuts and Negation PROLOG offers the programmer a number of predicates for explicitly controlling the back-tracking behaviour of the interpreter. Note that here PROLOG deviates from the logic programming idea. The predicate True takes no arguments, and it always succeeds. 11.5.1 Fail The predicate Fail also has no arguments, the condition fail never succeeds. The general application of the predicate fail is to enforce backtracking, as shown in the following clause: a(x) : - b(x),fail. When the query a(x) is entered, the PROLOG interpreter first tries to find a match for b(x). Let us suppose that such a match is found, and that the variable X is instantiated to some term. Then, in the next step f ail, as a consequence of its failure, enforces the interpreter to look for an alternative instantiation to X. If it succeeds in finding another instantiation for X, then again fail will be executed. This entire process is repeated until no further instantiations can be found. This way all possible instantiations for X will be found. Note that if no side-effects are employed to record the instantiations of X in some way, the successive instantiations leave no trace. It will be evident that in the end the query a(x) will be answered by no. But, we have been successful in backtracking, i.e., going back and trying all possible instantiations for X, which helps in searching all the values. The negation in prolog is taken as failure as shown in the following program. Example 11.6 Negation as failure. bachelor(p) :- male(p), not(married(p)). male(rajan). male(rajam). married(dicken). When run, the queries responded as obvious. In the third case, married(who) succeeds, so the negation of goal fails.?bachelor(rajan). yes

11-6 Lecture 11: Feb. 10, 2016?bachelor(dicken). no bachelor(who). Who = dicken no 11.5.2 Cut Some times it is desirable to selectively turn off backtracking. This is done by cut (!). The cut, denoted by!, is a predicate without any arguments. It is used as a condition which can be confirmed only once by the PROLOG interpreter: on backtracking it is not possible to confirm a cut for the second time. Moreover, the cut has a significant side effect on the remainder of the backtracking process: it enforces the interpreter to reject the clause containing the cut, and also to ignore all other alternatives for the procedure call which led to the execution of the particular clause. Example 11.7 backtracking. a :- b,c,d. c :- p,q,!,r,s. c. Suppose that upon executing the call a, the successive procedure calls b, p, q, the cut and r have succeeded (the cut by definition always succeeds on first encounter). Furthermore, assume that no match can be found for the procedure call s. Then as usual, the interpreter tries to find an alternative match for the procedure call r. For each alternative match for r, it again tries to find a match for condition s. If no alternatives for r can be found, or similarly if all alternative matches have been tried, the interpreter normally would try to find an alternative match for q. However, since we have specified a cut between the procedure calls q and r, the interpreter will not look for alternative matches for the procedure calls preceding r in the specific clause. In addition, the interpreter will not try any alternatives for the procedure call c; so, clause 3 is ignored. Its first action after encountering the cut during backtracking is to look for alternative matches for the condition preceding the call c, that is, for b.