スライド 0

Artificial Intelligence
- Prolog Programming -
Ryo Hatano
JAIST
Oct 16, 2012
About this Lecture
• Today only
• No report, no examination today
– But midterm examination contains some quiz
about Prolog
• TA: Ryo Hatano, D1 student of Tojo lab
[email protected]
• Lecture matelials:
https://www.jaist.ac.jp/~s1220010/
1
Objectives
• Study about the basic usage of Prolog
– Understand the basics of logic programming
• Become able to study Prolog by yourself
– Today, I’ll teach only introduction
2
Reference
•
•
•
•
I. Bratko, Prolog Programming for Artificial Intelligence (easy)
Shapiro et al, The Art of Prolog (contains advanced topics)
P. Blackburn et al, Learn Prolog Now! (be available online)
S. Russell et al, Artificial Intelligence A Modern Approach
(chap. 9 contains some background info)
• I. Bratko, Prologへの入門 (わかりやすい)
• 古川康一 他, 帰納論理プログラミング (短くまとまっている)
• S. Russell 他, エージェントアプローチ人工知能 (8章が背景に詳しい)
You can find some books about Prolog in JAIST Library or online via Google.
3
What is the Prolog ?
• PROgrammation en LOGique
– Programming language which based on predicate logic
– The implementation is a kind of automated proving system
– It specializes in logical processing and knowledge
representation
• It suitable for the problems to handle relation between some objects
• Symbol processing is better
4
Simple Planning System
• There is a person in a room
• He wants to catch a banana hanging from a ceiling
• He have to find a way to the banana
Definition of predicates for solving
move(state(Before), command, state(After)).
state(X, Y, BOX, Has).
canget(state):←Recursion rule
The problem can solve using only these predicates!
5
Monkey & Banana problem (details, for reference)
state(atdoor, onfloor, atwindow, hasnot)
walk(atdoor, P2)
state(P2, onfloor, atwindow, hasnot)
climb(onfloor, onbox)
P2 = atwindow
state(atwindow, onbox, atwindow, hasnot)
Backtrack(onbox→onfloor)
state(atwindow, onfloor, atwindow, hasnot)
push(atwindow, P2’)
state(P2’, onfloor, P2’, hasnot)
climb
state(P2’, onbox, P2’, hasnot)
Grasp
P2’ = middle
state(middle, onbox, middle, has)
Other backtracks are ommitted
6
Overview of the Prolog
• Using of the Prolog environment
• start, stop, load, execution
• Many Syntaxes
– Basics
Today’s
Topics
• Data structure, operators and recursion
• Evaluation process
– Advanced
and some samples
• list, cut, syntax sugar, user defined operator,
extra logical predicates, set predicates, failure driven loop
7
Overview of the Prolog (cont, for reference)
• Theoretical Backgrounds
–
–
–
–
–
History
Formal Semantics of Prolog
Warren Abstract Machine
Herbrand’s Theorem
Evaluation Algorithms
• Advanced topics
– Meta programming (Higher order programming, Meta interpreter)
– Grammar parsing with DCG (Definition Clauses Grammar)
– Theorem proving and its application with user defined axiomatic
system
– Other Logic programming (Inductive logic programming,
Probabilistic logic programming)
– etc…
8
About the Prolog environment
• Implementation
– SICStus Prolog Not free, performance is good, but not easy to use
– SWI Prolog Free, easy to use, recommend
– GNU Prolog
Note: some built-in libraries are not same
• Development environment
– Prolog mode of Emacs
– PDT of Eclipse
– Text editor + Prolog interpreter
9
Basic Usage of the Prolog Environment
• Using interpreter
– You can control the prolog system interactively
– First we load the program first. Then input a query
after outputs of “?-”.
Example
?- [sample_1e.pl]. ←load program by short notation
% sample_1e.pl compiled 0.00 sec, 1,004 bytes ←load then compile
?- foo(bar).
←query which input by user
true.
?- foo(X).
X = bar;
X = baz
←If other answer exists, input “;” then search next answer
?- halt.
10
Basic usage of the Prolog Environment (cont.)
• Start
– %prolog [-l] [filename]
• Exit
In OS shell, -l is option for loading
a prolog program
– halt.
– Ctrl + ‘d’
• Interrupt and termination
– Ctrl + ‘c’ then ‘a’
• File load
– chdir(‘dir_path’). Change the current directory (ex.‘c:\\test’)
– consult[‘file_name’]. or [‘file_name’]. Execute the file load
• File reload
– make. Reload the edited file
• Trace
– trace. It shows all steps of evaluation. “notrace” is for exit.
(See also: official manual)
11
Syntax of the Prolog program
Data structures
Clauses
Head :- Body.
Predicate(Term, Term, …, Term)
Variable Constant Function
+
Operators
• Arithmetic, Comparison, Substitution, User defined
• Unification, Control of backtrack
• Comment
+
Some technics (ex. Recursion)
12
Comment
• One line comment
– From “%” to end of the line
• Multi line comment
– From “/*” to “*/”
Write the comment in the source code and give the readability.
It is important habit in software engineering.
Example in Prolog programs
/*
Multi line comment
*/
foo(bar) %comment to end of the line
13
Syntax of the Prolog program
Data structures
Clauses
Head :- Body.
Predicate(Term, Term, …, Term)
Variable Constant Function
+
Operators
• Arithmetic, Comparison, Substitution, User defined
• Unification, Control of backtrack
• Comment
+
Some technics (ex. Recursion)
14
Clauses
• Prolog program consists of the set of “Horn clauses”
– Horn clause is clause which has zero or one positive conclusion
Example in predicate logic
A1  A2    An  B
C
A1  A2    Am 
These formula are expressed to the form of Prolog
In the real program
• Prolog system has 3 types of clauses
– Facts, Rules, Goals(Query)
Program clauses
15
Example of Program
Program
% All of these are horn clauses!
vegetable(carrot).
fruit(apple).
Fact clauses
vegetable(tomato). fruit(tomato).
plant(X) :- vegetable(X).
plant(X) :- fruit(X).
plant(X) :- fruit(X), vegetable(X).
Rule clauses
Interpreter
?- plant(X).
← Goal clauses(query)
• Notation of clauses in Prolog
Write the period end of the each clauses
Head :- Body.
It is equivalent to implication operator “→” in predicate logic.
But the direction is opposite (Body→Head).
16
Fact clauses
• The clause express about the facts
– Clauses has empty body (condition)
⇔ Head (conclusion) only. Empty value means “true” in Prolog system
– It contains predicates and constants which value is always true
Explain about predicates is later
Example of Prolog program
vegetable(carrot). %Carrot is a kind of vegetables
fruit(apple). %Apple is a kind of fruits
vegetable(tomato). fruit(tomato). %Tomato is a kind of fruits and vegetables
Equivalent form of predicate formula
C
17
Rule clauses
• The clauses express about rules
– The clause has head and non empty body
– It offers the function of Modus Ponens like implication operator
– True/False value is depends on the contents of the body
Example in Prolog programs
plant(X) :- vegetable(X).
plant(X) :- fruit(X).
plant(X) :- vegetable(X), fruit(X).
Comma “,” means “and” condition.
Semi colon “;” means “or” condition.
If there are some same heads of fact and rule clauses, it means “or” condition
Equivalent form of predicate formula
A1  A2   An  B
Important notations are
“.”, “,” and “:-”.
18
Goal clauses
• The clause express about query
– The clause has only body
– It consists of at least one goal
– There are 2 types of queries
• Yes/No type, What type
Example in interpreter (“Yes/No” type of query)
?- vegetable(carrot).
true.
←Query which ask the fact exists
←System answers Yes or No
Example in interpreter (“What” type of query)
←Query which contains valiable
←System answers the value of variable
If the answer doesn’t exists, system answers error.
Equivalent form of predicate formula
Prolog system tries to find the answer
A1  A2   Am 
of this arrow.
?- vegetable(X).
X = carrot.
19
Syntax of the Prolog program
Data structures
Clauses
Head :- Body.
Predicate(Term, Term, …, Term)
Variable Constant Function
+
Operators
• Arithmetic, Comparison, Substitution, User defined
• Unification, Control of backtrack
• Comment
+
Some technics (ex. Recursion)
20
Data structures
• All data objects treats as “term” in Prolog system
• There are 3 types of terms
– Constant
– Variable
– Function (= It is the complex data structure which
consists of some elements)
21
Atoms
• There are 3 types of atoms
– Character string which starts with lower case or
number
– Special character string +, -, *, /, <, >, =, :, ., &, _, ~
– Quoted string
Example of constants
carrot.
miss_mary.
1234.
←Some atoms already used by system such as “:-”
======>.
←If you need constants which starts with upper case, “‘” is suitable
‘Mr. Tom’.
日本語の定数. ←This is exceptional case. It depends on environment
There are some special constants such as “true”, “end_of_file”.
It depends on environment.
22
Variables
• There are 2 types of variables
– Normal variables which starts with upper case or
under score
– Anonymous variables which only express in under
score
• Temporary name of variables which appears only one time in
the clause
• When it appear, it allocates different number by the system
• Anonymous variables in query ignores when answer
Example of variables
X
Result
_Arg1
hoge( _ , X):- ...
←Anonymous variable excludes from evaluation
Memory allocates when variables evaluated
23
Function
• Structural data which has some elements
–
–
–
–
Functor(Term1, Term2, …) Another name is “Compound term”
The naming rule is same as constants
The number of arguments calls “arity”
Function only refers other terms. It doesn’t have truth
value.
Example of function
fruit(apple).
plant(eatable(X)):- fruit(X). ←Function and predicate are not same
FunctorTerm Predicate
Interpreter
?- plant(Func).
Func = eatable(apple).
←It only directs other terms.
“eatable(apple)” is not returns true.
24
Function (cont.)
• The data structure consider as tree
– When all elements of some trees are same, they treat
as same data
It depends on matching operation
Example of tree structure father(parent(X, Y), male(X))
father
parent
X
Y
The root of tree calls to Principal functor
male
X
25
Predicates
• Structural data which express relation between
terms
– Predicate symbol(Term1, Term2, …)
– The naming rule is same as constants
– Predicate symbols and terms constructs atomic
formula. It has truth value.
Example of predicates
fruit(carrot).
←It can contains some variables and constants.
plant(X):- fruit(X).
father(X):- parent(X, Y), male(X).
Predicate symbol Terms
26
Predicate (cont.)
• Distinguish the same predicate or not is by
predicate symbol and arity
– Short notation “predicate symbol/arity” has used
Example
plant(X) :- vegetable(X).
plant(Y) :- vegetable(Y), fruit(Y).
Body and variable name are same, but each predicate
Treat as same by plant/1
Note: The problem of distinguish predicates and
tree structure of functions are not same.
27
Syntax of the Prolog program
Data structures
Clauses
Head :- Body.
Predicate(Term, Term, …, Term)
Variable Constant Function
+
Operators
• Arithmetic, Comparison, Substitution, User defined
• Unification, Control of backtrack
• Comment
+
Some technics (ex. Recursion)
28
Arithmetic operator
•
•
•
•
•
•
•
X+Y
X- Y
X* Y
X/ Y
X // Y
X mod Y
X is Y
Addition
Subtraction
Multiplication
Division
Quotient of the natural number division
Remainder of the natural number division
Y substitute to X (Y need to be bind)
Example of arithmetic formula
?- Result is 2 + 3.
Result = 5.
←example of correct arithmetic operation and substitution
?- Result = 2 + 3.
Result = 2 + 3
←it is not correct. “=” is not arithmetic operation.
So it is not evaluated.
In general, the arithmetic operator writes in infix notation
29
Comparison operators
•
•
•
•
•
X>Y
X<Y
X >= Y
X =< Y
X =:= Y
equals
• X =\= Y
equals
• X == Y
• X \== Y
X is greater than Y
X is less than Y
X is greater than or equal to Y
X is less than or equal to Y
(Arithmetic formula) value of X and Y are
(Arithmetic formula) value of X and Y are not
Terms X and Y are equals
Terms X and Y are not equals
30
Unification
• X=Y
Matching X and Y, then if it matches true
otherwise false
Example of unification
?-date(_Day, _Month, 2012) = date(9, april, _Year).
_Day = 9
_Month = april
←it returns most general solution
_Year = 2012
Matching of the Prolog is near to predicate logic
31
Recursion
• The evaluation process calls itself
– The rule which calls itself in the body
– Usually, it uses as loop
– The condition (address of variables and values) of each
predicates are saved on memory
When returns, the process take the values from memory
Example of recursion
←Stop condition. It needs to write above recursion.
factorial(0, 1).
factorial(N, Result):N2 is N – 1,
factorial(N2, Result2),
Result is N * Result2.
32
Outline of the evaluation process
• Prolog system is a kind of automated theorem
proving system
• It mainly consists of 4 technics
–
–
–
–
Depth first backward search
Unification
Backtracks
Closed world assumption
33
Depth first backward search
Source code
Interpreter
?- trace.
true.
%Definition of facts
fruit(apple).
fruit(tomato).
vegetable(tomato).
?- plant(X).
Call: (6) plant(_G466) ? creep
Call: (7) fruit(_G466) ? creep
Exit: (7) fruit(apple) ? creep
Exit: (6) plant(apple) ? creep
X = apple
%Definition of rules
plant(X) :- fruit(X).
plant(X) :- vegetable(X).
Search tree
plant
fruit
apple
vegetable
tomato
It searches from query to defined facts
by depth first
tomato
34
Unification
Source code
Interpreter
?- trace.
true.
%Definition of facts
fruit(apple).
fruit(tomato).
vegetable(tomato).
?- plant(X).
Call: (6) plant(_G466) ? creep
Call: (7) fruit(_G466) ? creep
Exit: (7) fruit(apple) ? creep
Exit: (6) plant(apple) ? creep
X = apple
%Definition of rules
plant(X) :- fruit(X).
plant(X) :- vegetable(X).
Search tree
plant
X= apple
fruit
apple
vegetable
tomato
It matches variables and terms.
The scope is only same clause.
tomato
35
Backtracks
Source code
Interpreter
%Definition of facts
fruit(apple).
fruit(tomato).
vegetable(tomato).
X = apple ;
Redo: (7) fruit(_G466) ? creep
Exit: (7) fruit(tomato) ? creep
Exit: (6) plant(tomato) ? creep
X = tomato
%Definition of rules
plant(X) :- fruit(X).
plant(X) :- vegetable(X).
Search tree
plant
fruit
apple
It backs to former branch then search
other answers.
vegetable
tomato
tomato
36
Closed world assumption
Source code
Interpreter
%Definition of facts
fruit(apple).
fruit(tomato).
vegetable(tomato).
?- plant(X).
X = apple ;
X = tomato ;
X = tomato ;
X = tomato.
%Definition of rules
plant(X) :- fruit(X).
plant(X) :- vegetable(X).
Search tree
plant
fruit
apple
?-
vegetable
tomato
tomato
←Waiting for next query
There are no more things substitute to X.
In the prolog, there are assumption which
Means not defining things are all false.
Therefore, the result of this example is false.
It is called closed world assumption
No more choices
37