chapter 15 an introduction to prolog

34
CSC411 CSC411 Artificial Intelligence Artificial Intelligence 1 Chapter 15 Chapter 15 An Introduction to An Introduction to PROLOG PROLOG Syntax for Predicate Calculus Abstract Data Types (ADTs) in PROLOG A Production System Example in PROLOG Designing Alternative Search Strategies Contents

Upload: dougal

Post on 16-Jan-2016

60 views

Category:

Documents


0 download

DESCRIPTION

Chapter 15 An Introduction to PROLOG. Contents. Syntax for Predicate Calculus Abstract Data Types (ADTs) in PROLOG A Production System Example in PROLOG Designing Alternative Search Strategies. Represent Facts and Rules. Facts (propositions): e.g. male(philip). - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 11

Chapter 15Chapter 15

An Introduction to PROLOGAn Introduction to PROLOG

• Syntax for Predicate Calculus

• Abstract Data Types (ADTs) in PROLOG

• A Production System Example in PROLOG

• Designing Alternative Search Strategies

Contents

Page 2: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 22

Represent Facts and RulesRepresent Facts and RulesFacts (propositions): e.g.Facts (propositions): e.g.

male(philip).male(philip).

Rules (implications): e.g. Rules (implications): e.g. parent(X, Y) := father(X, Y).parent(X, Y) := father(X, Y).

parent(X, Y) := mother(X, Y).parent(X, Y) := mother(X, Y).

parent(X, Y) := father(X, Y); mother(X, Y).parent(X, Y) := father(X, Y); mother(X, Y).

Questions (start point of execution):Questions (start point of execution):e.g.e.g.

?-parent(X, Y).?-parent(X, Y).

Page 3: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 33

Prolog as LogicProlog as LogicHorn clause – a subset of first-order logicHorn clause – a subset of first-order logicLogic formula:Logic formula:– Description – A – e.g. philip is male.Description – A – e.g. philip is male.– Logic OR – A Logic OR – A B : B : A; B.A; B.– Logic AND – A Logic AND – A B : B : A, B.A, B.– Logic NOT -- Logic NOT -- A : A : not A.not A.– Logic implication: A Logic implication: A B : B : B :- A.B :- A.Each expression terminates with a .Each expression terminates with a .Deductive inference – Modus ponentsDeductive inference – Modus ponents

AAA A B B-------- -------- BB

Page 4: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 44

A Simple RuleA 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 YThen 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).

Page 5: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 55

A Simple ProgramA Simple ProgramA 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).

Page 6: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 66

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

Page 7: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 77

Program Trace TreeProgram Trace Tree

brother(philip, jane)

male(philip) parent(P, philip) parent(P, jane)

father(P,philip) mother(P,philip) father(P,jane) mother(P,jane)

male(philip) father(bill,philip) father(bill, jane)

X=philip

P=bill P=bill

Page 8: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 88

Another ExampleAnother ExampleFactsFacts

mother(jane, george).mother(jane, george).father(john, george).father(john, george).Brother(bill, john).Brother(bill, john).

Rules:Rules:parent(X, Y) :- mother(X, Y).parent(X, Y) :- mother(X, Y).parent(X, Y) :- father(X, Y).parent(X, Y) :- father(X, Y).uncle(X, Y) :- parent(P, Y), brother(X, P).uncle(X, Y) :- parent(P, Y), brother(X, P).

Question:Question:?- uncle(X, george).?- uncle(X, george).

Page 9: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 99

Program Execution TraceProgram Execution Traceuncle(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

Page 10: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1010

Unification and BacktrackingUnification and BacktrackingFirst matching (dashed line):First matching (dashed line):– parent(jane, george)parent(jane, george) -- P -- P janejane– brother(bill, john)brother(bill, john) -- P -- P john johnwhich is not consistent.which is not consistent.

Backtracking (solid line):Backtracking (solid line):– parent(john, george) parent(john, george) -- P -- P john john– Brother(bill, john)Brother(bill, john) -- P -- P john johnwhich is unifiedwhich is unified

Multiple solutionsMultiple solutions– Interactive programInteractive program– InterpreterInterpreter– Once the program outputs, the user can respond with ; Once the program outputs, the user can respond with ;

to ask for more solutionsto ask for more solutions– If no more solutions, the program answers “no”If no more solutions, the program answers “no”

Page 11: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1111

Prolog EnvironmentProlog EnvironmentAdd new predicatesAdd new predicates– assert(P) – add new predicate P to database assert(P) – add new predicate P to database – asserta(P) – add P to the beginning of databaseasserta(P) – add P to the beginning of database– assertz(P) – add P to the end of databaseassertz(P) – add P to the end of database

Delete predicatesDelete predicates– retract(P) – remove P fromdatabaseretract(P) – remove P fromdatabase

Import database from a fileImport database from a file– consult(File)consult(File)

Input/outputInput/output– read(X) – read a term from the input stream to Xread(X) – read a term from the input stream to X– write(X) – put the term X in the output streamwrite(X) – put the term X in the output stream– see(File) – open a file for reading (input stream)see(File) – open a file for reading (input stream)– tell(File) – open a file for writing (output stream)tell(File) – open a file for writing (output stream)

Page 12: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1212

Prolog Program Execution TracingProlog Program Execution TracingList all clauses with the predicate nameList all clauses with the predicate name– listing(P) – regardless of the number of listing(P) – regardless of the number of

arguments arguments Monitor the program progressMonitor the program progress– trace – print every goaltrace – print every goal– exit – when a goal is satisfiedexit – when a goal is satisfied– retry – if more matchesretry – if more matches– fail – enforce failfail – enforce fail– notrace – stop the tracenotrace – stop the traceTrace PredicatesTrace Predicates– spy – print all uses of predicates spy – print all uses of predicates More predicates exist and are version-More predicates exist and are version-dependentdependent

Page 13: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1313

RecursionRecursionBase case – a set of rules for direct solutionBase case – a set of rules for direct solutionNormal case – another set of rules for indirection solutionNormal case – another set of rules for indirection solutionE.g.E.g.

child(X, Y) :- mother(Y, X).child(X, Y) :- mother(Y, X).child(X, Y) :- father(Y, X).child(X, Y) :- father(Y, X).descendant(X, Y) :- child(X, Y).descendant(X, Y) :- child(X, Y). base case base casedescendent(X, Y) :- child(X, Z), descendent(Z, Y).descendent(X, Y) :- child(X, Z), descendent(Z, Y).

E.g.E.g. Fibnacci number: Fibnacci number: fib(0) = 0, fib(1) = 1, fib(0) = 0, fib(1) = 1, base case base case

fib(n) = fib(n-1) + fib(n-2)fib(n) = fib(n-1) + fib(n-2) normal case normal case Prolog program:Prolog program:

Facts:Facts: fib(0, 0).fib(0, 0).fib(1, 1).fib(1, 1).

Rules:Rules: fib(X, N) :- N > 1, N1 is N - 1, N2 is N – 2, fib(X, N) :- N > 1, N1 is N - 1, N2 is N – 2, fib(Y, N1), fib(Z, N2), X is Y + Z.fib(Y, N1), fib(Z, N2), X is Y + Z.

Question:Question: ? :- fib(X, 5).? :- fib(X, 5).X = 5.X = 5.? :- fib(5, N).? :- fib(5, N).N = 5.N = 5.? :- fib(X, 8).? :- fib(X, 8).X = 21.X = 21.

Page 14: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1414

Data RepresentationData RepresentationAtom – numbers, strings, etc.Atom – numbers, strings, etc.Structured data – patternStructured data – pattern– Format: functor(parameter-list) where parameters in the list Format: functor(parameter-list) where parameters in the list

are either atom or structured data separated with “,”are either atom or structured data separated with “,”– E.g.E.g. person(name)person(name)

student(person(name), age)student(person(name), age)male(bill)male(bill)female(jane)female(jane)

– Special functor dot (.)Special functor dot (.)Represents list:Represents list: .(p, .pattern).(p, .pattern)Special .pattern:Special .pattern: .().() [], empty list [], empty listE.g.:E.g.: .(p, .(q, .(r, .(s, .())))).(p, .(q, .(r, .(s, .()))))List:List: [p, q, r, s][p, q, r, s]Operations:Operations: [X|Y] [X|Y] pattern pattern

– Anonyous variable:Anonyous variable: underscore (_) underscore (_) – E.g. E.g. member(X, [X|_]) :- !.member(X, [X|_]) :- !.

member(X, [_|Y]) :- member(X, Y).member(X, [_|Y]) :- member(X, Y).

Page 15: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1515

ListsListsA sequence of elements separated by comma and enclosed A sequence of elements separated by comma and enclosed by [ and ]by [ and ]List elements can be other listsList elements can be other listsExamples: Examples: [1, 2, 3, 4][1, 2, 3, 4]

[a, george, [b, jack], 3][a, george, [b, jack], 3]Empty list:Empty list: [][]Non-empty lists consists of two partsNon-empty lists consists of two parts– Header – the first elementHeader – the first element– Tail – the list containing all elements except the firstTail – the list containing all elements except the first– Can be written [Header|Tail]Can be written [Header|Tail]

Example:Example: for list [a, 1, b, 2]for list [a, 1, b, 2]– Header: aHeader: a– Tail: [1, b, 2]Tail: [1, b, 2]

Match: Match: – headers match and tails matchheaders match and tails match– Match [a, 1, b, 2] with [H|T]Match [a, 1, b, 2] with [H|T]

H = aH = aT = [1, b, 2]T = [1, b, 2]

Page 16: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1616

List and RecursionList and RecursionRecursively process all elements in a listRecursively process all elements in a listUsually the base case is the Empty listUsually the base case is the Empty listNormal casesNormal cases– Process the headerProcess the header– Recursion on the tailRecursion on the tail

Example: membership testExample: membership testmember(X, [X|T]).member(X, [X|T]).member(X, [_|T]) :- member(X, T).member(X, [_|T]) :- member(X, T).?- member(a, [a, b, c, d]).?- member(a, [a, b, c, d]).YesYes;;nono?- member(a, [1, [a, b], 2, [c, d]).?- member(a, [1, [a, b], 2, [c, d]).no no ?- member(X, [a, b, c]?- member(X, [a, b, c]X = aX = a;;X = bX = b;;X = cX = c;;nono

Page 17: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1717

More Recursion ExamplesMore Recursion ExamplesWrite out a list one element to a lineWrite out a list one element to a line

writelist([]).writelist([]).writelist([H|T) :- write(H), nl, writelist(T).writelist([H|T) :- write(H), nl, writelist(T).

Write out a list in reverse orderWrite out a list in reverse orderReverse_writelist([]).Reverse_writelist([]).Reverse_writelist([H|T]) :- reverse_writelist(T), write(H), Reverse_writelist([H|T]) :- reverse_writelist(T), write(H),

nl.nl.

Append a list to anotherAppend a list to anotherappend([], L, L).append([], L, L).append([H|T], L, [H|X]) :- append(T, L, X).append([H|T], L, [H|X]) :- append(T, L, X).

Reverse a listReverse a listreverse([], []).reverse([], []).reverse([H|T], X) :- reverse(T, Y), append(Y, [H], X).reverse([H|T], X) :- reverse(T, Y), append(Y, [H], X).

Page 18: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1818

Count the number of elements Count the number of elements

Count the number of elements in a Count the number of elements in a listlist– Base case: Base case: if the list is empty, then number if the list is empty, then number

of elements is 0of elements is 0

– Normal case: Normal case: the number of elements in the the number of elements in the list is the number of elements in the tail plus 1list is the number of elements in the tail plus 1

– Rules? Rules?

Page 19: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 1919

Count the number of elements Count the number of elements

Find the number of elements in a listFind the number of elements in a listlength:-length([], 0) :- !.length:-length([], 0) :- !.

length([X|Y], N) :- length(Y, M), N is M+1.length([X|Y], N) :- length(Y, M), N is M+1.

Page 20: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2020

Recursive SearchRecursive SearchDepth-first search with backtrackingDepth-first search with backtrackingOrdering of facts and rules affect the Ordering of facts and rules affect the problem-solving efficiencyproblem-solving efficiencySearch a subgoal:Search a subgoal:

– Top Top down: matching facts and heads of down: matching facts and heads of rulesrules

Decomposition of goals:Decomposition of goals:– Left Left right right

Backtracking:Backtracking:– Matching: Top Matching: Top down down– Subgoals: right Subgoals: right left left

Page 21: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2121

Closed-world assumption and Closed-world assumption and negation (NOT)negation (NOT)

Question:Question: ?- X.?- X.– Assumption:Assumption:

If you prove X then X is true.If you prove X then X is true.

Otherwise X is false.Otherwise X is false.

Question:Question: ?- ?- not Xnot X..– Assumption:Assumption:

If you can prove If you can prove not Xnot X then then not Xnot X is true; is true;

Otherwise Otherwise not Xnot X is false, meaning X is true. is false, meaning X is true.

So, if can not prove either X or So, if can not prove either X or not Xnot X, , then ?- X. and ?- then ?- X. and ?- not Xnot X. both false (true).. both false (true).

Page 22: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2222

Stop (cut) Backtracking Stop (cut) Backtracking ! – success once and only once! – success once and only once

Efficiency – cut backtracking Efficiency – cut backtracking

E.g.E.g.fib(0, 0) :- !.fib(0, 0) :- !.

fib(1, 1) :- !.fib(1, 1) :- !.

fib(X, N) :- N1 = N-1, N2=N-2, fib(Y, N1), fib(X, N) :- N1 = N-1, N2=N-2, fib(Y, N1), fib(Z, N2), X=Y+Z.fib(Z, N2), X=Y+Z.

Two uses:Two uses:– Control the shape of the search treeControl the shape of the search tree– Control recursionControl recursion

Page 23: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2323

Abstract Data Types in PrologAbstract Data Types in PrologADTADT– A set of operationsA set of operations– No data structure specifiedNo data structure specified

ADT building componentsADT building components– Recursion, list, and pattern matchingRecursion, list, and pattern matching– List handing and recursive processing List handing and recursive processing

are hidden in ADTsare hidden in ADTs

Typical ADTsTypical ADTs– Stack, Queue, Set, Priority QueueStack, Queue, Set, Priority Queue

Page 24: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2424

The ADT StackThe ADT StackCharacteristicsCharacteristics– LIFO (Last-in-first-out)LIFO (Last-in-first-out)

OperationsOperations– Empty testEmpty test– Push an element onto the stackPush an element onto the stack– Pop the top element from the stackPop the top element from the stack– Peek to see the top elementPeek to see the top element– Member_stack to test membersMember_stack to test members– Add_list to add a list of elements to the StackAdd_list to add a list of elements to the Stack

ImplementationImplementation– empty_stack([]).empty_stack([]).– stack(Top, Stack, [Top|Stack]).stack(Top, Stack, [Top|Stack]).

Push – bind first two elements and free the third elementPush – bind first two elements and free the third elementPop – bind the third element and free the first twoPop – bind the third element and free the first twoPeek – same as Pop but keep the third elementPeek – same as Pop but keep the third element

– member_stack(Element, Stack) :- member(Element, Stack).member_stack(Element, Stack) :- member(Element, Stack).– add_list_to_stack(List, Stack, Result):-append(List, Stack, add_list_to_stack(List, Stack, Result):-append(List, Stack,

Result).Result).

Page 25: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2525

Print a Stack in Reverse OrderPrint a Stack in Reverse Orderempty_stack([]).empty_stack([]).stack(Top, Stack, [Top|Stack]).stack(Top, Stack, [Top|Stack]).member_stack(E, Stack) :-member_stack(E, Stack) :-

member(E, Stack).member(E, Stack).add_list_to_stack(L, S, R) :-add_list_to_stack(L, S, R) :-

append(L, S, R).append(L, S, R).reverse_print_stack(S) :-reverse_print_stack(S) :-

empty_stack(S), !.empty_stack(S), !.reverse_print_stack(S) :- reverse_print_stack(S) :-

stack(H, T, S),stack(H, T, S),reverse_print_stack(T),reverse_print_stack(T),write(H), nl.write(H), nl.

?- reverse_print_stack([1, 2, 3, 4, 5]).?- reverse_print_stack([1, 2, 3, 4, 5]).

Page 26: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2626

The ADT QueueThe ADT QueueCharacteristicsCharacteristics– FIFO (First-in-first-out)FIFO (First-in-first-out)

OperationsOperations– Empty testEmpty test– Enqueue – add an element to the endEnqueue – add an element to the end– Dequeue – remove the first elementDequeue – remove the first element– Peek – see the first elementPeek – see the first element– Member testMember test– Merge two queuesMerge two queues

ImplementationImplementation– empty_queue([]).empty_queue([]).– enqueue(E, [], [E]).enqueue(E, [], [E]).

enqueue(E, [H|T], [H|Tnew]) :- enqueue(E, T, Tnew).enqueue(E, [H|T], [H|Tnew]) :- enqueue(E, T, Tnew).– dequeue(E, [E|T], T).dequeue(E, [E|T], T).– dequeue(E, [E|T], _).dequeue(E, [E|T], _). % peek% peek– member_queue(E, Q) :- member(E, Q).member_queue(E, Q) :- member(E, Q).– Add_list_to_queue(L, Q, R) :- append(Q, L, R).Add_list_to_queue(L, Q, R) :- append(Q, L, R).

Page 27: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2727

The ADT Priority QueueThe ADT Priority QueueCharacteristicsCharacteristics– Each element is associated with a priorityEach element is associated with a priority– Always remove the “smallest” oneAlways remove the “smallest” one

OperationsOperations– Empty testEmpty test– Member testMember test– Add an element to the priority queueAdd an element to the priority queue– Min – find the minimum elementMin – find the minimum element– Remove the minimum elementRemove the minimum element– Add a list to a priority queueAdd a list to a priority queue

ImplementationImplementation– empty_pq([]).empty_pq([]).– member_pq(X, P) :- member(X, P).member_pq(X, P) :- member(X, P).– insert_pq(E, [], [E]) :- !.insert_pq(E, [], [E]) :- !.

insert_pq(E, [H|T], [E, H|T]) :- E < H.insert_pq(E, [H|T], [E, H|T]) :- E < H.insert_pq(E, [H|T], [H|Tnew]) :- insert_pq(E, T, Tnew).insert_pq(E, [H|T], [H|Tnew]) :- insert_pq(E, T, Tnew).

– min_pq(E, [E|_]).min_pq(E, [E|_]).– remove_min_pq(E, [E|T], T).remove_min_pq(E, [E|T], T).– add_list_pq([], L. L).add_list_pq([], L. L).

add_list_pq([H|T], L, R) :- insert_pq(H, L, L2), add_list_pq(T, L2, Lnew).add_list_pq([H|T], L, R) :- insert_pq(H, L, L2), add_list_pq(T, L2, Lnew).

Page 28: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2828

The ADT SetThe ADT SetA collection of elementsA collection of elements– No orderNo order– No duplicatesNo duplicatesOperationsOperations– Empty testEmpty test– Member testMember test– Add an element to the setAdd an element to the set– Remove an element from the setRemove an element from the set– Union two setsUnion two sets– Intersect two setsIntersect two sets– Difference two setsDifference two sets– Subset testSubset test– Equality testEquality test

Page 29: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 2929

The Set ImplementationThe Set Implementationempty_set([]).empty_set([]).member_set(E, S) :- member(E, S).member_set(E, S) :- member(E, S).delete_from_set(E, [], []).delete_from_set(E, [], []).delete_from_set(E, [E|T], T) :- !.delete_from_set(E, [E|T], T) :- !.delete_from_set(E, [H|T], [E|Tnew]) :- delete_from_set(E, 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, S) :- member(E, S), !.add_to_set(E, S, [X|S]).add_to_set(E, S, [X|S]).union([], S, S).union([], S, S).union([H|T], S, R) :- union(T, S, S2), add_to_set(H, S2, R).union([H|T], S, R) :- union(T, S, S2), add_to_set(H, S2, R).subset([], _).subset([], _).subset([H|T], S) :- member(H, S), subset(T, S).subset([H|T], S) :- member(H, S), subset(T, S).intersection([], _, []).intersection([], _, []).intersection([H|T], S, [H|R]) :- member(H, S), intersection(T, S, R), !.intersection([H|T], S, [H|R]) :- member(H, S), intersection(T, S, R), !.intersection([_|T], S, R) :- intersection(T, S, R), !.intersection([_|T], S, R) :- intersection(T, S, R), !.Set_diff([], _, []).Set_diff([], _, []).set_diff([H|T], S, R) :- member(H,S), set_diff(T, S, R), !.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), !.set_diff([H|T], S, [H|R]) :- set_diff(T, S, R), !.equal_set(S1, S2) :- subset(S1, S2), subset(S2, S1).equal_set(S1, S2) :- subset(S1, S2), subset(S2, S1).

Page 30: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 3030

A Production System in PrologA Production System in PrologFarmer, wolf, goat, and cabbage problemFarmer, wolf, goat, and cabbage problem– A farmer with his wolf, goat, and cabbage come to the edge of 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, 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 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 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; 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 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 eat the cabbage. Devise a sequence of crossings of the river so that all four characters arrives safely on the other side of the that all four characters arrives safely on the other side of the river.river.

RepresentationRepresentation– state(F, W, G, C) describes the location of Farmer, Wolf, Goat, state(F, W, G, C) describes the location of Farmer, Wolf, Goat,

and Cabbageand Cabbage– Possible locations are Possible locations are ee for east bank, for east bank, ww for west bank for west bank– Initial state is state(w, w, w, w)Initial state is state(w, w, w, w)– Goal state is state(e, e, e, e)Goal state is state(e, e, e, e)– Predicates opp(X, Y) indicates that X and y are opposite sides Predicates opp(X, Y) indicates that X and y are opposite sides

of the riverof the river– Facts: Facts:

opp(e, w).opp(e, w).opp(w, e).opp(w, e).

Page 31: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 3131

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

Page 32: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 3232

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

Page 33: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 3333

Unsafe statesUnsafe statesunsafe(state(X, Y, Y, C)) :- opp(X, Y).unsafe(state(X, Y, Y, C)) :- opp(X, Y).unsafe(state(X, W, Y, Y)) :- opp(X, Y).unsafe(state(X, W, Y, Y)) :- opp(X, Y).

Move rulesMove rulesmove(state(X, X, G, C), state(Y, Y, G, C))) :- opp(X, Y), move(state(X, X, G, C), state(Y, Y, G, C))) :- opp(X, Y),

not(unsafe(state(Y, Y, G, C))), not(unsafe(state(Y, Y, G, C))), writelist([‘farms takes wolf’, 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), move(state(X, W, X, C), state(Y, W, Y, C)) :- opp(X, Y), not(unsafe(state(Y, W, Y, C))), not(unsafe(state(Y, W, Y, C))), writelist([‘farmers takes goat’, 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),move(state(X, W, G, X), state(Y, W, G, Y)) :- opp(X, Y),not(unsafe(state(Y, W, G, Y))), not(unsafe(state(Y, W, G, Y))), writelist(‘farmer takes cabbage’, 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), move(state(X, W, G, C), state(Y, W, G, C)) :-opp(X, Y), not(unsafe(state(Y, W, G, C))), not(unsafe(state(Y, W, G, C))), writelist([‘farmer takes self’, Y, W, G, C]).writelist([‘farmer takes self’, Y, W, G, C]).

move(state(F, W, G, C), state(F, W, G, C)) :- move(state(F, W, G, C), state(F, W, G, C)) :- writelist([‘Backtrack from ‘, F, W, G, C]), fail.writelist([‘Backtrack from ‘, F, W, G, C]), fail.

Production Rules in PrologProduction Rules in Prolog

Page 34: Chapter 15 An Introduction to PROLOG

CSC411CSC411 Artificial IntelligenceArtificial Intelligence 3434

Path rulesPath rulespath(Goal, Goal, Stack) :- path(Goal, Goal, Stack) :-

write(‘Solution Path Is: ‘), nl, write(‘Solution Path Is: ‘), nl, reverse_print_stack(Stack).reverse_print_stack(Stack).

path(State, Goal, Stack) :- path(State, Goal, Stack) :- move(State, Next), move(State, Next),

not(member_stack(Next, not(member_stack(Next, Stack)), Stack)),

stack(Next, Stack, NewStack), stack(Next, Stack, NewStack), path(Next, Goal, NewStack), !.path(Next, Goal, NewStack), !.

Start ruleStart rulego(Start, Goal) :- go(Start, Goal) :-

empty_stack(EmptyStack), empty_stack(EmptyStack), stack(Start, EmptyStack, Stack), stack(Start, EmptyStack, Stack), path(Start, Goal, Stack).path(Start, Goal, Stack).

QuestionQuestion?- go(state(w, w, w, w), state(e, e, e, e)?- go(state(w, w, w, w), state(e, e, e, e)

Production Rules in PrologProduction Rules in Prolog