CSC411Artificial Intelligence1 Chapter 15 An Introduction to PROLOG Syntax for Predicate Calculus Abstract Data Types (ADTs) in PROLOG A Production System.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Problem Solving Well-formed predicate calculus expressions provide a means of describing objects and relations in a problem domain and inference rule.
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).
INTRODUCTION TO PROLOG. PROLOG BASICS Atoms - most primitive terms that the language manipulates start with lower case letter includes strings (‘inside.
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
CS 330 Programming Languages 12 / 12 / 2006 Instructor: Michael Eckmann.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Building Control Algorithms For State Space Search
Prolog A Production System Example.
Inference and Resolution for Problem Solving
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 15 Logic Programming Q: How many legs does.
(9.1) COEN Logic Programming  Logic programming and predicate calculus  Prolog statements  Facts and rules  Matching  Subgoals and backtracking.
Prolog Programming Lecture Module 13. Objective ● What is Prolog? ● Prolog program ● Syntax of Prolog ● Prolog Control Strategy ● Execution of Prolog.
ISBN Chapter 16 Logic Programming Languages.
Logic Programming Languages
P-Phunck - Prolog1 Introduction to Prolog Brian Paden.
Notes for Chapter 12 Logic Programming The AI War Basic Concepts of Logic Programming Prolog Review questions.
ISOM MIS 215 Module 3 – Stacks and Queues. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
CS 321 Programming Languages and Compilers Prolog part 2.
Lists – More Examples  ‘Translate’ a list to another list  Counting  Split a given list into two  Merge two lists into one  Output a list (some I/O.
COP4020 Programming Languages Logical programming with Prolog Prof. Xin Yuan.
1-1 Introduction Logic programming languages, sometimes called declarative programming languages Express programs in a form of symbolic logic Use a logical.
Knowledge and search, page 1 CSI 4106, Winter 2005 Knowledge and search Points Properties of knowledge  Completeness  Objectivity  Certainty  Formalizability.
ARTIFICIAL INTELLIGENCE Lecture 3 Predicate Calculus.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now Chapter 9, exs 4 and 6. –6 must be in Horn clause form Prolog Handout 2.
1 Knowledge Based Systems (CM0377) Lecture 3 (Last modified 5th February 2001)
1 COMP 205 Introduction to Prolog Dr. Chunbo Chu Week 14.
1 Prolog and Logic Languages Aaron Bloomfield CS 415 Fall 2005.
CS Introduction to AI Tutorial 8 Resolution Tutorial 8 Resolution.
Logic Programming Prolog Program = sequence of FOPC sentences All sentences are Horn clauses p1  p2  …  pn  q All variables are universally quantified.
Prolog Cut to Control Search Abstract Data Types Practical Examples Summary.
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.
Automated Reasoning Early AI explored how to automated several reasoning tasks – these were solved by what we might call weak problem solving methods as.
Ch. 13 Ch. 131 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (notes?) Dr. Carter Tiernan.
UNIVERSITI TENAGA NASIONAL CMPB454 ARTIFICIAL INTELLIGENCE (AI) CHAPTER 6 LOGIC PROGRAMMING USING PROLOG CHAPTER 6 LOGIC PROGRAMMING USING PROLOG Instructor:
Introduction to Prolog. Outline What is Prolog? Prolog basics Prolog Demo Syntax: –Atoms and Variables –Complex Terms –Facts & Queries –Rules Examples.
© 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.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
KU NLP Artificial Intelligence1 Ch 14. An Introduction to Prolog q an Implementation of logic as a programming language(PROgramming in LOGig) q many interesting.
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.
Knowledge Based Information System
In The Name Of Allah Lab 03 1Tahani Aldweesh. objectives Searching for the solution’s. Declaration. Query. Comments. Prolog Concepts. Unification. Disjunction.
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”
C H A P T E R N I N E Logic Programming Part 2 Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
Prolog Overview Syntax Mechanism Summary. Overview PROLOG : Programming with Logic Uses predicate (first-order) calculus History: Roots: J.A. Robinson.
Copyright 1999Paul F. Reynolds, Jr. Foundations of Logic Programming.
Section 16.5, 16.6 plus other references
By P. S. Suryateja Asst. Professor, CSE Vishnu Institute of Technology
Set Collection A Bag is a general collection class that implements the Collection interface. A Set is a collection that resembles a Bag with the provision.
Data Structure Interview Question and Answers
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now:
Introduction to Data Structure
Prolog fundamentals Module 14.2 COP4020 – Programming Language Concepts Dr. Manuel E. Bermudez.
Chapter 3: Prolog (Lists, Arithmetic, Operators)
Logic Programming Language
Chapter 2: Prolog (Introduction and Basic Concepts)
Presentation transcript:

CSC411Artificial Intelligence1 Chapter 15 An Introduction to PROLOG Syntax for Predicate Calculus Abstract Data Types (ADTs) in PROLOG A Production System Example in PROLOG Designing Alternative Search Strategies Contents

CSC411Artificial Intelligence2 Represent Facts and Rules Facts (propositions): e.g. male(philip). Rules (implications): e.g. parent(X, Y) := father(X, Y). parent(X, Y) := mother(X, Y). parent(X, Y) := father(X, Y); mother(X, Y). Questions (start point of execution): e.g. ?-parent(X, Y).

CSC411Artificial Intelligence3 Prolog as Logic Horn clause – a subset of first-order logic Logic formula: –Description – A – e.g. philip is male. –Logic OR – A  B : A; B. –Logic AND – A  B : A, B. –Logic NOT -- A : not A. –Logic implication: A  B : B :- A. Each expression terminates with a. Deductive inference – Modus ponents A A  B B

CSC411Artificial Intelligence4 A Simple Rule English description: If X is male, F is the father of X, M is the mother of X, F is the father of Y, M is the mother of Y Then X is a brother of Y Logic formula: male(X)  father(F, X)  mother(M, X)  father(F, Y)  mother(M, Y)  brother(X, Y) Prolog: brother(X, Y) :- male(X), father(F,X), mother(M,X), father(F,Y), mother(M, Y).

CSC411Artificial Intelligence5 A Simple Program A Prolog program is a sequence of facts and rules brother(X, Y) :- male(X), parent(P, X),parent(P, Y). parent(X, Y):- father(X, Y); mother(X, Y). male(philip). father(bill, philip). ?- brother(philip, jane).

CSC411Artificial Intelligence6 Program Execution Start from the question Matching – match the question with facts and rules by substitution (try) Unification – looking for unified solution (consistent solution) Backtracking – once fails, go back to try another case Divide-and-conquer –divide problem into sub problems –solve all sub problems –integrate sub solutions to build the final solution –Solutions to all sub problems must be consistent

CSC411Artificial Intelligence7 Program Trace Tree

CSC411Artificial Intelligence8 Another Example Facts mother(jane, george). father(john, george). Brother(bill, john). Rules: parent(X, Y) :- mother(X, Y). parent(X, Y) :- father(X, Y). uncle(X, Y) :- parent(P, Y), brother(X, P). Question: ?- uncle(X, george).

CSC411Artificial Intelligence9 Program Execution Trace uncle(X, george) parent(P, Y)brother(X, P) mother(X, Y)father(X, Y) brother(bill, john) mother(jane, george)father(john, george) Y/george P/X, Y/george X/jane X/john X/bill, P/john

CSC411Artificial Intelligence10 Unification and Backtracking First matching (dashed line): –parent(jane, george)-- P  jane –brother(bill, john)-- P  john which is not consistent. Backtracking (solid line): –parent(john, george) -- P  john –Brother(bill, john)-- P  john which is unified Multiple solutions –Interactive program –Interpreter –Once the program outputs, the user can respond with ; to ask for more solutions –If no more solutions, the program answers “no”

CSC411Artificial Intelligence11 Prolog Environment Add new predicates –assert(P) – add new predicate P to database –asserta(P) – add P to the beginning of database –assertz(P) – add P to the end of database Delete predicates –retract(P) – remove P fromdatabase Import database from a file –consult(File) Input/output –read(X) – read a term from the input stream to X –write(X) – put the term X in the output stream –see(File) – open a file for reading (input stream) –tell(File) – open a file for writing (output stream)

CSC411Artificial Intelligence12 Prolog Program Execution Tracing List all clauses with the predicate name –listing(P) – regardless of the number of arguments Monitor the program progress –trace – print every goal –exit – when a goal is satisfied –retry – if more matches –fail – enforce fail –notrace – stop the trace Trace Predicates –spy – print all uses of predicates More predicates exist and are version- dependent

CSC411Artificial Intelligence13 Recursion Base case – a set of rules for direct solution Normal case – another set of rules for indirection solution E.g. child(X, Y) :- mother(Y, X). child(X, Y) :- father(Y, X). descendant(X, Y) :- child(X, Y).  base case descendent(X, Y) :- child(X, Z), descendent(Z, Y). E.g.Fibnacci number: fib(0) = 0, fib(1) = 1,  base case fib(n) = fib(n-1) + fib(n-2)  normal case fib(n) = fib(n-1) + fib(n-2)  normal case Prolog program: Facts:fib(0, 0). fib(1, 1). Rules:fib(X, N) :- N > 1, N1 is N - 1, N2 is N – 2, fib(Y, N1), fib(Z, N2), X is Y + Z. Question:? :- fib(X, 5). X = 5. ? :- fib(5, N). N = 5. ? :- fib(X, 8). X = 21.

CSC411Artificial Intelligence14 Data Representation Atom – numbers, strings, etc. Structured data – pattern –Format: functor(parameter-list) where parameters in the list are either atom or structured data separated with “,” –E.g.person(name) student(person(name), age) male(bill)female(jane) –Special functor dot (.) Represents list:.(p,.pattern) Special.pattern:.()  [], empty list E.g.:.(p,.(q,.(r,.(s,.())))) List:[p, q, r, s] Operations:[X|Y]  pattern –Anonyous variable:underscore (_) –E.g. member(X, [X|_]) :- !. member(X, [_|Y]) :- member(X, Y).

CSC411Artificial Intelligence15 Lists A sequence of elements separated by comma and enclosed by [ and ] List elements can be other lists Examples: [1, 2, 3, 4] [a, george, [b, jack], 3] Empty list:[] Non-empty lists consists of two parts –Header – the first element –Tail – the list containing all elements except the first –Can be written [Header|Tail] Example:for list [a, 1, b, 2] Example:for list [a, 1, b, 2] –Header: a –Tail: [1, b, 2] Match: –headers match and tails match –Match [a, 1, b, 2] with [H|T] H = a T = [1, b, 2]

CSC411Artificial Intelligence16 List and Recursion Recursively process all elements in a list Usually the base case is the Empty list Normal cases –Process the header –Recursion on the tail Example: membership test member(X, [X|T]). member(X, [_|T]) :- member(X, T). ?- member(a, [a, b, c, d]). Yes;no ?- member(a, [1, [a, b], 2, [c, d]). no ?- member(X, [a, b, c] X = a ; X = b ; X = c ;no

CSC411Artificial Intelligence17 More Recursion Examples Write out a list one element to a line writelist([]). writelist([H|T) :- write(H), nl, writelist(T). Write out a list in reverse order Reverse_writelist([]). Reverse_writelist([H|T]) :- reverse_writelist(T), write(H), nl. Append a list to another append([], L, L). append([H|T], L, [H|X]) :- append(T, L, X). Reverse a list reverse([], []). reverse([H|T], X) :- reverse(T, Y), append(Y, [H], X).

CSC411Artificial Intelligence18 Count the number of elements Count the number of elements in a list –Base case: if the list is empty, then number of elements is 0 –Normal case: the number of elements in the list is the number of elements in the tail plus 1 –Rules?

CSC411Artificial Intelligence19 Count the number of elements Find the number of elements in a list length:-length([], 0) :- !. length([X|Y], N) :- length(Y, M), N is M+1.

CSC411Artificial Intelligence20 Recursive Search Depth-first search with backtracking Ordering of facts and rules affect the problem-solving efficiency Search a subgoal: –Top  down: matching facts and heads of rules Decomposition of goals: –Left  right Backtracking: –Matching: Top  down –Subgoals: right  left

CSC411Artificial Intelligence21 Closed-world assumption and negation (NOT) Question:?- X. –Assumption: If you prove X then X is true. Otherwise X is false. Question:?- not X. –Assumption: If you can prove not X then not X is true; Otherwise not X is false, meaning X is true. So, if can not prove either X or not X, then ?- X. and ?- not X. both false (true).

CSC411Artificial Intelligence22 Stop (cut) Backtracking ! – success once and only once Efficiency – cut backtracking E.g. fib(0, 0) :- !. fib(1, 1) :- !. fib(X, N) :- N1 = N-1, N2=N-2, fib(Y, N1), fib(Z, N2), X=Y+Z. Two uses: –Control the shape of the search tree –Control recursion

CSC411Artificial Intelligence23 Abstract Data Types in Prolog ADT –A set of operations –No data structure specified ADT building components –Recursion, list, and pattern matching –List handing and recursive processing are hidden in ADTs Typical ADTs –Stack, Queue, Set, Priority Queue

CSC411Artificial Intelligence24 The ADT Stack Characteristics –LIFO (Last-in-first-out) Operations –Empty test –Push an element onto the stack –Pop the top element from the stack –Peek to see the top element –Member_stack to test members –Add_list to add a list of elements to the Stack Implementation –empty_stack([]). –stack(Top, Stack, [Top|Stack]). Push – bind first two elements and free the third element Pop – bind the third element and free the first two Peek – same as Pop but keep the third element –member_stack(Element, Stack) :- member(Element, Stack). –add_list_to_stack(List, Stack, Result):-append(List, Stack, Result).

CSC411Artificial Intelligence25 Print a Stack in Reverse Order empty_stack([]). stack(Top, Stack, [Top|Stack]). member_stack(E, Stack) :- member(E, Stack). add_list_to_stack(L, S, R) :- append(L, S, R). reverse_print_stack(S) :- empty_stack(S), !. reverse_print_stack(S) :- stack(H, T, S), reverse_print_stack(T), write(H), nl. ?- reverse_print_stack([1, 2, 3, 4, 5]).

CSC411Artificial Intelligence26 The ADT Queue Characteristics –FIFO (First-in-first-out) Operations –Empty test –Enqueue – add an element to the end –Dequeue – remove the first element –Peek – see the first element –Member test –Merge two queues Implementation –empty_queue([]). –enqueue(E, [], [E]). enqueue(E, [H|T], [H|Tnew]) :- enqueue(E, T, Tnew). –dequeue(E, [E|T], T). –dequeue(E, [E|T], _).% peek –member_queue(E, Q) :- member(E, Q). –Add_list_to_queue(L, Q, R) :- append(Q, L, R).

CSC411Artificial Intelligence27 The ADT Priority Queue Characteristics –Each element is associated with a priority –Always remove the “smallest” one Operations –Empty test –Member test –Add an element to the priority queue –Min – find the minimum element –Remove the minimum element –Add a list to a priority queue Implementation –empty_pq([]). –member_pq(X, P) :- member(X, P). –insert_pq(E, [], [E]) :- !. insert_pq(E, [H|T], [E, H|T]) :- E < H. insert_pq(E, [H|T], [H|Tnew]) :- insert_pq(E, T, Tnew). –min_pq(E, [E|_]). –remove_min_pq(E, [E|T], T). –add_list_pq([], L. L). add_list_pq([H|T], L, R) :- insert_pq(H, L, L2), add_list_pq(T, L2, Lnew).

CSC411Artificial Intelligence28 The ADT Set A collection of elements –No order –No duplicates Operations –Empty test –Member test –Add an element to the set –Remove an element from the set –Union two sets –Intersect two sets –Difference two sets –Subset test –Equality test

CSC411Artificial Intelligence29 The Set Implementation empty_set([]). member_set(E, S) :- member(E, S). delete_from_set(E, [], []). delete_from_set(E, [E|T], T) :- !. delete_from_set(E, [H|T], [E|Tnew]) :- delete_from_set(E, T). add_to_set(E, S, S) :- member(E, S), !. add_to_set(E, S, [X|S]). union([], S, S). union([H|T], S, R) :- union(T, S, S2), add_to_set(H, S2, R). subset([], _). subset([H|T], S) :- member(H, S), subset(T, S). intersection([], _, []). intersection([H|T], S, [H|R]) :- member(H, S), intersection(T, S, R), !. intersection([_|T], S, R) :- intersection(T, S, R), !. Set_diff([], _, []). set_diff([H|T], S, R) :- member(H,S), set_diff(T, S, R), !. set_diff([H|T], S, [H|R]) :- set_diff(T, S, R), !. equal_set(S1, S2) :- subset(S1, S2), subset(S2, S1).

CSC411Artificial Intelligence30 A Production System in Prolog Farmer, wolf, goat, and cabbage problem –A farmer with his wolf, goat, and cabbage come to the edge of a river they wish to cross. There is a boat at the river’s edge, but, of course, only the farmer can row. The boat also can carry only two things, including the rower, at a time. If the wolf is ever left alone with the goat, the wolf will eat the goat; similarly if the goat is left alone with the cabbage, the goat will eat the cabbage. Devise a sequence of crossings of the river so that all four characters arrives safely on the other side of the river. Representation –state(F, W, G, C) describes the location of Farmer, Wolf, Goat, and Cabbage –Possible locations are e for east bank, w for west bank –Initial state is state(w, w, w, w) –Goal state is state(e, e, e, e) –Predicates opp(X, Y) indicates that X and y are opposite sides of the river –Facts: opp(e, w). opp(w, e).

CSC411Artificial Intelligence31 Sample crossings for the farmer, wolf, goat, and cabbage problem.

CSC411Artificial Intelligence32 Portion of the state space graph of the farmer, wolf, goat, and cabbage problem, including unsafe states.

CSC411Artificial Intelligence33 Unsafe states unsafe(state(X, Y, Y, C)) :- opp(X, Y). unsafe(state(X, W, Y, Y)) :- opp(X, Y). Move rules move(state(X, X, G, C), state(Y, Y, G, C))) :- opp(X, Y), not(unsafe(state(Y, Y, G, C))), writelist([‘farms takes wolf’, Y, Y, G, C]). move(state(X, W, X, C), state(Y, W, Y, C)) :- opp(X, Y), not(unsafe(state(Y, W, Y, C))), writelist([‘farmers takes goat’, Y, W, Y,C]). move(state(X, W, G, X), state(Y, W, G, Y)) :- opp(X, Y), not(unsafe(state(Y, W, G, Y))), writelist(‘farmer takes cabbage’, Y, W, G, Y]). move(state(X, W, G, C), state(Y, W, G, C)) :-opp(X, Y), not(unsafe(state(Y, W, G, C))), writelist([‘farmer takes self’, Y, W, G, C]). move(state(F, W, G, C), state(F, W, G, C)) :- writelist([‘Backtrack from ‘, F, W, G, C]), fail. Production Rules in Prolog

CSC411Artificial Intelligence34 Path rules path(Goal, Goal, Stack) :- write(‘Solution Path Is: ‘), nl, reverse_print_stack(Stack). path(State, Goal, Stack) :- move(State, Next), not(member_stack(Next, Stack)), stack(Next, Stack, NewStack), path(Next, Goal, NewStack), !. Start rule go(Start, Goal) :- empty_stack(EmptyStack), stack(Start, EmptyStack, Stack), path(Start, Goal, Stack). Question ?- go(state(w, w, w, w), state(e, e, e, e) Production Rules in Prolog