Prolog

advertisement
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
CSC411
Artificial Intelligence
1
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).
CSC411
Artificial Intelligence
2
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
CSC411
Artificial Intelligence
3
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
CSC411
Logic formula:
male(X) 
father(F, X) 
mother(M, X) 
father(F, Y) 
mother(M, Y)

brother(X, Y)
Artificial Intelligence
Prolog:
brother(X, Y) :male(X),
father(F,X),
mother(M,X),
father(F,Y),
mother(M, Y).
4
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).
CSC411
Artificial Intelligence
5
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
–
–
–
–
CSC411
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
Artificial Intelligence
6
Program Trace Tree
brother(philip, jane)
male(philip)
parent(P, philip)
parent(P, jane)
X=philip
father(P,philip)
mother(P,philip)
father(P,jane)
P=bill
male(philip)
CSC411
mother(P,jane)
P=bill
father(bill,philip)
Artificial Intelligence
father(bill, jane)
7
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).
CSC411
Artificial Intelligence
8
Program Execution Trace
uncle(X, george)
Y/george
brother(X, P)
parent(P, Y)
X/bill, P/john
P/X, Y/george
mother(X, Y)
X/jane
mother(jane, george)
CSC411
father(X, Y)
brother(bill, john)
X/john
father(john, george)
Artificial Intelligence
9
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”
CSC411
Artificial Intelligence
10
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
–
–
–
–
CSC411
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)
Artificial Intelligence
11
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 versiondependent
CSC411
Artificial Intelligence
12
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
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.
CSC411
Artificial Intelligence
13
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).
CSC411
Artificial Intelligence
14
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]
– 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]
CSC411
Artificial Intelligence
15
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
CSC411
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
Artificial Intelligence
16
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).
CSC411
Artificial Intelligence
17
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?
CSC411
Artificial Intelligence
18
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.
CSC411
Artificial Intelligence
19
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:
–
–
CSC411
Matching: Top  down
Subgoals: right  left
Artificial Intelligence
20
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).
CSC411
Artificial Intelligence
21
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),
N2), X=Y+Z.
fib(Z,
Two uses:
– Control the shape of the search tree
– Control recursion
CSC411
Artificial Intelligence
22
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
CSC411
Artificial Intelligence
23
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).
CSC411
Artificial Intelligence
24
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]).
CSC411
Artificial Intelligence
25
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).
CSC411
Artificial Intelligence
26
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).
CSC411
Artificial Intelligence
27
The ADT Set
A collection of elements
– No order
– No duplicates
Operations
–
–
–
–
–
–
–
–
–
CSC411
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
Artificial Intelligence
28
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).
CSC411
Artificial Intelligence
29
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).
CSC411
Artificial Intelligence
30
Sample crossings for the farmer, wolf, goat, and cabbage
problem.
CSC411
Artificial Intelligence
31
Portion of the state space graph of the farmer, wolf,
goat, and cabbage problem, including unsafe states.
CSC411
Artificial Intelligence
32
Production Rules in Prolog
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.
CSC411
Artificial Intelligence
33
Production Rules in Prolog
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)
CSC411
Artificial Intelligence
34
Download