artificial intelligence - prolog programming - ryo hatano jaist oct 16, 2012
TRANSCRIPT
Artificial Intelligence
- Prolog Programming -
Ryo HatanoJAIST
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 [email protected]
• Lecture matelials:https://www.jaist.ac.jp/~s1220010/
2
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
3
4
Reference
• I. Bratko, Prolog Programming for Artificial Intelligence• Shapiro et al, The Art of Prolog• P. Blackburn et al, Learn Prolog Now!• S. Russell et al, Artificial Intelligence A Modern Approach
• I. Bratko, Prolog への入門• 古川康一 他 , 帰納論理プログラミング• S. Russell 他 , エージェントアプローチ人工知能
You can find some books about Prolog in JAIST Library or online via Google.
( わかりやすい )
( 短くまとまっている )
(8 章が背景に詳しい )
(chap. 9 contains some background info)
(be available online)
(contains advanced topics)
(easy)
5
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
6
• 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
Simple Planning System
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 !
7
Monkey & Banana problem (details, for reference)
state(atdoor, onfloor, atwindow, hasnot)
state(atwindow, onbox, atwindow, hasnot)
state(P2’, onfloor, P2’, hasnot)
state(P2’, onbox, P2’, hasnot)
state(middle, onbox, middle, has)
walk(atdoor, P2)
push(atwindow, P2’)
climb
GraspP2’ = middle
state(P2, onfloor, atwindow, hasnot)
climb(onfloor, onbox)P2 = atwindow
state(atwindow, onfloor, atwindow, hasnot)
Backtrack(onbox→onfloor)
Other backtracks are ommitted
Overview of the Prolog
• Using of the Prolog environment• start, stop, load, execution
• Many Syntaxes– Basics
• Data structure, operators and recursion• Evaluation process
– Advanced• list, cut, syntax sugar, user defined operator,
extra logical predicates, set predicates, failure driven loop
8
Today’s Topics
and some samples
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…
9
10
About the Prolog environment
• Implementation– SICStus Prolog – SWI Prolog– GNU Prolog
• Development environment– Prolog mode of Emacs– PDT of Eclipse– Text editor + Prolog interpreter
Not free, performance is good, but not easy to use
Free, easy to use, recommend
Note: some built-in libraries are not same
11
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 “?-”.
?- [sample_1e.pl].% sample_1e.pl compiled 0.00 sec, 1,004 bytes?- foo(bar).true.
?- foo(X).X = bar;X = baz
?- halt.
←load program by short notation
←query which input by user
←If other answer exists, input “;” then search next answer
←load then compile
Example
12
Basic usage of the Prolog Environment (cont.)
• Start– %prolog [-l] [filename]
• Exit– 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.
In OS shell, -l is option for loading a prolog program
(See also: official manual)
13
Syntax of the Prolog program
• Arithmetic, Comparison, Substitution, User defined• Unification, Control of backtrack• Comment
Operators+
Data structures
Clauses
Head :- Body.
Predicate(Term, Term, …, Term)
Variable Constant Function
+ Some technics (ex. Recursion)
14
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.
/* Multi line comment*/foo(bar) %comment to end of the line
Example in Prolog programs
15
Syntax of the Prolog program
• Arithmetic, Comparison, Substitution, User defined• Unification, Control of backtrack• Comment
Operators+
Data structures
Clauses
Head :- Body.
Predicate(Term, Term, …, Term)
Variable Constant Function
+ Some technics (ex. Recursion)
16
• Prolog program consists of the set of “Horn clauses”– Horn clause is clause which has zero or one positive conclusion
• Prolog system has 3 types of clauses– Facts, Rules, Goals(Query)
Clauses
These formula are expressed to the form of Prolog In the real program
m
n
AAA
C
BAAA
21
21
Example in predicate logic
Program clauses
17
Example of Program
• Notation of clauses in Prolog
Head :- Body.
% All of these are horn clauses !vegetable(carrot).fruit(apple).vegetable(tomato). fruit(tomato).
plant(X) :- vegetable(X).plant(X) :- fruit(X).plant(X) :- fruit(X), vegetable(X).
?- plant(X).
Program
Interpreter
← Goal clauses(query)
Rule clauses
Fact clauses
It is equivalent to implication operator “→” in predicate logic.But the direction is opposite (Body→Head).
Write the period end of the each clauses
18
Fact clauses
vegetable(carrot). %Carrot is a kind of vegetablesfruit(apple). %Apple is a kind of fruitsvegetable(tomato). fruit(tomato). %Tomato is a kind of fruits and vegetables
Example of Prolog program
Explain about predicates is later
C
Equivalent form of predicate formula
• The clause express about the facts– Clauses has empty body (condition) ⇔ Head (conclusion) only.– It contains predicates and constants which value is always true
Empty value means “true” in Prolog system
19
Rule clauses
plant(X) :- vegetable(X).plant(X) :- fruit(X).plant(X) :- vegetable(X), fruit(X).
Example in Prolog programs
Equivalent form of predicate formula
• 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
BAAA n 21
Comma “,” means “and” condition.Semi colon “;” means “or” condition.
If there are some same heads of fact and rule clauses, it means “or” condition
Important notations are“ .” , “ ,” and “:-”.
20
Goal clauses
?- vegetable(carrot).true.
Example in interpreter (“Yes/No” type of query)
Equivalent form of predicate formula
• 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
←Query which ask the fact exists←System answers Yes or No
Example in interpreter (“What” type of query)
mAAA 21
Prolog system tries to find the answerof this arrow.
?- vegetable(X).X = carrot.
←Query which contains valiable←System answers the value of variable If the answer doesn’t exists, system answers error.
21
Syntax of the Prolog program
• Arithmetic, Comparison, Substitution, User defined• Unification, Control of backtrack• Comment
Operators+
Data structures
Clauses
Head :- Body.
Predicate(Term, Term, …, Term)
Variable Constant Function
+ Some technics (ex. Recursion)
22
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)
23
Atoms
• There are 3 types of atoms– Character string which starts with lower case or
number– Special character string +, -, *, /, <, >, =, :, ., &, _, ~– Quoted string
←This is exceptional case. It depends on environment
carrot.miss_mary.1234.======>.‘Mr. Tom’.日本語の定数 .
←If you need constants which starts with upper case, “‘” is suitable←Some atoms already used by system such as “:-”
Example of constants
There are some special constants such as “true”, “end_of_file”.It depends on environment.
24
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
←Anonymous variable excludes from evaluation
XResult_Arg1hoge( _ , X):- ...
Memory allocates when variables evaluated
Example of variables
25
Function
• Structural data which has some elements– Functor(Term1, Term2, …)– The naming rule is same as constants– The number of arguments calls “arity”– Function only refers other terms. It doesn’t have truth
value.
fruit(apple).plant(eatable(X)):- fruit(X).
Example of function
FunctorTerm
←Function and predicate are not same
Another name is “Compound term”
Predicate
Interpreter
?- plant(Func).Func = eatable(apple). ←It only directs other terms.
“ eatable(apple)” is not returns true.
26
Function (cont.)
• The data structure consider as tree– When all elements of some trees are same, they treat
as same data
Example of tree structure father(parent(X, Y), male(X))
father
parent male
X Y X
The root of tree calls to Principal functor
It depends on matching operation
27
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.
fruit(carrot).plant(X):- fruit(X).father(X):- parent(X, Y), male(X).
Example of predicates
Predicate symbol Terms
←It can contains some variables and constants.
28
Predicate (cont.)
• Distinguish the same predicate or not is by predicate symbol and arity– Short notation “predicate symbol/arity” has used
plant(X) :- vegetable(X).plant(Y) :- vegetable(Y), fruit(Y).
Example
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.
29
Syntax of the Prolog program
• Arithmetic, Comparison, Substitution, User defined• Unification, Control of backtrack• Comment
Operators+
Data structures
Clauses
Head :- Body.
Predicate(Term, Term, …, Term)
Variable Constant Function
+ Some technics (ex. Recursion)
30
Arithmetic operator
• X + Y Addition• X - Y Subtraction• X * Y Multiplication• X / Y Division• X // Y Quotient of the natural number division• X mod Y Remainder of the natural number division• X is Y Y substitute to X (Y need to be bind)
?- Result is 2 + 3.Result = 5.
?- Result = 2 + 3.Result = 2 + 3
Example of arithmetic formula
In general, the arithmetic operator writes in infix notation
←it is not correct. “ =” is not arithmetic operation. So it is not evaluated.
←example of correct arithmetic operation and substitution
31
Comparison operators
• X > Y X is greater than Y• X < Y X is less than Y• X >= Y X is greater than or equal to Y• X =< Y X is less than or equal to Y• X =:= Y (Arithmetic formula) value of X and Y are
equals• X =\= Y (Arithmetic formula) value of X and Y are
not equals• X == Y Terms X and Y are equals• X \== Y Terms X and Y are not equals
32
Unification
• X = Y Matching X and Y, then if it matches true otherwise false
Matching of the Prolog is near to predicate logic
?-date(_Day, _Month, 2012) = date(9, april, _Year)._Day = 9_Month = april_Year = 2012
Example of unification
←it returns most general solution
33
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 memoryWhen returns, the process take the values from memory
Example of recursion
factorial(0, 1).factorial(N, Result):-
N2 is N – 1,factorial(N2, Result2), Result is N * Result2.
←Stop condition. It needs to write above recursion.
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
34
35
Depth first backward search
%Definition of factsfruit(apple).fruit(tomato). vegetable(tomato).
%Definition of rulesplant(X) :- fruit(X).plant(X) :- vegetable(X).
InterpreterSource code
?- trace.true.
?- plant(X). Call: (6) plant(_G466) ? creep Call: (7) fruit(_G466) ? creep Exit: (7) fruit(apple) ? creep Exit: (6) plant(apple) ? creepX = apple
plant
fruit vegetable
It searches from query to defined factsby depth first
apple tomato tomato
Search tree
36
Unification
%Definition of factsfruit(apple).fruit(tomato). vegetable(tomato).
%Definition of rulesplant(X) :- fruit(X).plant(X) :- vegetable(X).
InterpreterSource code
?- trace.true.
?- plant(X). Call: (6) plant(_G466) ? creep Call: (7) fruit(_G466) ? creep Exit: (7) fruit(apple) ? creep Exit: (6) plant(apple) ? creepX = apple
plant
fruit vegetable
It matches variables and terms.The scope is only same clause.
apple tomato tomato
X= apple
Search tree
37
Backtracks
%Definition of factsfruit(apple).fruit(tomato). vegetable(tomato).
%Definition of rulesplant(X) :- fruit(X).plant(X) :- vegetable(X).
InterpreterSource code
X = apple ; Redo: (7) fruit(_G466) ? creep Exit: (7) fruit(tomato) ? creep Exit: (6) plant(tomato) ? creepX = tomato
plant
fruit vegetable
It backs to former branch then search other answers.
apple tomato tomato
Search tree
38
Closed world assumption
%Definition of factsfruit(apple).fruit(tomato). vegetable(tomato).
%Definition of rulesplant(X) :- fruit(X).plant(X) :- vegetable(X).
InterpreterSource code
?- plant(X).X = apple ;X = tomato ;X = tomato ;X = tomato.
?-
plant
fruit vegetable
There are no more things substitute to X.In the prolog, there are assumption whichMeans not defining things are all false.Therefore, the result of this example is false.
apple tomato tomato
←Waiting for next query
It is called closed world assumption
No more choices
Search tree