Sheet

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24








  . 


 


!
"
#$ ! %&.469 "*! +,-+
 ./0
%!!1 %&!
%2!1 3,1%
,
"!1 ,* 3
%4
4


      !"#  $%& 
' !()* +*%"
!,-#% !" )  ." $ Knowledge Base /0  
$ 0   %  ' !()* 
   12." ."$3 %  $4 %$"#
  $2."
 
!  &  
   # &

  %   ##&  %  3*3! $ " +4  ! 1 2."  !"50 ( 3
676 #&& -%$"   ." %" !"#  89-
& 167
   1   67%$" 50("  !#
   - !
   1 3" ! +(*+!% !9(
%"
  1$ !
2."&!$# 50(& !"  ." !"& 
   %" 
 *
% 5* -*!"  :  0  +*%"- " '$& 5# %  

+  8+9

2."&!
 *

$ "
 

Introduction 1
Prolog Constants 3
Rules 3
Prolog’s Search Strategy 6
Unification & Recursion 7
Lists 8
Box Model of Execution 10
Programming Techniques 12
List Processing 14
Control and Negation 15
Parsing in Prolog 16
Special Control Predicate 18
Input/Output 20
Prolog Example 21
Outline
Introduction to Prolog
Knowledge representation
Logic Programming Prolog’s search strategy
Sukree Sinthupinyo

1 2

Introduction to Prolog Introduction to Prolog (cont’)

PROgramming in LOGic. The special attention should be given to


Prolog is based on First-Order logic. understanding variables in Prolog.
Prolog is known to be a difficult The programmer should pay careful
language to master. attention to the issue of backtracking.
The system does not give too much help to
the programmer to employ structured
programming concepts.

3 4

Logic Programming 1
Knowledge Representation Knowledge Representation (cont’)

How do we represent what we know? Propositional calculus.


Knowledge how procedural knowledge The propositional calculus is based on
such as how to drive a car. statements which have truth values (true
Knowledge that declarative knowledge or false).
such as knowing the speed limit for a car An example:
on a motorway. If p stands for “fred is rich" and q for “fred is
tall“.
Connection symbol ∧, ∨, ⇔, ⇒, ¬

5 6

Knowledge Representation (cont’) We turn to Prolog


First order predicate calculus. “the capital of france is paris“
Permits the description of relations and the use of has_capital(france,paris).
variables.
Variables: X,Y,Z
“jim is tall”
jim(tall).
Constant: x,y,john,jean
tall(jim).
Predicate: brother(x,y)
Formulae: brother(x,y) ∧brother(y,z) There must be no space between the
Sentence: brother(john,jean) predicate name and “(” . The whole thing
also ends in a “.”

7 8

Logic Programming 2
Examples of statement in
Prolog Constants Prolog form
Constant is a string of characters bill likes ice-cream.
starting with a lower case letter. bill is tall
loves(jane,jim).
jane hits jimmy with the cricket bat
jane and jim are constant.
john travels to london by train
No predicate may be variable
X(jane,jim).

9 10

Multiple Clauses Rules


Examples The format is:
bill only eats chocolate, bananas or divisible_by_two:- even.
cheese. This is a non-unit clause.
the square root of 16 is 4 or -4. The head is divisible_by_two.
wales, ireland and scotland are all The body is even.
countries. divisible_by_two is true if even is true

11 12

Logic Programming 3
Rules (continue) Rules (continue)

No more than one goal is allowed in the A number is divisible by two if it is


head. even.
We cannot translate rich(fred) ⇒ We can express this with the help of
happy(fred) ∧ powerful(fred) the logical variable. Here is the
directly into the Prolog version improved rule:
happy(fred),powerful(fred) :- divisible_by_two(X):- even(X).
rich(fred).

13 14

Semantics The Logical Variable


divisible_by_two(X):- even(X). If an object is referred to by a name
If we can find a value of X that satisfies starting with a capital letter then the
the goal even(X) then we have also object has the status of a logical
found a number that satisfies the goal variable.
divisible_by_two(X). The same variables in one rule refer to
the same object.

15 16

Logic Programming 4
The Logical Variable (continue) Rules and Conjunction
The logical variable cannot be A man is happy if he is rich and famous
overwritten with a new value. might translate to:
For example, in Pascal: happy(Person):-
X:= 1; X:= 2;
man(Person),
In Prolog:
rich(Person),
X=1 ∧ X=2.
cannot be true as X cannot be both ‘2’ and ‘1’ famous(Person).
simultaneously. An attempt to make a logical
variable take a new value will fail.

17 18

Both Disjunctions and


Rules and Disjunctions Conjunctions
Someone is happy if they are healthy, happy(Person):-healthy(Person),woman(Person).
happy(Person):-wealthy(Person),woman(Person).
wealthy or wise.
happy(Person):-wise(Person),woman(Person).
translates to:
happy(Person):- healthy(Person).
happy(Person):- wealthy(Person).
happy(Person):- wise(Person).

19 20

Logic Programming 5
Prolog’s Search Strategy Queries and Disjunctions
Prolog use depth-first search. A query is a goal which is submitted to
Prolog enables the programmer to Prolog in order to determine whether
implement other search methods quite this goal is true or false.
easily. Prolog normally expects queries it prints
Prolog is an interactive system. the prompt:
?-

21 22

Queries and Disjunctions (continue) A Simple Conjunction


Perhaps we would like to determine
Program Database
whether or not
woman(jean).
woman(jane)
man(fred).
We can type this wealthy(fred).
?- woman(jane). happy(Person):- woman(Person),
wealthy(Person).

23 24

Logic Programming 6
A Simple Conjunction (continue) A Simple Conjunction (continue)

From the knowledge base, if we would So two sub goals are:


like to find “Is Jean happy?”. woman(jean)
wealthy(jean)
Prolog try to match happy(jean) with
the knowledge base. There is a possible match but we
happy(jean):- woman(jean), cannot unify
wealthy(jean). wealthy(fred) with wealthy(jean)

25 26

Unification Recursion
Unification is a two way matching Prolog depends heavily upon it
process Examples
book(waverley,X) and book(Y,scott)
X/scott, Y/waverley One of my ancestors is one of my parents
or one of their ancestors.
Examples
X=fred. succeeds A string of characters is a single character
jane=fred fail or a single character followed by a string of
Y=fred,X=Y succeeds characters
X=happy(jim) succeeds

27 28

Logic Programming 7
Recursion (continue) Lists
Examples Lists can be regarded as special Prolog
ancestor(X,Y) :- parent(X,Y). structures.
ancestor(X,Y) :- parent(X,Z),
ancestor(Z,Y).
Lists can be used to represent an
Program Database ordered sequence of Prolog terms.
ancestor(X,Y) :- parent(X,Y). Examples
ancestor(X,Y) :- parent(X,Z),
ancestor(Z,Y).
[ice_cream,coffee,chocolate]
parent(bob,bill). parent(bill,jane). [a,b,c,c,d,e]
parent(jane,jim). parent(bob,babe).

29 30

Lists (continue) Lists (continue)

List destruction List construction


[X|Y] = [f,r,e,d]. X=[r,e,d].
will result in X=f. Result_Wanted=[b|X].
The first element of the list is known as the HEAD of will result in Result_Wanted=[b,r,e,d].
the list.
Y=[r,e,d].
The list formed by deleting the head is the TAIL of
the list.

31 32

Logic Programming 8
Lists (continue) Lists (continue)

Bigger Chunks: Bigger Chunks:


Suppose you want to stick the elements a, Conversely, suppose you want to take
b and c onto the front of the list X to make three elements off the front of a list X.
a new list Y. This can be done with X=[A,B,C|Y].
This can be done with Y=[a,b,c|X] Y is available for use as the remaining list.

33 34

Lists (continue) Lists (continue)

Some Possible Matches A recursive program using list


1. [b,a,d]=[d,a,b] fails print_a_list([]).
2. [X]=[b,a,d] fails print_a_list([H|T]):- write(H),
3. [X|Y]=[he,is,a,cat] succeeds print_a_list(T).
4. [X,Y|Z]=[a,b,c,d] succeeds write/1 is a build in predicate, the
5. [X|Y]=[] fails argument is Prolog term.
6. [X|Y]=[[a,[b,c]],d] succeeds
nl/0 is new line command
7. [X|Y]=[a] succeeds

35 36

Logic Programming 9
The Box Model of Execution
The Box Model of Execution (continue)

We can think in term of procedure The control flows into the box through
rather than predicate. the Call port.
Then, Prolog seek a clause with a head
that unify with the goal.
Seek solutions to all the subgoals in the
body of the successful clause.
If the unification fails for all clauses then
control would pass out of the Fail port.

37 38

The Box Model of Execution


(continue) The Flow of Control
Control reaches the Exit port if the
procedure succeeds.
The Redo port can only be reached if
the procedure call has been successful
and some subsequent goal has failed.

39 40

Logic Programming 10
The Flow of Control (continue)
The Flow of Control (continue)

41 42

Practical Matter Practical Matter (continue)

Exit Prolog by the following commands Undeclared predicates could be handled


?- halt. by
^D :- dynamic predicate/arity.
end_of_file. :- dynamic foo/1.
:- dynamic two_hand/1.
Loading file(s) ?- unknown(X,Y).
?- consult(filename). ?- unknown(X,trace).
?- consult(‘test.pl’). ?- unknown(X,fail).
?- consult(‘test’).
?- consult(test).

43 44

Logic Programming 11
Practical Matter (continue) Practical Matter (continue)

Singleton variable Singleton variable


A singleton variable occurs in a clause if a You can use the anonymous variable.
variable is mentioned once and once only. The anonymous variables can be written
mammal(Animal):- dog(Aminal). by the string starting with the underscore
Warning: singleton variable Animal (_).
in procedure mammal/1 member(X,[X|_]).
Warning: singleton variable Aminal
in procedure mammal/1

45 46

Programming Techniques and Programming Techniques and


Lists Processing Lists Processing (continue)
The reversibility of Prolog program We can ask all the following queries.
?- square(2,X).
Program Database
?- square(X,5).
square(1,1).
?- square(X,Y).
square(2,4).
square(3,9). ?- square(2,3).
square(4,16).
square(5,25).
square(6,36).

47 48

Logic Programming 12
Programming Techniques and Programming Techniques and
Lists Processing (continue) Lists Processing (continue)
Evaluation in Prolog successor(X,Y):- Y is X + 1.
?- successor(3,X).
Pascal: Y:=2+1;
?- successor(X,4).
Prolog: Y=2+1.
?- successor(X,Y).
This command only binds the variable Y with
?- successor(3,5).
the clause 2+1 and gives the value of Y as 2+1
Prolog: Y is 2+1.
After the above command, the value of Y is 3.

49 50

Programming Techniques and Programming Techniques and


Lists Processing (continue) Lists Processing (continue)
Calling patterns For example, successor/2 above
For any given predicate with arity greater requires a calling pattern of
than 0, each argument may be intended to 1st argument must be +
have one of three calling patterns: 2nd argument can be + or - and is
Input |indicated with a + therefore ?
Output |indicated with a -
We write this as
Indeterminate |indicated with a ? (+ or -) :- mode successor(+,?).

51 52

Logic Programming 13
Lists Processing Lists Processing (continue)

Program Patterns Example


Test for Existence member(Element,[Element|Tail]).
list_existence_test(Info,[Head|Tail]):- member(Element,[Head|Tail]):-
element_has_property(Info,Head). member(Element,Tail).
list_existence_test(Info,[Head|Tail]):-
list_existence_test(Info,Tail). Test all elements
test_all_have_property(Info,[]).
Example
test_all_have_property(Info,[Head|Tail]):-
nested_list([Head|Tail]):- sublist(Head).
element_has_property(Info,Head),
nested_list([Head|Tail]):- nested_list(Tail).
test_all_have_property(Info,Tail).
sublist([]).
sublist([Head|Tail]).

53 54

Lists Processing (continue) Lists Processing (continue)

Example Example
all_digits([]). everything_after_a([Head|Tail],Result):-
all_digits([Head|Tail]):- Head = a,
member(Head,[0,1,2,3,4,5,6,7,8,9]), Result = Tail.
all_digits(Tail). everything_after_a([Head|Tail],Ans):-
everything_after_a(Tail,Ans).
Return a Result – Having processed one element
return_after_event(Info,[H|T],Result):- Return a Result – Having processed all elements
property(Info,H), process_all(Info,[],[]).
result(Info,H,T,Result). process_all(Info,[H1|T1],[H2|T2]):-
return_after_event(Info,[H|T],Ans):- process_one(Info,H1,H2),
return_after_event(Info,T,Ans). process_all(Info,T1,T2).

55 56

Logic Programming 14
Lists Processing (continue) Control and Negation
Example Some useful predicate for control
triple([],[]). true/0
triple([H1|T1],[H2|T2]):-
father(jim,fred).
H2 is 3*H1,
triple(T1,T2). father(jim,fred) :- true.
fail/0
lives_forever(X) :- fail.
repeat/0
test :- repeat, write(hello), fail.

57 58

Some General Program


Control and Negation (continue) Schemata
call/1 Generate – Test
call(write(hello)).
generate and test(Info,X):-
Negation . . .
\+/1 generate(Info,X),
Equivalent to ¬ test(Info,X),
man(jim). . . .
man(fred).
woman(X) :- \+ man(X).
Finite generator
Infinite generator

59 60

Logic Programming 15
Generate – Test Test – Process
integer_with_two_digit_square(X) :- int(X), test_process(Info,X,Y):-
test square(X).
test(Info,X),
test square(X) :- Y is X*X, Y >= 10, Y < 100.
process(Info,X,Y).
Finite generator
int(1). int(2). int(3). int(4). int(5). Example
parity(X,Y) :- odd(X), Y=odd.
Infinite Generator parity(X,Y) :- \+ (odd(X)),Y=even.
int(1).
int(N) :- int(N1), N is N1+1.

61 62

Failure-Driven Loop Parsing in Prolog


failure_driven_loop(Info):- Simple English Syntax
generate(Info,Term), Unit: sentence Constructed from noun_phrase
fail. followed by a verb_phrase
failure_driven_loop(Info). Unit: noun phrase Constructed from: proper noun
An example or determiner followed by a
noun
int(1). int(2). int(3). int(4).
Unit: verb phrase Constructed from: verb or verb
int(5).
followed by noun_phrase
print_int :- int(X),write(X),nl,fail. Unit: determiner Examples: a, the
print_int. Unit: noun Examples: man, cake
Unit verb: Examples: ate

63 64

Logic Programming 16
Simple English Syntax First Attempt at Parsing
The man ate the cake. sentence(S):-append(NP,VP,S),
noun_phrase(NP),verb_phrase(VP).
noun_phrase(NP):-append(Det,Noun,NP),
determiner(Det),noun(Noun).
verb_phrase(VP):-append(Verb,NP,VP),
verb(Verb),noun_phrase(NP).
determiner([a]). determiner([the]).
noun([man]). noun([cake]).
verb([ate]).

65 66

A Second Approach Prolog Grammar Rules


sentence(S,S0):-noun_phrase(S,S1), sentence --> noun_phrase, verb_phrase.
verb_phrase(S1,S0). noun_phrase --> determiner, noun.
noun_phrase(NP,NP0):- verb_phrase --> verb, noun_phrase.
determiner(NP,NP1),noun(NP1,NP0). determiner --> [a].
determiner --> [the].
verb_phrase(VP,VP0):-verb(VP,VP1),
noun --> [man].
noun_phrase(VP1,VP0).
noun --> [cake].
determiner([a|Rest],Rest). verb --> [ate].
determiner([the|R],R). noun_phrase --> determiner, adjectives, noun.
noun([man|R],R). noun([cake|R],R). adjectives --> adjective.
verb([ate|R],R). adjectives --> adjective, adjectives.
adjective --> [young].

67 68

Logic Programming 17
Prolog Grammar Rules Prolog Grammar Rules
Prolog enables you to write in: How to Extract a Parse Tree
sentence --> noun phrase, verb phrase. sentence([[np,NP],[vp,VP]]) --> noun_phrase(NP),
verb_phrase(VP).
and Prolog turns this into: noun_phrase([[det,Det],[noun,Noun]]) -->
sentence(S,S0):-noun_phrase(S,S1), determiner(Det), noun(Noun).
verb_phrase(S1,S0). determiner(the) --> [the].

And So what structure is returned from solving


adjective --> [young]. the goal:
sentence(Structure,[the,man,ate,a,cake],[])
into
adjective(A,A0):-'C'(A,young,A0). The result is:
'C'([H|T],H,T). [[np,[[det,the],[noun,man]]],[vp,[…

69 70

Special Control Predicate Special Control Predicate (continue)

Cut (!/0) Commit


On backtracking, all attempts to redo a subgoal to skin(X,Y) :- thai(X),!,Y=yellow.
the left of the cut results in the subgoal skin(X,Y) :- asia(X),!,Y=yellow.
immediately failing.
On backtracking, into the predicate once the call
had exited: if one of the clauses defining the
predicate had previously contained a cut that had
been executed then no other clauses for that
predicate may be used to resatisfy the goal being
redone.

71 72

Logic Programming 18
Special Control Predicate (continue) Special Control Predicate (continue)

Make determination Fail Goal Now


sum(1,1). \+ (Goal):- call(Goal),!,fail.
sum(N,Ans):- NewN is N-1, \+ (Goal).
sum(NewN,Ans1), woman(X):- man(X),! ,fail.
Ans is Ans1+N. woman(X).
sum(1,1):-!.
sum(N,Ans):- NewN is N-1,
sum(NewN,Ans1),
Ans is Ans1+N.

73 74

Changing the Program Changing the Program (continue)

assert(C): Assert clause C assert(man(bill)).


asserta(C): Assert C as first clause asserta(man(bob)).
assertz(man(jim)).
assertz(C): Assert C as last clause
retract(man(bob)).
retract(C): Erase the first clause of
abolish(man,1).
form C
abolish(Name,Arity): Abolish the
procedure named F with arity N

75 76

Logic Programming 19
Input/Output Input/Output and File
read/1 see/1: Take input from the named file
test:-read(X),double(X,Y), seen/0: Close the current input stream
write(Y),nl.
and take input from user
?- test.
|: 2. seeing/1: Returns name of current
4 input stream
yes

77 78

Input/Output and File (continue) Input/Output and File (continue)

test:-read(X),\+(X = -1), tell/1: Send output to the named file


double(X,Y),write(Y),nl,test.
told/0: Close the current output
go:-see(in),test,seen.
stream and send output to user
telling/1: Returns name of current
output stream

79 80

Logic Programming 20
Input/Output and File (continue) Prolog Examples
test:-read(X),\+(X = -1), move(state(middle,onbox,middle,hasnot),grasp,
state(middle,onbox,middle,has)).
double(X,Y),write(Y),nl,test. move(state(P,onfloor,P,H),climb,state(P,onbox,
go:-tell(out),see(in),test,seen, P,H)).
move(state(P1,onfloor,P1,H),push(P1,P2),
told. state(P2,onfloor,P2,H)).
move(state(P1,onfloor,B,H),walk(P1,P2),
state(P2,onfloor,B,H)).

81 82

Prolog Examples (continue)


depth_first(State,State,[]).
depth_first(StartState,GoalState,Ans) :-
findsuccessor(StartState,Successor,Operator),
depth_first(Successor,GoalState,Ans1),
Ans=[Operator|Ans1].

findsuccessor(OldState,NewState,Operator) :-
move(OldState,Operator,NewState).

83

Logic Programming 21

You might also like